AJAX POST method to Spring RestAPI not working - java

I'm trying to send a large form of data to my server side, using jQuery AJAX and sending it to a RESTful service made in the Spring Framework. And the form as arrays of unknown sizes, so am trying to get the auto serializing to work. But I can't even get it to work with a simple test example.
It seems to not be able to match my JSON file to the input class. So I must be doing something wrong. But I have not been able to see what I'm doing wrong based on the tutorials I have been trying to follow.
Here is my AJAX call
var test = JSON.stringify({
name : "hallo", lastname : "there"
});
console.log(test);
$.ajax({
type: "POST",
url: "/SpringTest_war_exploded/test",
contentType: "application/json",
data: test,
success: function (returnValue) {
console.log("success");
console.log(returnValue);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log (XMLHttpRequest);
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
Here is my server-side method.
#PostMapping(value = "/test", consumes = "application/json")
#ResponseBody
public String testajax(#RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
Here is the class I'm trying to match it with
public class TestAutoCreate {
private String name;
private String lastname;
public TestAutoCreate(String name, String lastname) {
this.name = name;
this.lastname = lastname;
}
// the getters and setters
...
}
And here is the error massage I get
The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
If I remove the #RequestBody TestAutoCreate test from the server side method, then the call works fine. It is only

The problem at here
#PostMapping(value = "/test", consumes = "application/json")
#ResponseBody
public String testajax(#RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
It is RESTful controller, but return view. You must return RESTful response, what has content type is Content-Type: application/json .
See authority example: https://spring.io/guides/tutorials/rest/

Related

Spring Boot #RestController no respond

I'm starting with Spring and REST application. Currently, I'm developing one application on my own and I stuck.
The app is divided just like standard Spring Boot project. All of the controllers are contained in web package.
One of "standard" controller is responsible for handling HTTP request and returning an HTML website. I have added a REST controller which should respond to POST request from the first controller, but I receive a 404 error.
How it looks like in code?
#RestController
#RequestMapping("/users")
public class UserRestController {
#Autowired
private UserService userService;
#RequestMapping(value = "/user", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public ResponseEntity<?> getUser(#RequestParam("userId") String userId, Errors errors) {
AjaxUser response = new AjaxUser();
if (errors.hasErrors()) {
response.message = errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(","));
return ResponseEntity.badRequest().body(response);
}
response.setUser(userService.getUserById(Integer.getInteger(userId).intValue()));
return ResponseEntity.ok(response);
}
private class AjaxUser {
private User user;
private String message;
public void setUser(User user) {
this.user = user;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
#Override
public String toString() {
return "User { id:" + user.getId() + ", Name: " + user.getName() + ", surname: " + user.getSurname() + "}";
}
}
}
From .js file I send a ajax query which should trigger a rest controller, here is the code:
function sendUserId(id) {
var user = {};
user["userId"] = id;
console.log("USER: ", user);
$.ajax({
type: "POST",
contentType: "application/json",
url: "/users/user",
data: JSON.stringify(user),
dataType: 'json',
cache: false,
timeout: 100000,
success: function (user) {
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(user, null, 4) + "</pre>";
console.log("SUCCESS : ", user);
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
console.log("ERROR : ", e);
}
});
}
userId is taken from a html by jQuery, console.log show existing and right value.
Note: There exist a standard user #Controller which is responsible for displaying a user list, it works, problem appear during sending a user id to REST controller. It behaves just like the REST controller doesn't exist and browser return 404 status response. Btw, page use a Spring Secure to login and so on.
Could someone help?
BR Konrad
The controller is looking to have a request parameter that you are missing in the js requesting url
/users/user?userId=1
You can get a user by id like below:
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(#PathVariable("id") int id) {
User user = userService.findById(id);
if (user == null) {
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
So your rest entry point is /users/userid, eg: /users/1
Found this from the post Spring MVC RESTFul Web Service CRUD Example
the problem based on function arguments, REST controller should take String argument and next parse it to JSON object, the response should be String too. Topic can be closed, thanks all to be involved.

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.

Why does Spring MVC respond with 415 for an Ajax query requesting JSON?

I've read 3/4 posts on Stack plus many other examples to try figure this out but I've no clue ! Need some pointers please !!
Creating my first Ajax update through Spring-MVC and I keep getting a Status 415 being returned by my submission with The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request accept
JQuery... Version 3.1.1
function updateScore () {
$("div#results").append("<p>Posting User/Game ID " + this.id + " Value " + this.value + "</p>");
var prediction = {}
prediction["id"] = this.id;
prediction["value"] = this.value;
$.ajax({
type : "POST",
contentType : "application/json",
url : "/tournament/setPrediction.html",
data : JSON.stringify(prediction),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
displayResult(data, "success");
},
error : function(e) {
console.log("ERROR: ", e);
displayResult(e, "error");
},
done : function(e) {
console.log("DONE");
displayResult(true, "done");
}
});
}
Controller... Spring version 4.3.5
#RestController
public class PredictionAjaxController {
#ResponseBody
#RequestMapping(value = "/setPrediction.html", consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST, headers="Accept=application/json")
public Prediction setUserPrediction(#RequestBody PredictionPojo prediction) {
Prediction result = new Prediction();
System.out.println("AJAX call made in controller");
return result;
}
}
Finally a very simple POJO for the JSon to map to
public class PredictionPojo {
private String id;
private String value;
Getters & Setters... ()
}
I've added different things onto the controller now to try and resolve, didn't start with it all ! I'm completely confuddled !
Should be so simple...
DH
You have an error in your ajax call, you are sending a string instead of a JSON object. Also I don't think is necessary to specify the consumes and headers attributes in you #RequestMapping annotation in your setUserPrediction method, The PredictionAjaxController is already defined as a RestController. Your ajax should be:
$.ajax({
// .......
data : prediction,
// .......
});

Spring REST webservice with JSON param to be consumed using Jquery AJAX

I am trying to learn Spring Framework for creating RESTful web service for my future projects. So far I have tried using GET and consume it with no problem using a simple Ajax request. I have also tried using query strings to input parameters.
As of now I am trying to create an endpoint that receives a POST request. I've been researching for some days now but to no avail (some tuts are too complicated for a beginner like me).
Here is my simple code:
Java Spring
#RequestMapping(value = "/test", method = RequestMethod.POST)
#ResponseBody
public String testString(String jsonString)
{
System.out.println(jsonString);
return jsonString;
}
Ajax
var data = {"name":"John Doe"}
$.ajax({
url: "http://localhost:8080/springrestexample/test",
method:"POST",
data:data,
dataType:'text',
success: function( data ) {
alert(data);
},
error: function( xhr, status, errorThrown ) {
alert("Error:" + errorThrown + status);
}
});
I have tried debugging tomcat and it seems like I am not passing any value on the testString. Do I need to add something on my java code?
#RequestMapping only maps your method to some url.
To access data you need #RequestParam annotation to get data, eg:
#RequestMapping(value = "/test", method = RequestMethod.POST)
#ResponseBody
public String testString(#RequestParam("name") String jsonString)
{
System.out.println(jsonString);
return jsonString;
}
Look at this manual for more examples.
Since you are passing data into body from your ajax request, so you need to retrieve from the
#RequestBody
Add this annotation before the arguments like this way;
public String testString(#RequestBody String jsonString) {
System.out.println(jsonString);
return jsonString;
}
And you are done :)

How to correctly handle this AJAX request that send an array to a Spring MVC controller method? Why it can't work?

I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}

Categories