SpringMVC uses Json to transmit data, springmvcjson
It is very common and useful to use Json for data transmission in web projects. Here we will introduce a method to use Json for data transmission in SpringMVC. In my use, it mainly includes the following four parts (I personally prefer to use maven for project Building ):
1. Introduce the dependent Jar package
Add the following dependencies to the POM. xml file (or other Maven project configuration files:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.5</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
2. Start SpringMVC annotation and Json message ConverterThe following snippet is in the SpringMVC configuration file:
<mvc:annotation-driven /> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean>
3. javascript asynchronous request on the JSP Interface
<Script type = "text/javascript"> function getInfo () {$. ajax ({type: "POST", dataType: "json", url: "/ajax/getHtml", success: function (map) {$ ("input [name = getInfo]"). after ("<table>"); $. each (map, function (I, item) {$ ("input [name = getInfo]"). after ("<tr> <td>" + item. userName + "</td>" + "<td>" + item. password + "</td> </tr>") ;}); $ ("input [name = getInfo]"). after ("</table") ;}, error: function (ret) {alert ("loading failed") ;}}</script>
4. execute the request in the Controller
@ ResponseBody // The annotation @ RequestMapping (value = "/getHtml") public ModelAndView getHtml () {Map <String, user> map = new HashMap <String, User> (); User li = new User (); li. setUserName ("Li"); li. setPassword ("123"); User na = new User (); na. setUserName ("Na"); na. setPassword ("456"); map. put ("1", li); map. put ("2", na); return new ModelAndView (new MappingJackson2JsonView (), map );}