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,选中多个商品后点击删除按 ...
随机推荐
- Leetcode之二分法专题-367. 有效的完全平方数(Valid Perfect Square)
Leetcode之二分法专题-367. 有效的完全平方数(Valid Perfect Square) 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 ...
- mysql8.0版本下命令行mysqld –skip-grant-tables 失效,无法登陆的问题
1.管理员权限登陆cmd,不会使用管理员登陆的请搜索cmd,搜索结果右键. 2.命令行输入:net stop mysql;然后提示.服务停止中 --> 服务已停止,如出现其他错误请百度. 这只是 ...
- CodeForces 715B Complete The Graph 特殊的dijkstra
Complete The Graph 题解: 比较特殊的dij的题目. dis[x][y] 代表的是用了x条特殊边, y点的距离是多少. 然后我们通过dij更新dis数组. 然后在跑的时候,把特殊边都 ...
- asp.net core系列 72 Exceptionless使用介绍
一.Exceptionless介绍 Exceptionless专注于.net平台提供实时错误和日志报告.主要包括:错误通知.智能分组异常.详细错误报告堆栈跟踪.支持离线.UI查看重要错误和确定优先级. ...
- java基础面试(二)
最近有搜了几个面试题,大家一起来探讨一下. 1.Oracle 的分页 --分页查询一 select * from (select a1.*,rownum rn from (select * from ...
- 一起来读Netty In Action之传输(三)
当我们的应用程序需要接受比预期多很多的并发连接的时候,我们需要从阻塞传输切换到非阻塞传输上去,如果是我们的网络编程是基于jdk提供的API进行开发地的话,这种传输模式的切换几乎要我们重构整个网络传输相 ...
- 【入门】广电行业DNS、DHCP解决方案详解(三)——DNS部署架构及案
[入门]广电行业DNS.DHCP解决方案详解(三)——DNS部署架构及案 DNS系统部署架构 宽带业务DNS架构 互动业务DNS架构 案例介绍 案例一 案例二 本篇我们将先介绍DNS系统部署架构体系, ...
- 关于Java网络编程
一,网络编程中两个主要的问题 一个是如何准确的定位网络上一台或多台主机,另一个就是找到主机后如何可靠高效的进行数据传输. 在TCP/IP协议中IP层主要负责网络主机的定位,数据传输的路由,由IP地址可 ...
- 通过Service访问应用 (2)
目录 通过NodePort Service在外部访问集群应用 通过LoadBalancer Service在外部访问集群应用 Microsoft SQL Server数据库部署 为了便于理解和学习,请 ...
- 警告:Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
执行Maven Install打包的时候,提示以下警告信息: [WARNING] Using platform encoding (GBK actually) to copy filtered res ...