SpringMVC框架三
一、消息转换器
1、概述
消息转换器能够将请求信息转换成对象,也可以将对象换成响应信息
消息转换器是由 RequestMappingHandlerAdapter 调用
依赖于HttpMessageConverter接口,此接口是spring3.0才有
2、如何使用
依赖于以下的注解
@RequestBody
作用:将请求信息----》对象
@ResponseBody
作用:对象----》响应信息
3、应用场景
json的数据格式的转换
如果提交json数据------>消息转换器-------》对象
对象--------》消息转换器---------》响应信息
4、如何json转换实现
a、导入jackson库


b、配置bean文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xmlns:p="http://www.springframework.org/schema/p" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context-4.3.xsd 15 http://www.springframework.org/schema/util 16 http://www.springframework.org/schema/util/spring-util.xsd"> 17 <context:component-scan base-package="com.gec.controller" /> 18 19 <!--配置注解的处理器映射器--> 20 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> 21 <!--配置注解的处理器适配器--> 22 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" p:messageConverters-ref="messageConverter"/> 23 <!--JackSon实现的消息转换器--> 24 <util:list id="messageConverter"> 25 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 26 </util:list> 27 <!-- 视图解析器 --> 28 <bean id="viewResolver" 29 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 30 <!-- 前缀 --> 31 <property name="prefix"> 32 <value>/WEB-INF/jsp/</value> 33 </property> 34 <!-- 后缀 --> 35 <property name="suffix"> 36 <value>.jsp</value> 37 </property> 38 </bean> 39 </beans>
c、配置web.xml
将映射前端控制器的路径(/)------>(*.action)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 5 http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 6 version="4.0"> 7 <!-- 定义Spring MVC的前端控制器 --> 8 <servlet> 9 <servlet-name>springmvc</servlet-name> 10 <servlet-class> 11 org.springframework.web.servlet.DispatcherServlet 12 </servlet-class> 13 <init-param> 14 <param-name>contextConfigLocation</param-name> 15 <param-value>/WEB-INF/springmvc-config.xml</param-value> 16 </init-param> 17 <load-on-startup>1</load-on-startup> 18 </servlet> 19 <!-- 让Spring MVC的前端控制器拦截尾缀为.action的请求 --> 20 <servlet-mapping> 21 <servlet-name>springmvc</servlet-name> 22 <url-pattern>*.action</url-pattern> 23 </servlet-mapping> 24 </web-app>
d、handler实现
1 package com.gec.controller; 2 3 import com.gec.domain.Book; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestBody; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 10 11 @Controller 12 public class BookController { 13 @RequestMapping("/testRequestBody.action") 14 @ResponseBody 15 public Book testRequestBody(@RequestBody Book book){ 16 System.out.println(book); 17 book.setAuthor("Lantxy"); 18 return book; 19 } 20 21 @RequestMapping("/viewindex.action") 22 public String viewindex(){ 23 return "index"; 24 } 25 }
e、引入js

f、编写index.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; 7 charset=UTF-8"> 8 <title>测试接收JSON格式的数据</title> 9 <script type="text/javascript" 10 src="${pageContext.request.contextPath}/js/jquery-3.2.1.js"> 11 </script> 12 <script type="text/javascript" 13 src="${pageContext.request.contextPath}/js/json2.js"> 14 </script> 15 <script type="text/javascript"> 16 $(document).ready(function(){ 17 testRequestBody(); 18 }); 19 function testRequestBody(){ 20 $.ajax( 21 "${pageContext.request.contextPath}/testRequestBody.action", 22 // 发送请求的URL字符串。 23 { 24 dataType : "json", // 预期服务器返回的数据类型。 25 type : "post", // 请求方式 POST或GET 26 contentType:"application/json", // 发送信息至服务器时的内容编码类型 27 // 发送到服务器的数据。 28 data:JSON.stringify({id : 1, name :"thinking in java"}), 29 async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求 30 // 请求成功后的回调函数。 31 success :function(data){ 32 console.log(data); 33 $("#id").html(data.id); 34 $("#name").html(data.name); 35 $("#author").html(data.author); 36 }, 37 // 请求出错时调用的函数 38 error:function(){ 39 alert("数据发送失败"); 40 } 41 }); 42 } 43 </script> 44 </head> 45 <body> 46 编号:<span id="id"></span><br> 47 书名:<span id="name"></span><br> 48 作者:<span id="author"></span><br> 49 </body> 50 </html>
5、使用fastjson实现
a、导入fastjson库

