JQuery send JSON to Spring MVC controller

13,177

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.

Share:
13,177
carlo
Author by

carlo

Software Developer with many years of experience

Updated on June 04, 2022

Comments

  • carlo
    carlo almost 2 years

    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.

  • carlo
    carlo over 12 years
    Thank you for your reply, now I get a 404 error. I have also tried with var obj = jQuery.parseJSON('{"createUser":"John"}'); and passing this object to the mvc method. Seems that does not recognize the RequestBody object. Others configuration should I try ? Or is incorrect my ajax request ? Many thanks.
  • soulcheck
    soulcheck over 12 years
    @carlo first check if you can connect to your controller (using curl or telnet). Then check if you have any errors in your server log. Check if you have <context:annotation-config/> in your spring context. And lastly check if your message converter is configured properly. See my edit.
  • carlo
    carlo over 12 years
    Now happens a think that I'm not able to understand: if I remove the annotation @RequestBody, the services is invoked instead if is present the annotation I have a 404 error. How debug this situation ? Thank you.
  • soulcheck
    soulcheck over 12 years
    @carlo hmm, make sure you changed the request type of your jquery to 'post'. otherwise jquery will try to encode the json in url and i think spring doesn't yet know how to deal with it.
  • carlo
    carlo over 12 years
    yes, the type of request is this: $.ajax({ dataType: "json", contentType: "application/json", url: ctx + "/InboxViewTemplate/updateInboxView", type: "POST", cache : false, data : { name : "appId"}, success: function(data) { $("#updateInboxView").html(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR + " : " + textStatus + " : " + errorThrown); } });
  • soulcheck
    soulcheck over 12 years
    @carlo post, if you can your web.xml, application context, jsp and InboxView + InboxViewController classes. It's hard to diagnose the problem without looking at some more code.
  • soulcheck
    soulcheck almost 11 years
    @carlo i just noticed that the answer was missing JSON serialization on jquery part. A bit of a late call, i know :)