Http status 404 (Not Found) on jquery ajax GET to spring controller? - java

My spring controller contains such get handler :
#RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Region> getRegionsFor(#RequestParam(value = "countryName") String countryName,
#RequestParam(value = "geonameId") Long geonameId) {
logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
RegionInfo regionInfo = restTemplate.getForObject(
"http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
RegionInfo.class, geonameId);
return regionInfo.getRegions();
}
#Controller is mapped to /hostel. So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754
When I type in chrome browser
http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754
It returns json response as expected!!!
But I want to access this url with the following ajax call made with jquery:
$.ajax({
headers : {
'Accept' : 'application/json'
},
url : '/hostel/country',
dataType : 'json',
data : {countryName:"Albania",geonameId:783754},
type : 'GET',
async : true,
success : function(response) {
console.log("response=" + response.join(','));
},
error : function(errorData) {
console.log("data on fail ");
printObject(errorData);
}
});
As you guess this doesn't work at all. Http status 404 (Not Found) is returned to error: handler .
How can I solve this?

The url in the ajax call is relative to the hostname. You need to add your web application context
url : '/HostMe/hostel/country',

Related

POSTing data return error instead of success

I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}

Error 415 with Ajax request(Ajax, Spring)

I send Ajax request to my server, but server doesn't get responce.
PUT request:
function editNavigation() {
var flight={
id:idAction.replace('edit',''),
navigation:newNavigation
};
console.log(flight);
var prefix = '/airline/';
$.ajax({
type: 'PUT',
url: prefix +'flights/' + idAction.replace('edit',''),
data: JSON.stringify(flight),
headers:{contentType: "application/json"},
success: function(receive) {
$("#adminTable").empty();
$("#informationP").replaceWith(receive);
$("#hiddenLi").removeAttr('style');
},
error: function() {
alert('Error edited flight');
}
});
}
Controller:
#RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String updateFlight(#PathVariable("id") String id, #RequestBody FlightDto flightDto) {
String returnText = "Flight edited successful";
String str1 = flightDto.getNavigation();
logger.info(str1);
String str2 = id;
logger.info(str2);
return returnText;
}
Browser console:
Object {id: "5", navigation: "sdf"}
PUT http://localhost:8080/airline/flights/5 415 ()
Why I get error 415?
Why my controller doesn't send responce?
415 resonance code is Unsupported Media Type.
If your service expect POST(or any kind) request and if user send
PUT request then server will give this kind of response.
if user send wrong MediaType then also this type of error comes.
In your code, I think you have configure wrong MediaType which is APPLICATION_JSON_VALUE. you can specify MediaType.APPLICATION_JSON.
I think this will helps.

Send json object with another parmeter to the controller in spring mvc

1.- I want to recive this two paramters like this in my controller :
*/Controller
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST)
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
String table_name = tableName;
String catalogInserted = catalogGenericService.insertCatalogGeneric( table_name, catalogGeneric);
return catalogInserted;
}
2.- I send to the contoller in this way...
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: {'catalogGeneric' : JSON.stringify(description_data) , 'tableName' : "fadsf"},
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
3.- In my debug I receive error 400 not found the direction .... i know that is for the way that i send the parameters , but what will be the correct form to do that ?
In your case, Ajax call having contentType: "application/json" format, So when your doing ajax call with JSON format, In your Controller your Request Mapping should have consumes = "application/json",
For the particular request mapping add like this in your controller,
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST,
consumes = "application/json")
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
[Additional]
For safe request body format
try to stringify the whole JavaScript Object.
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: JSON.stringify({'catalogGeneric' : description_data , 'tableName' : "fadsf"}),
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
}
});

How can I pass a JSON object from Javascript to Java

What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}

Pass JSON as Java Class to Spring Controller by GET

I have the following code that works:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassPost(#RequestBody ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and the corresponding ajax call by post:
$.ajax({
url: '/jsonasclass/',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
}),
contentType: 'application/json',
mimeType: 'application/json',
success: _callBack,
error: _errorCallback
});
Now I want to achieve the same thing, but I want to do it by GET. Anyone knows how?
I have tried changing POST to GET (in both controller and ajax call) but it did not work.
The error I get: description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thanks to RaulRene's comment here is how you would do it.
get rid of #RequestBody from the controller and change method to get.
send the properties of the class in the controller as browser variables and spring will automatically map them to the class.
Here is the solution:
#RequestMapping(value = "/jsonasclass", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
ContactVO jsonAsClassGet(ContactVO ct){
ct.setFirstName("This-property-is-changed-in-the-controller");
return ct;
}
and corresponding ajax:
$.ajax({
url:'/jsonasclass/',
type: 'GET',
data: {
id:1,
userID:1.1,
login:'sample-login',
firstName:'sample-first-name'
},
success: _callBack,
error: _errorCallback
});

Categories