JQuery sends JSON to Spring MVC controller

I cannot send a JSON object with jQuery Ajax to a Spring MVC controller. This is the definition of my controller method:

@Controller @RequestMapping(value = "InboxViewTemplate") public class InboxViewController { @ResponseBody @RequestMapping(value = "updateInboxView") public String updateInboxView(HttpServletRequest request, InboxView inboxView) { ... } 

then I'm trying to call this query:

 $.ajax({ dataType: 'json', contentType: "application/json", url: ctx + "/InboxViewTemplate/updateInboxView", data: ({inboxView : {createUser:"dave"}}), success: function(data) { $("#updateInboxView").html(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR + " : " + textStatus + " : " + errorThrown); } }); } 

but the JSON object is not passed. Can anybody help me? Thanks in advance.

+4
source share
2 answers

First of all, your controller does not know where to look for InboxView. Is this a query parameter? Path param? Request a body?

Secondly, you probably want to change your json request type to POST or PUT, as you are updating the data, not just retrieving it.

So something like this:

 @Controller @RequestMapping(value = "InboxViewTemplate") public class InboxViewController { @ResponseBody @RequestMapping(value = "updateInboxView", method = RequestMethod.POST) public String updateInboxView(HttpServletRequest request, @RequestBody InboxView inboxView) { ... } 

and

 $.ajax({ dataType: 'json', contentType: "application/json", url: ctx + "/InboxViewTemplate/updateInboxView", type: 'POST', data: JSON.stringify({inboxView : {createUser:"dave"}}), //if no JSON is available use the one from https://github.com/douglascrockford/JSON-js success: function(data) { $("#updateInboxView").html(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR + " : " + textStatus + " : " + errorThrown); } }); } 

must work.

I assume that you have configured json message converter correctly.

change This means that you have:

 <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter"/> </list> </property> </bean> 

or something equivalent for other message converters in your spring xml configuration.

+8
source

You saw your log file to find out reason 404. I suspect you need a jar file associated with jakson to insert it into your lib.

0
source

Source: https://habr.com/ru/post/1388264/


All Articles