第二章 SpringMVC数据绑定
第1节 常用注解介绍
@Controller : 将所标识的类加入到IOC容器中进行管理
@RequestMapping : 配置前端请求的映射地址以及请求参数的设置
- method=RequestMethod.GET
- method=RequestMethod.POST
- params:限定请求参数
- params是一个数组
- params={
"name","no!=100","age=10"} : 表示请求参数包含name和no属性,并且no不能等于100,age一定等于10
- params={
"!name"} : 表示请求参数不能有name参数
@PathVariable : 数据绑定
@RequestParam : 类似于servlet的request.getParameter("key");
- value : 要从请求域中获取参数的key值
- required : 参数是否必须
- defaultValue : 如果没有参数,那么走默认值
第2节 GET请求数据绑定风格介绍
2.1 风格一
使用?拼接的方式 hello?name=lilei&age=18
/**
* 通过名称匹配
*/
@GetMapping(value = "/hello")
public String hello02(String name,int age){
System.out.println(name);
System.out.println(age);
return "result";
}
2.2 风格二
hello/lilei/18
/**
* 使用占位符加PathVariable注解的方式
*/
@GetMapping(value = "/hello/{name}/{age}")
public String hello03(@PathVariable("name") String name,@PathVariable("age") int age){
System.out.println(name);
System.out.println(age);
return "result";
}
第3节 其他数据类型对象绑定
3.1 原生的JavaWeb的数据绑定
前端页面
<a href="testJavaWeb">原生的JavaWeb数据绑定测试</a>
后台控制器
@RequestMapping(value = "/testJavaWeb",method = RequestMethod.GET) public String testJavaWeb(HttpServletRequest request){ String name = request.getParameter("name"); System.out.println(name); return "result"; }
3.2 基本数据类型/字符类型
前端页面
<a href="testBase?name=Tom&age=18">基本数据类型/字符类型数据绑定测试</a>
后台控制器
@RequestMapping(value = "/testBase",method = RequestMethod.GET) public String testBase(String name,int age){ System.out.println(name); System.out.println(age); return "result"; }
3.3 数组
前端页面
<a href="testArray?roleId=1001&roleId=1002">数组类型数据绑定测试</a>
后台控制器
@RequestMapping(value = "/testArray",method = RequestMethod.GET) public String testArray(int[] roleId){ System.out.println(roleId); return "result"; }
3.4 自定义类型/嵌套类型
前端页面
<form action="testPOJO" method="post"> <input type="text" name="bookName"/> <%--嵌套提交--%> <input type="text" name="author.authorName"/> <input type="submit" value="提交"/> </form>
模型对象
public class Book { private String bookName; /*嵌套对象*/ private Author author; } public class Author { private String authorName; }
@DateTimeFormat(请求时间格式处理)
如果前端input空间的type类型为date类型,控制器接收参数的类型为Date类型时需要使用注解 @DateTimeFormat(pattern = "yyyy-MM-dd")进行转换
后台控制器
@RequestMapping(value = "/testPOJO",method = RequestMethod.POST) public String testPOJO(Book book){ System.out.println(book); return "result"; }
3.5 SpringMVC中文乱码解决(web.xml)
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第4节 SpringMVC的数据类型转换器
通过传统的JavaWeb数据获取方式获取到的请求数据类型都是String类型,也就是说从前端传过来的数据默认都会变成String类型那么我们的SpringMVC是怎么将String类型转自动转换成其他数据类型的呢?
4.1 SpringMVC内部提供的常见类型转换器
名称 | 作用 |
---|---|
StringToBooleanConverter | String 到 boolean 类型转换 |
StringToCharacterConverter | String 到 Character 类型转换 |
StringToEnumConverterFactory | String 到 Enum 类型转换 |
StringToNumberConverterFactory | String 到 Number 类型转换 |
StringToNumberConverterFactory | Locale 到 String 类型转换 |
… | … |
详细见Spring官网地址:
https://docs.spring.io/spring-framework/docs/4.3.29.RELEASE/spring-framework-reference/htmlsingle/#core-convert
第9.5节 Spring Type Conversion(Spring的类型转换)
Spring类型转换器介绍
1、类型转换是Spring3版本引入,默认是一种SPI(Service Provider Interface[服务发现机制])的机制帮助Spring进行类型转换.
2、提供了常见的API在运行时执行类型转换(例如上面表格中的自带的类型转换以及自定义类型转换).
3、在Spring容器中这个系统(类型转换)可以作为PropertyEditor的替换
4、将String类型转换成其他类型
4.2 自定义类型转换器
常见的自定义类型转换器 API 介绍
Converter
package org.springframework.core.convert.converter; public interface Converter<S, T> { T convert(S source); } 简答类型转换接口,将S类型转换成T类型,进行简单类型的转换比如将String转成Integer
ConverterFactory
package org.springframework.core.convert.converter; public interface ConverterFactory<S, R> { <T extends R> Converter<S, T> getConverter(Class<T> targetType); } 层级类型转换接口, S类型是要被转换的参数类型,R类型是目标转换类型的基类型,T类型是R类型的子类,比如String转枚举类型.
GenericConverter
复杂类型转换接口,当出现复杂类型的转换时,GenericConverter接口更灵活,支持多个源类型到目标类型的转换,并且在转换过程中提供了可以进行注解和泛型的驱动,比如数组Array到集合Collection的转换.
官方提示: 因为GenericConverter是一个复杂的SPI,当必须使用的时候在使用,否则最好是使用Converter or ConverterFactory 进行转换
ConversionService
ConversionService是一个在运行时执行转换逻辑的统一API接口
使用Converter接口实现自定义类型转换器(时间类型转换)
/**
* @Author 枫桥夜泊1990
* @BLOG https://hd1611756908.github.io/
* @BSITE https://space.bilibili.com/514155929/
* @DATE 2020/10/17
*/
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date =null;
try {
date = sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
将自定义Converter转换器加入到IOC容器中
<!--设置类型转换器的服务-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!--设置类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.ukoko.controller.StringToDateConverter"></bean>
</set>
</property>
</bean>
测试类型转换器
前端页面
<form action="testConverter" method="post"> <label for="createTime">时间:</label> <input id="createTime" type="text" name="createTime"/> <input type="submit" value="登陆"> </form>
控制器
@RequestMapping(value = "/testConverter",method = RequestMethod.POST) public String testConverter(Date createTime){ System.out.println("createTime="+createTime); return "result"; }
第三章 SpringMVC的RESTFUL风格
第1节 restful风格概念
Representational State Transfer :(资源)表现层状态转换
是目前最流行的一种互联网软件设计架构思想
资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的 URI。要获取这个资源,访问它的URI就可以,因此 URI 即为每一个资源的独一无二的标识符。
表现层(Representation) 把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文本可以用 txt格式表现,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式。
状态转化(State Transfer): 每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是“表现层状态转化”。具体说,就是HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源
第2节 restful风格格式
/book/1 HTTP GET :得到 id = 1 的 book
/book/1 HTTP DELETE:删除 id = 1的 book
/book/1 HTTP PUT :更新id = 1的 book
/book HTTP POST :新增 book
第3节 restful配置方式
HiddenHttpMethodFilter:浏览器 form 表单只支持 GET 与 POST请求,而DELETE、PUT 等 method并不支持,Spring3.0添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持 GET、POST、PUT 与 DELETE 请求.
web.xml中配置
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第4节 restfult风格使用
<form action="delete" method="post">
<!-- 用于状态转换 -->
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="删除"/>
</form>
<form action="update" method="post">
<!-- 用于状态转换 -->
<input type="hidden" name="_method" value="PUT"/>
<input type="submit" value="更新"/>
</form>
bug处理 405错误 JSPs only permit GET POST or HEAD
在进行资源状态转换时 POST --> DELETE POST --> PUT 由于tomcat8的问题造成的405错误 修复方式: 方式一: 换tomcat为7或者9 方式二: 在jsp页面中在设置 <% isErrorPage="true"%>
第四章 SpringMVC的模型数据
第1节 JavaWeb原生方式模型数据传递
RequestMapping(value = "/testJavaWebModel")
public String testJavaWebModel(HttpServletRequest request){
//将数据使用原生方式放在request域中
request.setAttribute("userName","李雷");
return "result";
}
第2节 SpringMVC的模型数据传递
使用ModelAndView对象传递
@RequestMapping(value = "/testModelAndView") public ModelAndView testModelAndView(){ ModelAndView mv = new ModelAndView(); //指定视图名称 mv.setViewName("result"); /*将数据保存到域对象中*/ mv.addObject("userName","李雷"); return mv; }
使用Model对象传递
@RequestMapping(value = "/testModel") public String testModel(Model model){ /*向域对象中存数据*/ model.addAttribute("userName","李雷"); return "result"; }
使用ModelMap对象传递
@RequestMapping(value = "/testModelMap") public String testModelMap(ModelMap modelMap){ /*向域对象中存数据*/ modelMap.addAttribute("userName","李雷"); return "result"; }
使用Map对象传递
@RequestMapping(value = "/testMap") public String testMap(Map map){ /*向域对象中存数据*/ map.put("userName","李雷"); return "result"; }
Model/ModelMap/Map关系
第六章 SpringMVC的转发和重定向
一句话解释转发和重定向的本质
转发是服务器行为,重定向是客户端行为
SpringMVC 返回值处理
一般情况下,控制器方法返回字符串类型的值会被当成逻辑视图名处理 如果返回的字符串中带forward:或redirect:前缀时,SpringMVC会对他们进行特殊处理:将 forward: 和 redirect: 当成指示符,其后的字符串作为 URL 来处理 redirect:ok:会完成一个到 ok的 @RequestMapping("/ok") 重定向的操作 redirect:/ok forward :ok:会完成一个到 ok的 @RequestMapping("/ok") 转发操作 forward:/ok