Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery send JSON to Spring MVC controller

I' not able to send a JSON object with JQuery Ajax to a Spring MVC controller. This is the definition of the method of my controller:

@Controller
@RequestMapping(value = "InboxViewTemplate")
public class InboxViewController {

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

then I'm trying to invoke this request:

$.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 someone help me? Thanks in advance.

like image 609
carlo Avatar asked Feb 22 '23 00:02

carlo


1 Answers

First of all your controller doesn't know where to look for InboxView. Is it a request parameter? Path param? Request body?

Second of all you probably want to change your json request type to POST or PUT as you're updating 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);
            }
          });
      }

should work.

I'm assuming here that you have your json message converter configured properly.

edit Meaning 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 config.

like image 176
soulcheck Avatar answered Feb 26 '23 22:02

soulcheck