0

I have a button in a HTML page with JQuery 1.8. I'm using Spring MVC 4.1 to handle the requests.

      var test= "foo";
      $.ajax({
            type : "POST",
            async : false,
            url : "rest/ping",
            data : JSON.stringify(test),
            dataType : "json" ,
            contentType : "application/json",
            error : function(jqXHR, textStatus, errorThrown) {
                alert(errorThrown + " -- " + jqXHR.responseText);

            },
            success : function(data) {
                console.log("bar");
            }
        });

The Spring side:

@Controller
@RequestMapping("/test")
public class DummyController {
@RequestMapping(value = "/rest/ping", method = RequestMethod.POST)
@ResponseBody
public void ping(@RequestBody String test) throws ServiceException{
    // nothing of concern
}
}

If I remove the @ResponseBody the system cannot find the mapping. If I add '(required=false)' to the request body annotation then the mapping is found but the ajax call fails because after the mapped url is called, the system calls "test/rest/ping/rest/ping".

If you have a documentation of JQuery and Spring MVC working together, please add them to this question. I'm not able to find a valid example describing exact this strange behaviour. If you have any questions, please ask. Thank you all for your time.

1
  • Could you provide the code of the entire controller? It can be that there is an inconsistency with the annotation of it. Commented Aug 3, 2016 at 12:27

2 Answers 2

2

@ResponseBody is needed since you are making an XHR call via JQuery. This is true for endpoints that will return a specific data format (JSON, XML) but also for endpoint that do not return any data (void).

Otherwise, when not specified Spring require a ModelView object to be returned that will point to a specific view and can be decorated with a model hash in it.

In your case the problem could be that during JSON.stringify(test) your are not providing a valid key-value pair in the form of: test=yourValue

For more info about Responsebody you can check this one.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Can you try following changes

Remove the controller's @RequestMapping("/test"). If you still want to keep it then include that as well in the AJAX as test/rest/ping

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.