Demo for use ajax in springmvc
setup the spring xml file:
<mvc:annotation-driven /> <!-- for use annotation--> <context:component-scan base-package="com.test.controller"/> <!-- for use common extends controller and annotation , will prompt "No adapter for handler" exception--> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- register the JSON parser --> <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> </list> </property> </bean>
prepare the controller:
package com.test.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.test.to.UserTO;
@Controller
public class JsonController{
private static Logger logger = Logger.getLogger(JsonController.class);
//pass string from frontend
@ResponseBody
@RequestMapping(value = "/extendSession", method = RequestMethod.POST)
public Map<String,Object> extendSession(
@RequestParam(value = "param1", required = true)Integer param1) {
logger.info("extendSession....................param1="+param1);
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("status", "OK");
return model;
}
//pass object from frontend
@ResponseBody
@RequestMapping(value = "/extendSession111", method = RequestMethod.POST)
public Map<String, Object> extendSession111(@RequestBody UserTO user,HttpServletRequest request) {
logger.info("extendSession111....................user:" + user.getAge()+"--"+user.getName());
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("status", "OK");
return map;
}
}
prepare the frontend javascripts:
function anotherAjaxCall(index){ if(index == 1){ var user={name:"USER NAME",age:26};//object var param = JSON.stringify(user);//parse to JSON object $.ajax({ type : "POST", contentType: "application/json; charset=utf-8", url : "${pageContext.request.contextPath}/extendSession111.do", data: param, dataType : "json", success : function(msg) { alert(msg.status); } }); }else{ $.ajax({ type : "POST", url : "${pageContext.request.contextPath}/extendSession.do", data: "param1=12999",//simple data dataType : "json", success : function(msg) { alert(msg.status); } }); } }
prepare the html:
<a href="javascript:void(0)" οnclick="anotherAjaxCall(1);">ajax call pass ENTITY to controller</a><br/>
<a href="javascript:void(0)" οnclick="anotherAjaxCall(2);">ajax call pass common STRING to controller</a><br/>