springmvc(二)
请求信息转换
异步发送表单数据到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同上
springmvc(二)的更多相关文章
- SpringMVC(二)——流程控制
SpringMVC主要就是用来做流程控制的,这篇博客总结一下如何在流程控制添加Interceptor(拦截器),如何将进行流程Mapping映射解析,如何编写Controller(控制器). 一,首先 ...
- springmvc(二) ssm框架整合的各种配置
ssm:springmvc.spring.mybatis这三个框架的整合,有耐心一步步走. --WH 一.SSM框架整合 1.1.整合思路 从底层整合起,也就是先整合mybatis与spring,然后 ...
- SpringMVC(二) SpringMVC Hello World
准备条件: STS(集成了Spring相关工具的Eclipse) Spring软件包 spring-framework-4.3.3.RELEASE-dist.zip. 步骤: 加入jar包. Ecli ...
- 浅谈SpringMVC(二)
一.SpringMVC的拦截器 1.写类implements HandlerInterceptor public class MyMvcInterceptor implements HandlerIn ...
- SpringMVC(二):RequestMapping修饰类、指定请求方式、请求参数或请求头、支持Ant路径
@RequestMapping用来映射请求:RequestMapping可以修饰方法外,还可以修饰类 1)SpringMVC使用@RequestMapping注解为控制指定可以处理哪些URL请求: 2 ...
- SpringMVC(二六) SpringMVC配置文件中使用mvc:view-controller标签
在springmvc中使用mvc:view-controller标签直接将访问url和视图进行映射,而无需要通过控制器. 参考springmvc.xml内容: <?xml version=&qu ...
- SpringMVC(二五) JSTL View
项目中使用JSTL,SpringMVC会把视图由InternalView转换为JstlView. 若使用Jstl的fmt标签,需要在SpringMVC的配置文件中配置国际化资源文件. 实现过程: 1. ...
- SpringMVC(二四) 视图解析流程
目标方法无论返回的是string.ModelAndView.View,最终都被解析成modelAndView 关键的实现代码是在springmvc.xml配置文件中定义解析器. 参考代码如下: < ...
- springMVC(二): @RequestBody @ResponseBody 注解实现分析
一.继承结构 @RequestBody.@ResponseBody的处理器:RequestResponseBodyMethodProcessor @ModelAttribute处理器: ModelAt ...
- SpringMVC(二)高级
高级参数绑定 1.1. 绑定数组 1.1.1. 需求 在商品列表页面选中多个商品,然后删除. 1.1.2. 需求分析 功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按 ...
随机推荐
- 前端测试工具之 postman
1.不论你是一个前端工程师还是一个后端工程师相信这款工具都会使你的开发更加简便. 2.在此我推荐的一款软件工具是 postman . 在这里我对 postman 做一个简单的介绍: ①它能够模拟表单发 ...
- SyntaxError: invalid syntax : if not 0 <= time_low < 1<<32L:
报错 Traceback (most recent call last): File "D:/PyCharm 5.0.3/WorkSpace/2.NLP/8.高阶实践/1.PipelineQ ...
- vue.js纯前端处理如何将后台返回来的csv数据导出成csv文件
需要实现一个下载csv文件的功能,但后台没有对这个下载文件进行处理,而是将csv数据传给前台而已,需要前台做一下处理. 这是按钮的代码: <a> <el-button size=&q ...
- CodeForces 346C Number Transformation II
Number Transformation II 题解: 对于操作2来说, a - a % x[i] 就会到左边离a最近的x[i]的倍数. 也就是说 [ k * x[i] + 1, (k+1)* x ...
- Atcoder D - 3N Numbers(优先队列+dp)
题目链接:http://abc062.contest.atcoder.jp/tasks/arc074_b 题意:给出3*n个数要求去掉n个数使得剩下的前n个数-后n个数的差最大. 题解:显然是一道如果 ...
- Hangman Judge UVA - 489
In ``Hangman Judge,'' you are to write a program that judges a series of Hangman games. For each gam ...
- 关于Ubunto在VMwark中无法全屏。
1.右键点击Ubunto桌面,进入终端 输入: 1.sudo apt-get install open-vm* 安装依赖项 2.sudo apt-get install open-vm-tools ...
- 2019icpc徐州网络赛_I_query
题意 给定一个序列,多次询问区间\([l,r]\)中满足\(min(a[i],a[j])==gcd(a[i],a[j])\)的数对\((i,j)\)数. 分析 其实就是求区间有倍数关系的数对数. 由于 ...
- 渗透之路基础 -- 服务端请求伪造SSRF
简介:SSRF 服务器端请求伪造,有的大型网站在web应用上提供了从其他服务器获取数据的功能.使用户指定的URL web应用获取图片,下载文件,读取文件内容.通常用于控制web进而探测内网服务以及攻击 ...
- Azure虚拟机时间同步问题
场景描述:在Azure上新创建虚拟机默认是UTC时区的,因为业务在国内,所以要修改在CST注:协调世界时(英语:Coordinated Universal Time,法语:Temps Universe ...