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;  
 }  

JSTL < c:url >

<c:url value='/abc' /> = context root name + "/abc"

In jsp
Context root name = ${pageContext.request.contextPath} (e.g. myApp)

Note c:url doesn't do URL encoding -- it doesn't convert 'a b' to 'a%20b'

Neither HttpServletResponse.encodeURL(Strin url) nor HttpServletResponse.encodeRedirectURL(String url) encodes URL

URLEncoder.encode(String url) does the job

http://www.cnblogs.com/season-huang/p/3439277.html
https://bluxte.net/musings/2006/03/29/servletpath-and-pathinfo-servlet-api-weirdness/