请求信息转换

  异步发送表单数据到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(二)的更多相关文章

  1. SpringMVC(二)——流程控制

    SpringMVC主要就是用来做流程控制的,这篇博客总结一下如何在流程控制添加Interceptor(拦截器),如何将进行流程Mapping映射解析,如何编写Controller(控制器). 一,首先 ...

  2. springmvc(二) ssm框架整合的各种配置

    ssm:springmvc.spring.mybatis这三个框架的整合,有耐心一步步走. --WH 一.SSM框架整合 1.1.整合思路 从底层整合起,也就是先整合mybatis与spring,然后 ...

  3. SpringMVC(二) SpringMVC Hello World

    准备条件: STS(集成了Spring相关工具的Eclipse) Spring软件包 spring-framework-4.3.3.RELEASE-dist.zip. 步骤: 加入jar包. Ecli ...

  4. 浅谈SpringMVC(二)

    一.SpringMVC的拦截器 1.写类implements HandlerInterceptor public class MyMvcInterceptor implements HandlerIn ...

  5. SpringMVC(二):RequestMapping修饰类、指定请求方式、请求参数或请求头、支持Ant路径

    @RequestMapping用来映射请求:RequestMapping可以修饰方法外,还可以修饰类 1)SpringMVC使用@RequestMapping注解为控制指定可以处理哪些URL请求: 2 ...

  6. SpringMVC(二六) SpringMVC配置文件中使用mvc:view-controller标签

    在springmvc中使用mvc:view-controller标签直接将访问url和视图进行映射,而无需要通过控制器. 参考springmvc.xml内容: <?xml version=&qu ...

  7. SpringMVC(二五) JSTL View

    项目中使用JSTL,SpringMVC会把视图由InternalView转换为JstlView. 若使用Jstl的fmt标签,需要在SpringMVC的配置文件中配置国际化资源文件. 实现过程: 1. ...

  8. SpringMVC(二四) 视图解析流程

    目标方法无论返回的是string.ModelAndView.View,最终都被解析成modelAndView 关键的实现代码是在springmvc.xml配置文件中定义解析器. 参考代码如下: < ...

  9. springMVC(二): @RequestBody @ResponseBody 注解实现分析

    一.继承结构 @RequestBody.@ResponseBody的处理器:RequestResponseBodyMethodProcessor @ModelAttribute处理器: ModelAt ...

  10. SpringMVC(二)高级

    高级参数绑定 1.1. 绑定数组 1.1.1. 需求 在商品列表页面选中多个商品,然后删除. 1.1.2. 需求分析 功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按 ...

随机推荐

  1. Java中集合的概述

    一.集合和数组的区别 1.数组(可以存储基本数据类型)是用来存现对象的一种容器,但是数组的长度固定,不适合在对象数量未知的情况下使用. 2.集合(只能存储对象,对象类型可以不一样)的长度可变,可在多数 ...

  2. 防盗链测试01 - Jwplayer+Tengine2.3.1 mp4模块打造流媒体测试服务器

    最近有个想法,想做类似下面的视频URL验证: 1.URL Tag Validation 2.Special format of URL for preventing unauthorized usag ...

  3. JavaScript label语句

    使用label 语句可以在代码中添加标签,以便将来使用. 以下是label 语句的语法: label: statement 下面是一个示例: start: for (var i=0; i < c ...

  4. hdu-6681 Rikka with Cake

    题目链接 hdu-6681 Problem Description Rikka's birthday is on June 12th. The story of this problem happen ...

  5. 51nod 1376 最长递增子序列的数量(不是dp哦,线段树 +  思维)

    题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1376 题解:显然这题暴力的方法很容易想到就是以每个数为结尾最 ...

  6. Spring Boot2 系列教程(二)创建 Spring Boot 项目的三种方式

    我最早是 2016 年底开始写 Spring Boot 相关的博客,当时使用的版本还是 1.4.x ,文章发表在 CSDN 上,阅读量最大的一篇有 43W+,如下图: 2017 年由于种种原因,就没有 ...

  7. 通过原型继承理解ES6 extends 如何实现继承

    前言 第一次接触到 ES6 中的 class 和 extends 时,就听人说这两个关键字不过是语法糖而已.它们的本质还是 ES3 的构造函数,原型链那些东西,没有什么新鲜的,只要理解了原型链等这些概 ...

  8. jQuery的大小拖动

    原来一直没有拖动放大的效果,居然只是没有jquery-ui.css的样式文件,虽然这是一个很小的部分,但是防微杜渐.程序本来就是个不容有小错误的存在. 如果没有样式文件,那么可以收缩的三角形就不会出现 ...

  9. Go语言基础之单元测试

    不写测试的开发不是好程序员.我个人非常崇尚TDD(Test Driven Development)的,然而可惜的是国内的程序员都不太关注测试这一部分. 这篇文章主要介绍下在Go语言中如何做单元测试和基 ...

  10. Ajax发送请求的四个步骤

    1.创建XMLHttpRequest let xhr=new XMLHttpRequest; 2.连接服务器 xhr.open("get","goods.json&quo ...