json作为前后端交互的重要手段,在springMVC中有自带的转换器可以免去平时那些繁琐的事情:
pom文件添加:spring5.0以上用Jackson2.9以上的版本
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.4</version> </dependency>
Controller层样例:
@Controller public class JsonController { @RequestMapping(value = "jsontest") @ResponseBody public User ajaxtest(){ User user=new User(); user.setUser_name("张三"); user.setPwd("123"); return user; } }
jsp代码样例:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'ajax.jsp' starting page</title> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="<%=basePath%>/static/js/jquery.js"></script> <script type="text/javascript"> function mytest(op){ $.getJSON("jsontest",{key:op},function(data){ alert(data.user_name); }); } </script> </head> <body> <input type="button" onclick="mytest('asdasd')" value="获取AJAX"> </body> </html>
接下来在Spring mvc 配置文件加入控制器的内容:
<!-- 设置json转换器 --> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </bean> <!-- 设置string转换器 --> <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="writeAcceptCharset" value="false" /> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringConverter" /> <ref bean="jsonConverter" /> </list> </property> </bean>
这样就可以直接完成对象,或者其他内容转换成json的格式。