Thursday, 22 September 2016

Spring MVC + jQuery Ajax get post cheat sheet

Get


 $.get( "get", { name: "John", time: "2pm" }, function( data ) {  
      alert( "Data Loaded: " + data );  
 });  

 @RequestMapping(value = "/get", method = RequestMethod.GET)  
 @ResponseBody  
 public String get(@RequestParam String name, @RequestParam time) throws Exception{  
      return "Hello "+name+" "+time;  
 }  

Post

 $.post("post", { name: "John", time: "2pm"}, function(data) {  
      alert( "Data Loaded: " + data );  
 });  

There are two ways to handle the request in controller
1. Use Request parameter
2. Use ModelAttributes

 //1st way  
 @RequestMapping(value = "/post", method = RequestMethod.POST)  
 @ResponseBody  
 public String post(@RequestParam String name, @RequestParam time) throws Exception{  
      return "Hello "+name+" "+time;  
 }  
 
 //2nd way
 public class AjaxRequest {  
      private String name;  
      private String time;  
      //Ingore setters and getters  
 }  
     
 @RequestMapping(value = "/post", method = RequestMethod.POST)  
 @ResponseBody  
 public String post(@ModelAttribute AjaxRequest request) throws Exception{  
      return "Hello "+name+" "+time;  
 }  

What if you want to use @RequestBody?

You cannot use the shorthand form $.post any more. You must use $.ajax method and specify the contentType as 'application/json' and stringify the data using JSON.stringify()

 $.ajax({  
      type : "POST",  
      //must set the contentType for @RequestBody annotation to work, otherwise use @ModelAttribute to replace @RequestBody  
      contentType : "application/json",   
      url : "post",  
      //must use the stringify method to convert to json format  
      data : JSON.stringify({ name: "John", time: "2pm"}),  
      success : function(data) {  
           console.log("SUCCESS: ", data);  
      }  
 });  
   
 @RequestMapping(value = "/post", method = RequestMethod.POST)  
 @ResponseBody  
 public String post(@RequestBody AjaxRequest request) throws Exception{  
      return "Hello "+name+" "+time;  
 }  

No comments:

Post a Comment