Ajax is a more commonly used page technology, with its good interactive effect has been widely used, in order to facilitate the use of Ajax, the market also appeared a lot of Ajax framework such as DWR. For this reason, Springmvc draws on the idea of DWR to interact with Ajax and SPRINGMVC, while providing a mechanism for translating Java objects into JSON. Let's just get a glimpse of it.
1 If you need SPRINGMVC for Java objects and JSON conversions, you need to add the following configuration
<bean class= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" ><property Name= "Cacheseconds" value= "0"/><property name= "messageconverters" ><list><bean class= " Org.springframework.http.converter.json.MappingJacksonHttpMessageConverter "></bean></list></ Property></bean>
If the JSON data does not require SPRINGMVC to be converted Messageconverters configuration can be ignored
2 The method in the controller plus the annotation @responsebody, at this time the method can be directly accessed through Ajax
Package Com.sxt.action;import Java.io.unsupportedencodingexception;import Java.util.arraylist;import Java.util.list;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.responsebody;import Com.sxt.po.User; @Controller @requestmapping (" Myajax.do ") public class Myajaxcontroller {@RequestMapping (params=" Method=test1 ", method=requestmethod.get) public @ Responsebody list<user> test1 (String uname) throws exception{string uname2 = new String (Uname.getbytes ("iso8859-1 ")," UTF-8 "); System.out.println (uname2); System.out.println ("Myajaxcontroller.test1 ()"); list<user> list = new arraylist<user> (), List.add (New User ("Wilber", "123"), List.add (New User ("Jolin", "456")); return list;}}
3 using AJAX to request SPRINGMVC and get the return value
<%@ page language= "java" import= "java.util.*" pageencoding= "GBK"%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Finally, let's see how it works:Is it also very simple, the most important thing to note is that the use of this method requires the support of Jackson, so the following two jar package can not be less
This time first to come here, next time to share is the SPRINGMVC interceptor.
Ajax interacting with SPRINGMVC