1

Here is my jquery ajax ajax request

$.ajax({
  url: "/some_url",
  type: "GET",
  contentType : "application/json; charset=utf-8",
  async: false,
  data: {"attribute_1":"some_value_1","attribute_2":"some_value_2"};,
  cache: false,
  success: function(response) {}
});

Here is my controller method

@RequestMapping(value = "/some_url", method = { RequestMethod.GET })
public String getDetails(HttpServletRequest request,@RequestBody CustomDTO customDTO) {
}

But request does not reach controller method and get 404 error ? If I make it post at ajax and controller level it works. I understand @RequestBody works with POST request only.

My question how can i map the input request parameters to domain object in ajax GET request under spring mvc ?

Do I have do define each parameter as getDetails(HttpServletRequest request,@RequestParam String pName1, @RequestParam String pName2,...) as defined at How to pass Json object from ajax to spring mvc controller? or is there a cleaner way to wrap them in domain object

Raju
  • 429
  • 6
  • 21
user3198603
  • 4,648
  • 11
  • 46
  • 101
  • Possible duplicate of [Does Spring @RequestBody support the GET method?](https://stackoverflow.com/questions/34956899/does-spring-requestbody-support-the-get-method) – Flown Nov 02 '17 at 07:39
  • This is not duplicate. I already mentioned that ` I understand @RequestBody works with POST request only.`. My question is how to convert GET request params to domain object ? – user3198603 Nov 02 '17 at 07:42
  • Then have a look at [Spring MVC: Complex object as GET @RequestParam](https://stackoverflow.com/a/16942352/4105457) – Flown Nov 02 '17 at 07:47
  • `async: false` is a bad idea, and is in fact deprecated due to the poor user experience which results from it (mainly, locking the browser's UI during the request so the user cannot click on anything, and if the request goes on too long they may thing the browser itself has crashed). There are almost no use cases where it would actually be necessary. – ADyson Nov 02 '17 at 09:55

1 Answers1

1

use JSON.stringify() covert data into Json value.

code

data: ({queryData:JSON.stringify({"attribute_1":"some_value_1","attribute_2":"some_value_2"}}))

Then you send data to spring as string parameter Then convert it by using jacksonLibrary

  @RequestMapping(value = "/some_url", method = { RequestMethod.GET })

  public String getDetails(HttpServletRequest request,
                 @RequestParam String queryData) 
    {

   ObjectMapper myMapper = new ObjectMapper();
QueryData myQueryData = myMapper.readValue(queryData, CustomDTO.class);

  //now you can access data... 
     myQueryData.getattribute_1(); 
    myQueryData.getattribute_2(); 
 }
Raju
  • 429
  • 6
  • 21