请求信息转换
异步发送表单数据到JavaBean,并响应JSON文本返回
操作步骤:
(1)加入Jackson2或fastjson框架包,springmvc默认支持Jackon2,不需要做任何操作,而fastjson需要重新配置HttpMessageConverter。
(2)使用@RequestBody接收数据和@ResponseBody返回数据,
这两个动作完全是透明的。
使用jackson转换json数据
代码示例:
创建动态web项目,配置web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Jackson处理json</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 定义Springmvc的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定解析文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-config.xml</param-value> </init-param> <!-- 指定一开始就加载 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 让spring mvc 的前端控制器拦截所有的请求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.jspx</url-pattern> </servlet-mapping> </web-app>
配置springmvc-config.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 自动扫描该包,SpringMVC会将包下用了@controller注解的类注册为Spring的controller --> <context:component-scan base-package="org.fkjava.action"/> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录页面</title> </head> <body> <a href="test1.jspx">测试RequestBody</a> <br><br> <a href="test2.jspx">测试ResponseBody</a> <br><br> <a href="test3.jspx">集合数据做成json返回</a> </body> </html>
TestAction.java类
package org.fkjava.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.fkjava.domain.Book; 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.ResponseBody; @Controller//声明该类为控制器 public class TestJson { @RequestMapping("/test1.jspx")//映射index.jspx的请求 public String test1(){ //返回/WEB-INF/jsp/test1.jsp页面,这里在springmvc-config.xml配置了前缀和后缀 return "test1"; } @RequestMapping("/test2.jspx") public String test2(){ return "test2"; } @RequestMapping("/json/testRequestBody.jspx")//映射对应的请求路径 public void testRequestBody( @RequestBody Book book, HttpServletResponse response) throws Exception{ //用@RequestBody接收数据,得到Book对象 //向book里添加数据 book.setAuthor("张山"); //Jackson开源类包操作json的类 ObjectMapper mapper = new ObjectMapper(); //将对象转成json字符串 String json = mapper.writeValueAsString(book); //设置字符编码,输出到json客户端 response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(json); } /**(重点) * @ResponseBody会将集合数据转换json格式返回客户端 * @return */ @ResponseBody //使用@RequestBody接收数据和@ResponseBody返回数据 @RequestMapping("/json/testResponseBody.jspx") public Object testResponseBody( @RequestBody Book book){ book.setAuthor("李四"); return book; } @ResponseBody @RequestMapping("/json/testArray.jspx") public Object testArray(){ //模拟数据库查询返回多个book对象 List<Book> books = new ArrayList<>(); books.add(new Book(1,"轻量级Java","李刚")); books.add(new Book(2,"疯狂讲义","李刚")); books.add(new Book(3,"Spring","肖")); return books; } }
test1.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试接收JSON格式的数据</title> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript"> $(document).ready(function(){//页面一加载就会加载testRequestBody()方法 testRequestBody(); }); function testRequestBody(){ $.ajax("${pageContext.request.contextPath}/json/testRequestBody.jspx",//发送请求 { dataType : "json",//预期服务器返回的数据类型 type : "post",//请求方式 contentType : "application/json", //发送信息至服务器时的内容编码类型 //发送到服务器的数据 data:JSON.stringify({id : 1, name : "Spring MVC企业应用实战"}), async : true ,//默认设置下,所有请求均为异步请求,如果设置为false,则发送同步请求 //请求成功后回调函数 success : function(data){ $("#id").html(data.id); $("#name").html(data.name); $("#author").html(data.author); }, //请求出错时调用函数 error : function(){ alert("数据发送失败"); } }); } </script> </head> <body> 编号:<span id="id"></span><br> 书名:<span id="name"></span><br> 作者:<span id="author"></span><br></br> </body> </html>
test2.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试接收JSON格式的数据</title> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript"> $(document).ready(function(){//页面一加载就会加载testRequestBody()方法 testRequestBody(); }); function testRequestBody(){ $.ajax("${pageContext.request.contextPath}/json/testResponseBody.jspx",//发送请求 { dataType : "json",//预期服务器返回的数据类型 type : "post",//请求方式 contentType : "application/json", //发送信息至服务器时的内容编码类型 async : true ,//默认设置下,所有请求均为异步请求,如果设置为false,则发送同步请求 //请求成功后回调函数 success : function(data){ $("#id").html(data.id); $("#name").html(data.name); $("#author").html(data.author); }, //请求出错时调用函数 error : function(){ alert("数据发送失败"); } }); } </script> </head> <body> 编号:<span id="id"></span><br> 书名:<span id="name"></span><br> 作者:<span id="author"></span><br></br> </body> </html>
test3.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试接收JSON格式的数据</title> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript"> $(document).ready(function(){//页面一加载就会加载testRequestBody()方法 testRequestBody(); }); function testRequestBody(){ $.ajax("${pageContext.request.contextPath}/json/testArray.jspx",//发送请求 { dataType : "json",//预期服务器返回的数据类型 type : "post",//请求方式 contentType : "application/json", //发送信息至服务器时的内容编码类型 //发送到服务器的数据 data:JSON.stringify({id : 1, name : "Spring MVC企业应用实战"}), async : true ,//默认设置下,所有请求均为异步请求,如果设置为false,则发送同步请求 //请求成功后回调函数 success : function(data){ $.each(data,function(){ var tr = $("<tr align=‘center‘/>"); $("<td/>").html(this.id).appendTo(tr); $("<td/>").html(this.name).appendTo(tr); $("<td/>").html(this.author).appendTo(tr); $("#booktable").append(tr); }) }, //请求出错时调用函数 error : function(){ alert("数据发送失败"); } }); } </script> </head> <body> <table id="booktable" border="1" style="border-collapse: collapse;"> <tr align="center"> <th>编号</th> <th>书名</th> <th>作者</th> </tr> </table> </body> </html>
domain
package org.fkjava.domain; public class Book { private Integer id; private String name; private String author; public Book() { super(); // TODO Auto-generated constructor stub } public Book(Integer id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
使用fastJson转换json数据
1、导包
2、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>fastjson操作json</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 定义springmvc的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定解析配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-config.xml</param-value> </init-param> <!-- 设置一开始就加载 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.jspx</url-pattern> </servlet-mapping> </web-app>
2、配置springmvc-config.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件, 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="org.fkjava.action"/> <mvc:annotation-driven> <!-- 设置不使用默认的消息转换器 --> <mvc:message-converters register-defaults="false"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> <!-- 配置fastjson中实现HttpMessageConverter接口的转换器 FastJsonHttpMessageConverter是fastjson中实现了HttpMessageConverter接口的类--> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <!-- 加入支持的媒体类型:返回contentType --> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录页面</title> </head> <body> <a href="test1.jspx">测试RequestBody</a> <br><br> <a href="test2.jspx">测试ResponseBody</a> <br><br> <a href="test3.jspx">集合数据做成json返回</a> </body> </html>
TestJson.java类
@Controller public class TestJson { @RequestMapping("/test1.jspx") public String test1(){ return "test1"; } @RequestMapping("/test2.jspx") public String test2(){ return "test2"; } @RequestMapping("/test3.jspx") public String test3(){ return "test3"; } @RequestMapping(value="/json/testRequestBody.jspx") public void setJson(@RequestBody Book book, HttpServletResponse response) throws Exception{ book.setAuthor("肖老师"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(JSONObject.toJSONString(book)); } //@esponseBody会将数据转换json格式返回客户端 @ResponseBody @RequestMapping("/json/testResponseBody.jspx") public Object setJson2( @RequestBody Book book, HttpServletResponse response) throws Exception{ book.setAuthor("张"); return book; } // @ResponseBody会将数据转换json格式返回客户端 @ResponseBody @RequestMapping(value="/json/testArray.jspx") public Object testArray() throws Exception { List<Book> list = new ArrayList<Book>(); list.add(new Book(1,"Spring MVC企业应用实战","肖文吉")); list.add(new Book(2,"轻量级JavaEE企业应用实战","李刚")); return list; } }
test1.jsp页面和test2.jsp,和test3.jsp页面以及domain同上
时间: 2024-12-09 05:27:23