I am newbie in Spring. I generate the JSON like below:
[
{
"customer" : "16", "project" : "19",
"phase" : "47", "approver" : "5",
"date1" : "", "date2" : "",
"date3" : "", "date4" : "",
"date5" : "", "date6" : "",
"date7" : "", "activity" : "1"
},
{
"customer" : "17", "project" : "20",
"phase" : "48", "approver" : "3",
"date1" : "", "date2" : "",
"date3" : "", "date4" : "",
"date5" : "", "date6" : "",
"date7" : "", "activity" : "1"
}
]
I am passed this JSON to my Spring controller:
$.ajax({
type: 'post',
url: 'NewTimesheet',
dataType : 'json',
data: JSON.stringify(jsonObj),
success: function(data) {
console.log(data);
}
});
I am mapped the request to controller like below:
#RequestMapping(value="NewTimesheet", headers = { "Content-type=application/json" })
#ResponseBody
public String addNewTimesheet(#RequestBody List<Timesheet> timesheet,
HttpSession session) {
logger.info("timesheet list size is" + timesheet.size());
return "success";
}
Timesheet class:
public class Timesheet {
private String project;
private String phase;
private String approver;
private String customer;
private String date1;
private String date2;
private String date3;
private String date4;
private String date5;
private String date6;
private String date7;
private String activity;
//Getters and setters
}
But my request is not mapped with the conroller. My console displays like below:
WARN
org.springframework.web.servlet.PageNotFound.handleNoSuchRequestHandlingMethod:142
- No matching handler method found for servlet request: path '/NewTimesheet', method 'POST', parameters
map['[{"customer":"16","project":"19","phase":"47","approver":"5","date1":"","date2":"","date3":"","date4":"","date5":"","date6":"","date7":"","activity":"1"},{"customer":"17","project":"20","phase":"48","approver":"3","date1":"","date2":"","date3":"","date4":"","date5":"","date6":"","date7":"","activity":"1"}]'
-> array['']]
How to map my JSON to controller? Any help will be greatly appreciated!!!
You need to annotate the class as Controller, add a RequestMapping in your class and the HTTP method your calling in your method.
#Controller
#RequestMapping("/NewTimesheet")
public class MyClassName {
#RequestMapping(value={ "", "/" }, method = RequestMethod.POST, headers = { "Content-type=application/json" })
#ResponseBody
public String addNewTimesheet(#RequestBody List<Timesheet> timesheet,HttpSession session){
logger.info("timesheet list size is"+timesheet.size());
return "success";
}
}
Change #RequestBody to #ModelAttribute before the list in the controller. And in your json, put 'timesheet.' before every field, that is, timesheet.customer,timesheet.project.... such like that. That would work.
You need to define method=post. also I added produces = "application/json"
#RequestMapping(value="NewTimesheet", method = RequestMethod.POST, produces = "application/json")
#ResponseBody
public String addNewTimesheet(#RequestBody List<Timesheet> timesheet,HttpSession session){
logger.info("timesheet list size is"+timesheet.size());
return "success";
}
A couple things that might be causing problems for you:
Make sure you have all of the necessary dependencies for Jackson. For Maven, this would be:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
You don't need to stringify your JavaScript object, this is done implicitly. You should also name your submitted variable, since it must map to the domain object:
$.ajax({
method : 'post',
url : 'NewTimesheet',
dataType : 'json',
data:{ 'timesheet': jsonObj },
success : function(data) {
console.log(data);
}
});
Your controller should be configured to explicitly handle a POST request. Setting the accepted content type in the headers is not necessary. Also, I believe you need to map your domain objects to an array and not a list:
#RequestMapping(value="NewTimesheet", method = RequestMethod.POST)
public #ResponseBody String addNewTimesheet(#RequestParam("timesheet") Timesheet[] timesheet,HttpSession session){
logger.info("timesheet list size is"+timesheet.length);
return "success";
}
If you are using a relatively recent version of Spring MVC, there is no additional configuration required to handle requests for and producing JSON. Your AJAX request specifies a JSON response, which Spring will recognize and delegate to Jackson for serializing the input and output.
In my ajax request i added the contentType:application/json.After adding this controller mapped my ajax request.Thanks for all.
Related
Here is my code ,I'm trying to pass the user details as a json input but I'm not able to receive the data in my rest api method. I"m getting all values as null,
this is my json request
{
"userId" : "12345",
"username" : "arun.ammasai",
"createdBy" : "-2",
"updatedBy" : "-2",
"statusCd" : "New",
"createdDate" : "2019-03-03",
"updatedDate" : "2019-03-03"
}
====================================================================
#RequestMapping(value = "/registerUser", method = RequestMethod.POST, consumes = { "application/JSON", "application/XML" })
private String registerUser(User user) {
System.out.println(user.toString());
return "User Created";
}
====================================================================
here is the response in Postman Client
Unexpected 'U'
Update your method signature with #RequestBody annotation. It will automatically deserialize your json into java entity. Be carefull, names in json should be the same as parameters in User object and User object should have getters and setters. So your method should look like
#RequestMapping(value = "/registerUser", method = RequestMethod.POST, consumes = { "application/JSON", "application/XML" })
private String registerUser(#RequestBody User user) {
System.out.println(user.toString()); //What is the reason of doing toString of java Object?
//better to do System.out.println(user.getUsername())
return "User Created";
}
I'm learning to pass a JSON object through ajax to a Spring Controller.
Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/
From that point i added a #RequestMapping to the Controller:
#RequestMapping(value = "/get-user-list", method = RequestMethod.POST)
public #ResponseBody String testPost(#RequestBody ResourceNumberJson resourceNumberDtoJson) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>> I AM CALLED");
return "111";
}
Then i'm forming my ajax post:
var json = {
"login" : "login",
"resource_number" : "111",
"identifier" : "1111",
"registrator_number" : "11111111111111"
};
console.log(JSON.stringify(json));
$.ajax({
type : "POST",
url : "/get-user-list",
dataType : "text",
data : JSON.stringify(json),
contentType : 'application/json; charset=utf-8',
mimeType: 'application/json',
success: function(data) {
alert(data.id + " " + data.name);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
which is runned from "get-user-list" page.
When i'm trying to run this, i recieve a HTTP 415 error. Spring 4, Jackson 2.4
Cant understand what i'm doing wrong.
HTTP 415 means, that the media type is not supported.
Try changing your #RequestMapping annotation to
#RequestMapping(value = "/get-user-list",
method = RequestMethod.POST,
consumes="application/json")
You should also consider testing your REST-service with a client like RESTClient, Postman or even cURL to make sure it is working correctly before you start implementing the jQuery client.
I am using spring mvc. I need to pass a json object from my jsp page to controller.
My ajax code:
function createJSON() {
jsonObj = [];
item = {};
$(".values").each(function() {
var code = $(this).attr('id');
item[code] = $('#' + code).val();
});
var content=JSON.stringify(item)
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
url: "/pms/season/submit",
data: content,
dataType: "json",
success : function(data) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
My controller code:
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json) {
System.out.println( "json ::::"+json );
}
But it's not working.
#RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...
I think you intend to get the request body, i.e. #RequestBody.
I would then suggest that, unless you really need the raw JSON string, you would have the #RequestBody translated to a Java object for you:
public void saveNewUsers(#RequestBody MyDto myDto) {
...
}
where MyDto would have getters/setters and fields matching the JSON class.
You can over omit the #RequestBody annotation if you annotate the controller with #RestController, instead of #Controller.
If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc #ResponseBody
I have a JSON object like as follows:
[
{
"usernameid": [
"2",
"7"
],
"phaseid": [
"2",
"7"
],
"weekstartdate": "2014-11-02"
}
]
I try to map this JSON in a POJO in my controller:
public ModelAndView approveTimesheet(#RequestBody ApproveTimesheet timesheet,HttpSession session)
{
logger.info("yes");
}
My AJAX Call:
$.ajax({
type : 'post',
url : 'PendingTimesheet',
contentType : "application/json; charset=utf-8",
data : JSON.stringify(jsonObj),
success : function(data) {
},
});
POJO class:
public class ApproveTimesheet
{
private String[] usernameid;
private String[] phaseid;
private String weekstartdate;
//Getters and Setters
}
I am getting the below exception
out of START_ARRAY token
at [Source: org.apache.catalina.connector.CoyoteInputStream#7097326d; line: 1, column: 1]
How to correctly map the above JSON request in Spring controller?
Any Ideas will be greatly appreciated.
You are sending an array of JSON objects and not a singleton one.
Your controller signature should then hold a Collection or Array of ApproveTimesheet on front of the #RequestBody annotation. (I would suggest using arrays to avoid generic types mismatch):
public ModelAndView approveTimesheet(
#RequestBody ApproveTimesheet[] timesheets,
HttpSession session)
{
for(int i = 0; i < timesheets.length; i++)
{
logger.info(timesheets[i]);
}
//...
}
I am new to Spring . From my previous search in google says that we can send JSON data to the Spring Controller using the #RequestBody and we can get the data in the controller.
But when I used the #RequestBody , It doesn't allow the request to the controller .
function sendJSON(){
var jsonData = {"name":"XXX","age":"20","hobby":"TV"};
/alert("json Data : \n\n\n"+jsonData);
$.ajax({
type: 'POST',
dataType: 'json',
url: contexPath + "/sender.html",
//dataType: "html",
//contentType: "application/x-www-form-urlencoded; charset=utf-8",
contentType: "application/json"
data : JSON.stringify(jsonData),
success: function(data, textStatus ){
alert("success");
$("#result").html(data.name+"data.age+" "+data.hobby);
},
error: function(xhr, textStatus, errorThrown){
//alert('request failed'+errorThrown);
}
});
}
My controller will be ,
#RequestMapping(value = "sender.html", method=RequestMethod.POST)
public #ResponseBody Person sendMessage(#RequestBody Persons person){
System.out.println("Test..........");
System.out.println(person.getName()+ " "+person.getAge()+" "+person.getHobby()+"\n");
return persons;
}
But my request blocks.
Am I sending the correct json data to the controller that matches the java bean ?
Hope our stack users will help me.
You need jackson-mapper-asl on your classpath. If you use maven add this to your pom:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
Please check your java bean class name that matches the JSON data.
You have multiple errors in the code. I've assumed that you're using this kind of Person:
public class Person {
private int age;
private String hobby;
private String name;
/* omitted getters/setters */
}
It's a little bit unclear form your code what do you want your controller to return - single person or a list of them. I've changed it to return one person:
#RequestMapping(value = "sender.html", method = RequestMethod.POST)
public #ResponseBody
Person sendMessage(#RequestBody Person person) {
System.out.println("Test..........");
System.out.println(person.getName() + " " + person.getAge() + " " + person.getHobby() + "\n");
return person;
}
And now the javascript. Instead of contextPath you can just use url without starting slash. There was also missing comma and wrong quotation marks. Here is the corrected version:
var jsonData = {
"name" : "XXX",
"age" : "20",
"hobby" : "TV"
};
$.ajax({
type : 'POST',
dataType : 'json',
url : "sender.html",
contentType : "application/json",
data : JSON.stringify(jsonData),
success : function(data, textStatus) {
alert("success");
$("#result").html(data.name + data.age + data.hobby);
}
});
Do not use JSON.stringify on your data. You should use the plain javascript object. Then, if it still does not work, look at the logs, maybe your json model does not match your java bean.
Shouldn't the content type be "application/json" and not "application/form encoded". Have you tried changing it. Its strange that you don't get any server side exceptions. What response do you get back?
It's hard to say without seeing your Person and Persons objects. You could turn on the debugging for spring. I find it very helpful. From my log4j config
<logger name="org.springframework.web.servlet.mvc" >
<level value="debug" />
</logger>
I would also check in Firebug or the Chrome dev tools that you are sending the correct payload to the server.