b、配置bean xml文件
1 <!--JackSon实现的消息转换器--> 2 <util:list id="messageConverter"> 3 <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> 4 <!-- 加入支持的媒体类型:返回contentType --> 5 <property name="supportedMediaTypes"> 6 <list> 7 <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 --> 8 <value>text/html;charset=UTF-8</value> 9 <value>application/json;charset=UTF-8</value> 10 </list> 11 </property> 12 </bean> 13 </util:list>
二、简化注解方式配置
1、注解实现配置
功能
不需要配置映射器及适配器
消息转换器(默认jackjson)
。。。。。
2、用法
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xmlns:p="http://www.springframework.org/schema/p" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context-4.3.xsd 15 http://www.springframework.org/schema/util 16 http://www.springframework.org/schema/util/spring-util.xsd"> 17 <context:component-scan base-package="com.gec.controller"/> 18 <mvc:annotation-driven/> 19 <mvc:default-servlet-handler/> 20 21 <!-- 视图解析器 --> 22 <bean id="viewResolver" 23 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 24 <!-- 前缀 --> 25 <property name="prefix"> 26 <value>/WEB-INF/jsp/</value> 27 </property> 28 <!-- 后缀 --> 29 <property name="suffix"> 30 <value>.jsp</value> 31 </property> 32 </bean> 33 </beans>
三、springmvc的表单标签用法
1、表单标签
form标签
input标签
checkBox标签和checkboxes标签
radiobutton标签和radiobuttons标签
select标签
option标签和options标签
errors标签
2、作用
javabean的属性值与form标签组件自绑定功能
3、用法
在jsp组件引入标签名,
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>,以下是jsp代码
1 <%-- 2 Created by IntelliJ IDEA. 3 User: Administrator 4 Date: 2020-10-20 5 Time: 14:18 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 10 <html> 11 <head> 12 <title>Title</title> 13 </head> 14 <body> 15 <form:form> 16 用户名:<form:input path="username"/><br/> 17 年龄:<form:input path="age"/><br/> 18 性别:<br/> 19 男<form:radiobutton path="sex" value="M"/><br/> 20 女<form:radiobutton path="sex" value="F"/><br/> 21 选择学习的语言:<form:select path="programlanguage" items="${programlanguageList}"/> 22 </form:form> 23 </body> 24 </html>
编写javabean
1 package com.gec.bean; 2 3 public class User { 4 private String username; 5 private Integer age; 6 private String sex; 7 private String Programlanguage; 8 9 @Override 10 public String toString() { 11 return "User{" + 12 "username='" + username + '\'' + 13 ", age=" + age + 14 ", sex='" + sex + '\'' + 15 ", Programlanguage='" + Programlanguage + '\'' + 16 '}'; 17 } 18 19 public String getUsername() { 20 return username; 21 } 22 23 public void setUsername(String username) { 24 this.username = username; 25 } 26 27 public Integer getAge() { 28 return age; 29 } 30 31 public void setAge(Integer age) { 32 this.age = age; 33 } 34 35 public String getSex() { 36 return sex; 37 } 38 39 public void setSex(String sex) { 40 this.sex = sex; 41 } 42 43 public String getProgramlanguage() { 44 return Programlanguage; 45 } 46 47 public void setProgramlanguage(String programlanguage) { 48 Programlanguage = programlanguage; 49 } 50 }
控制器
1 package com.gec.controller; 2 3 import com.gec.bean.User; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import javax.servlet.http.HttpSession; 11 import java.io.IOException; 12 import java.util.ArrayList; 13 import java.util.List; 14 15 @Controller 16 public class UserController { 17 @RequestMapping("toform") 18 public String toForm(Model model){ 19 User user=new User(); 20 user.setUsername("张三"); 21 user.setAge(35); 22 user.setSex("F"); 23 user.setProgramlanguage("c++"); 24 25 model.addAttribute("command",user); 26 27 List<String> programlanguageList =new ArrayList<>(); 28 programlanguageList.add("java"); 29 programlanguageList.add("c++"); 30 programlanguageList.add("c"); 31 programlanguageList.add("python"); 32 33 model.addAttribute("programlanguageList",programlanguageList); 34 35 return "form"; 36 } 37 }
视图组件(即上面的jsp代码,显示重要部分)
1 <form:form> 2 用户名:<form:input path="username"/><br/> 3 年龄:<form:input path="age"/><br/> 4 性别:<br/> 5 男<form:radiobutton path="sex" value="M"/><br/> 6 女<form:radiobutton path="sex" value="F"/><br/> 7 选择学习的语言:<form:select path="programlanguage" items="${programlanguageList}"/> 8 </form:form>
四、SpringMVC中的参数绑定
1、简介
直接将页面参数自注入到请求方法参数中
2、支持Servlet数据类型
HttpServletRequest对象
HttpServletResponse对象
HttpSession对象
Model/ModelMap对象
3、基础用法
1 @RequestMapping("dorequest") 2 public String doRequest(HttpServletRequest httpServletRequest){ 3 String username=httpServletRequest.getParameter("username"); 4 System.out.println("username="+username); 5 return "success"; 6 7 } 8 @RequestMapping("/dosession") 9 public String doSession(HttpSession httpSession){ 10 httpSession.setAttribute("username","root"); 11 return "success"; 12 } 13 @RequestMapping("/doresponse") 14 public String doResponse(HttpServletResponse httpServletResponse) throws IOException { 15 httpServletResponse.setContentType("text/html;charset=UTF-8"); 16 httpServletResponse.getWriter().println("hello,response"); 17 return "success"; 18 }
4、支持简单类型的绑定
简介
pojo类型的绑定
包装的pojo类型
数组的绑定
List的绑定(注意不能直接在请求方法参数定义集合类型)
Map的绑定(注意不能直接在请求方法参数定义集合类型)
pojo类型的绑定:
form定义
1 <form 2 action="${pageContext.servletContext.contextPath}/saveuser"> 3 用户名:<input type="text" name="username"/><br/> 4 年龄:<input type="text" name="age"/><br/> 5 性别:<input type="text" name="sex"/><Br/> 6 <input type="submit" value="提交"/> 7 </form>
请求方法定义
1 //获取会话参数 2 @RequestMapping("/saveuser") 3 public String saveUser(User user) 4 { 5 System.out.println("save user"); 6 System.out.println(user); 7 return "success"; 8 }
数组的绑定:
form页面实现
1 <form 2 action="${pageContext.servletContext.contextPath}/saveuser2"> 3 兴趣:<input type="checkbox" value="足球" 4 name="funs"/>足球<input type="checkbox" value="音乐" 5 name="funs"/>音乐<input type="checkbox" value="看书" 6 name="funs"/>看书 7 <input type="submit" value="提交"/> 8 </form>
请求方法定义
1 @RequestMapping("/saveuser2") 2 public String saveuser2(String []funs) 3 { 4 for(String fun:funs) 5 { 6 System.out.println(fun); 7 } 8 return "success"; 9 }
List的绑定:
页面form
1 <form 2 action="${pageContext.servletContext.contextPath}/save 3 user3"> 4 <table width="80%"> 5 <tr> 6 <th>用户名</th> 7 <th>年龄</th> 8 <th>性别</th> 9 <th>编程语言</th> 10 </tr> 11 <tr> 12 <!--userList仅仅是一个pojo对象(User)里面的属性,而此属性就是一个list类型--> 13 <td><input type="text" 14 name="userList[0].username"/></td> 15 <td><input type="text" 16 name="userList[0].age"/></td> 17 <td><input type="text" 18 name="userList[0].sex"/></td> 19 <td><input type="text" 20 name="userList[0].programlanguage"/></td> 21 </tr> 22 <tr> 23 <td><input type="text" 24 name="userList[1].username"/></td> 25 <td><input type="text" 26 name="userList[1].age"/></td> 27 <td><input type="text" 28 name="userList[1].sex"/></td> 29 <td><input type="text" 30 name="userList[1].programlanguage"/></td> 31 </tr> 32 <tr> 33 <td><input type="text" 34 name="userList[2].username"/></td> 35 <td><input type="text" 36 name="userList[2].age"/></td> 37 <td><input type="text" 38 name="userList[2].sex"/></td> 39 <td><input type="text" 40 name="userList[2].programlanguage"/></td> 41 </tr> 42 </table> 43 <input type="submit" value="提交"/> 44 </form>
请求方法定义
1 @RequestMapping("/saveuser3") 2 public String saveuser3(User user) 3 { 4 for (User user1 : user.getUserList()) { 5 System.out.println(user1); 6 } 7 return "success"; 8 }
定义pojo对象:
1 public class User implements Serializable { 2 ... 3 //添加一个集合 4 private List<User> userList; 5 public List<User> getUserList() { 6 return userList; 7 } 8 public void setUserList(List<User> userList) { 9 this.userList = userList; 10 } 11 public Map<String, String> getCourse() { 12 return course; 13 }
定义请求方法
1 public class User implements Serializable {
2 ....
3 //添加一个map
4 private Map<String,String> course;
5 public Map<String, String> getCourse() {
6 return course;
7 }
8 public void setCourse(Map<String, String>
9 course) {
10 this.course = course;
11 }
12 }
Map的绑定:
编写form
1 <form 2 action="${pageContext.servletContext.contextPath}/saveuser4"> 3 <table width="80%"> 4 <tr> 5 <th>科目1</th> 6 <th>科目2</th> 7 <th>科目3</th> 8 <th>科目4</th> 9 </tr> 10 <tr> 11 <!--course也是pojo的一个属性,此属性就是一个map对象--> 12 <td><input type="text" 13 name="course['001']"/></td> 14 <td><input type="text" 15 name="course['002']"/></td> 16 <td><input type="text" 17 name="course['003']"/></td> 18 <td><input type="text" 19 name="course['004']"/></td> 20 </tr> 21 </table> 22 <input type="submit" value="提交"/> 23 </form>
请求方法
1 @RequestMapping("/saveuser4")
2 public String saveuser4(User user)
3 {
4 user.getCourse().forEach((k,v)->
5 System.out.println("科目编号="+k+" 科目名="+v));
6 return "success";
7 }
五、数据转换
1、简介
将请求参数通过数据转换接口,自绑定到对应的请求方法参数对象

2、如何自定义数据转换接口
应用场景
以日期和user为例
编写handler
1 package com.gec.controller; 2 3 import com.gec.bean.User; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 import java.util.Date; 9 10 11 @Controller 12 public class TestController { 13 @RequestMapping("dodate") 14 public String doData(Date data){ 15 System.out.println(data); 16 return "success"; 17 } 18 @RequestMapping("saveuser") 19 @ResponseBody 20 public String saveUser(User user){ 21 System.out.println(user); 22 return "success"; 23 } 24 }
以上包含了dodate和saveuser两个例子
编写自定义数据类型转换器
date:
1 package com.gec.converter; 2 3 import org.springframework.core.convert.converter.Converter; 4 5 import java.text.ParseException; 6 import java.text.SimpleDateFormat; 7 import java.util.Date; 8 9 public class StringToDateConverter implements Converter<String, Date>{ 10 11 @Override 12 public Date convert(String s) { 13 SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd"); 14 try { 15 return sf.parse(s); 16 } catch (ParseException e) { 17 e.printStackTrace(); 18 } 19 return null; 20 } 21 }
user:
1 package com.gec.converter; 2 3 import com.gec.bean.User; 4 import org.springframework.core.convert.converter.Converter; 5 6 public class StringToUserConverter implements Converter<String, User> { 7 8 @Override 9 public User convert(String s) { 10 User user=new User(); 11 String dataArrays[]=s.split(","); 12 user.setUsername(dataArrays[0]); 13 user.setAge(Integer.parseInt(dataArrays[1])); 14 user.setCourse(dataArrays[2]); 15 return user; 16 } 17 }
配置数据类型转换器(beans.xml)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xmlns:p="http://www.springframework.org/schema/p" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context-4.3.xsd 15 http://www.springframework.org/schema/util 16 http://www.springframework.org/schema/util/spring-util.xsd"> 17 <context:component-scan base-package="com.gec.controller"/> 18 <mvc:annotation-driven conversion-service="conversionService"/> 19 <mvc:default-servlet-handler/> 20 21 22 <!--自定义的类型转换器--> 23 <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> 24 <property name="converters"> 25 <list> 26 <bean class="com.gec.converter.StringToDateConverter"/> 27 <bean class="com.gec.converter.StringToUserConverter"/> 28 </list> 29 </property> 30 </bean> 31 32 <!-- 视图解析器 --> 33 <bean id="viewResolver" 34 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 35 <!-- 前缀 --> 36 <property name="prefix"> 37 <value>/WEB-INF/jsp/</value> 38 </property> 39 <!-- 后缀 --> 40 <property name="suffix"> 41 <value>.jsp</value> 42 </property> 43 </bean> 44 </beans>
以上的自定义转换器方法就完成啦,但是小蓝有个问题请教大家,自定义的转换器如果遇到乱码问题该怎么解决,应该在xml中如何配置,欢迎所有人来暖博客(●'◡'●)

浙公网安备 33010602011771号