SpringMVC
1.1、什么是MVC
MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分
M:Model,模型层,指工程中的JavaBean,作用是处理数据 JavaBean分为两类:
-
一类称为实体类Bean:专门存储业务数据的,如 Student、User 等
-
一类称为业务处理 Bean:指 Service 或 Dao 对象,专门用于处理业务逻辑和数据访问。
V:View,视图层,指工程中的html或jsp等页面,作用是与用户进行交互,展示数据
C:Controller,控制层,指工程中的servlet,作用是接收请求和响应浏览器
MVC的工作流程: 用户通过视图层发送请求到服务器,在服务器中请求被Controller接收,Controller 调用相应的Model层处理请求,处理完毕将结果返回到Controller,Controller再根据请求处理的结果 找到相应的View视图,渲染数据后最终响应给浏览器
1.2、什么是SpringMVC
SpringMVC是Spring的一个后续产品,是Spring的一个子项目
SpringMVC 是 Spring 为表述层开发提供的一整套完备的解决方案。在表述层框架历经 Strust、 WebWork、Strust2 等诸多产品的历代更迭之后,目前业界普遍选择了 SpringMVC 作为 Java EE 项目表述层开发的首选方案。
- 注:三层架构分为表述层(或表示层)、业务逻辑层、数据访问层,表述层表示前台页面和后台 servlet
1.3、SpringMVC的特点
Spring 家族原生产品,与 IOC 容器等基础设施无缝对接
基于原生的Servlet,通过了功能强大的前端控制器DispatcherServlet,对请求和响应进行统一 处理
-
表述层各细分领域需要解决的问题全方位覆盖,提供全面解决方案
-
代码清新简洁,大幅度提升开发效率
-
内部组件化程度高,可插拔式组件即插即用,想要什么功能配置相应组件即可
-
性能卓著,尤其适合现代大型、超大型互联网项目要求
创建SpringMVC工程
导入依赖
<packaging>war</packaging>
<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
配置web.xml
配置SpringMVC的前端控制器DispatcherServlet
SpringMVC的配置文件默认位置和名称(因为Servlet封装到了前端控制器DispatcherServlet中。
所以读取配置文件也由它完成,那名称跟位置就有要求)
位置:WEB-INF
名称:<servlet-name>-servlet.xml,即当前配置下的配置文件名为SpringMVC-servlet.xml
url-pattern中/和/*的区别
/:匹配浏览器向服务器发送的所有请求(不包括.jsp)
/*:匹配浏览器向服务器发送的所有请求(包括.jsp)
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--设置SpringMVC配置文件的位置和名称-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMVC-servlet.xml</param-value>
</init-param>
<!--将DispatcherServlet初始化时间提前到服务器启动时;如果第一次访问时初始化的话,会花费大量时间-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
配置字符编码过滤器
<!--配置Spring的编码过滤器-->
<!--SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效-->
<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>
配置映射文件
扫描组件
<context:component-scan base-package="com.spring"></context:component-scan>
配置Thymeleaf视图解析器
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
视图控制器
视图控制器:为当前的请求直接设置视图名称实现页面跳转 若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他的请求将全部404 此时必须在配置一个标签: <mvc:annotation - driven />
<!--该设置就相当于,设置了请求路径为/的视图转发位置-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
那么下面这个设置就可以免了
@RequestMapping("/")
public String index(){
return "index";
}
像这样的设置在springboot中可以设置/路径默认跳转index
<!--添加按钮默认跳转页面-->
<mvc:view-controller path="/add" view-name="add"></mvc:view-controller>
开启mvc的注解驱动
<!--开启mvc的注解驱动-->
<!--<mvc:annotation-driven/>-->
@RequestMapping("/")
public String index(){
return "index";
}
浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器 DispatcherServlet处理。前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器, 将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的 控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会 被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应页面
@RequestMapping
@RequestMapping标识一个类:设置映射请求的请求路径的初始信息
@RequestMapping标识一个方法:设置映射请求请求路径的具体信息
@RequestMapping注解的value属性
作用:
通过请求的请求路径匹配请求value属性时数组类型,即当前浏览器所发送请求路径匹配value中的任何一个值则当前请求就会被注解所标注的方法进行处理
@RequestMapping注解的method属性
作用:
- 通过请求的方式匹配请求
method属性时RequestMethod类型的数组,即当前浏览器所发送请求方式匹配method属性中的任何一个请求方式,则当前请求就会别注解标注的方法进行处理 - 若浏览器所发送的请求的路径和
@RequestMapping中value属性匹配,但是method中的请求方式错误 此时页面报错:405 -Request method 'xxx' not supported
#### @RequestMapping注解的params属性
作用:
@RequestMapping注解的params属性通过请求的请求参数匹配请求映射
@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数
和请求映射的匹配关系
"param":要求请求映射所匹配的请求必须携带param请求参数
!param":要求请求映射所匹配的请求必须不能携带param请求参数
"param=value":要求请求映射所匹配的请求必须携带param请求参数且param=value
"param!=value":要求请求映射所匹配的请求可以不携带param请求参数但是携带就必须param!=value
@RequestMapping注解的headers属性
作用:
通过请求的请求头信息匹配请求,即浏览器发送的请求的请求头信息必须满足headers属性的设置 若浏览器所发送的请求的请求路径和RequestMapping注解value属性匹配,但是请求头信息不匹配 此时页面报错: 404
@RequestMapping(
value = {"/hello","/hello2"},
method ={RequestMethod.GET,RequestMethod.POST},
/*
若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时
页面回报错400:Parameter conditions
*/
params = {"username=zmj","gender!=14"},
headers = {"referer"}
)
public String success(){
return "success";
}
springMVC支持ant风格的路径
在@Reques tMapping注解的value属性值中设置一些特殊 字符
?:任意的单个字符(不包括? )
*:任意个数的任意字符(不包括?和/)
**:任意层数的任意目录,注意使用方式只能把**写在双斜线中,前后不能有任何的其他字符
@RequestMapping("/test/ant?/test/**/")
public String testAnt(){
return "success";
}
#### @RequestMapping注解使用路径中的占位符
@PathVariable
传统: /deleteUser?id=1
rest: /user/delete/1
需要在@RequestMapping注解的value属性中所设置的路径中,使用[xxx} 的方式表示路径中的数据
在通过@PathVariable注解,将占位符所标识的值和控制器方法的形参进行綁定
/*
获取路径中的占位符,值
*/
@RequestMapping("/test/path/{name}/{id}")
public String testPathValue(@PathVariable("name")String name,@PathVariable("id") Integer id){
System.out.println("name:"+name+",id:"+id);
return "success";
}
<a th:href="@{/test/antt/test}">测试@RequestMapping注解支持ant型风格的路径</a><br/>
<a th:href="@{/test/path/name/1}">测试@RequestMapping注解支持路径中的占位符</a>
整体流程
/**
* Created by KingsLanding on 2022/8/4 12:54
*
* @RequestMapping标识一个类:设置映射请求的请求路径的初始信息
* @RequestMapping标识一个方法:设置映射请求请求路径的具体信息
* 2、@RequestMapping注解value属性
* 作用:通过请求的请求路径匹配请求
* value属性时数组类型,即当前浏览器所发送请求路径匹配value中的任何一个值
* 则当前请求就会被注解所标注的方法进行处理
* 3.@RequestMapping注解的method属性
* 作用,通过请求的方式匹配请求
* method属性时RequestMethod类型的数组,即当前浏览器所发送请求方式匹配method属性中的任何一个请求方式
* 则当前请求就会别注解标注的方法进行处理
* 若浏览器所发送的请求的路径和@RequestMapping中value属性匹配,但是method中的请求方式错误
* 此时页面报错:405 -Request method 'xxx' not supported
* 4.@RequestMapping注解的params属性
* 作用:
* @RequestMapping注解的params属性通过请求的请求参数匹配请求映射
* @RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数
* 和请求映射的匹配关系
* "param":要求请求映射所匹配的请求必须携带param请求参数
*"!param":要求请求映射所匹配的请求必须不能携带param请求参数
* "param=value":要求请求映射所匹配的请求必须携带param请求参数且param=value
* "param!=value":要求请求映射所匹配的请求可以不携带param请求参数但是携带就必须param!=value
*
* 5、@RequestMapping注解的headers属性
* 作用:通过请求的请求头信息匹配请求,即浏览器发送的请求的请求头信息必须满足headers属性的设置
* 若浏览器所发送的请求的请求路径和RequestMapping注解value属性匹配,但是请求头信息不匹配
* 此时页面报错: 404
*
* 6、springMVC支持ant风格的路径
* 在@Reques tMapping注解的value属性值中设置-些特殊 字符
* ?:任意的单个字符(不包括? )
* *:任意个数的任意字符(不包括?和/)
* **:任意层数的任意目录,注意使用方式只能工*写在双斜线中,前后不能有任何的其他字符
*
* 7、 @RequestMapping注解使用路径中的占位符
* 传统: /deleteUser?id=1
* rest: /user/delete/1
* 需要在@RequestMapping注解的value属性中所设置的路径中,使用[xxx} 的方式表示路径中的数据
* 在通过@PathVariable注解,将占位符所标识的值和控制器方法的形参进行綁定
*
* 解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是
* 必须在web.xml中进行注册
*/
@Controller
//@RequestMapping("/test")
// 此时控制器方法所匹配的的请求的请求路径为/test/..
public class SpringHello {
@RequestMapping("/")
public String index(){
return "index";
}
@RequestMapping(
value = {"/hello","/hello2"},
method ={RequestMethod.GET,RequestMethod.POST},
/*
若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时
页面回报错400:Parameter conditions
*/
params = {"username=zmj","gender!=14"},
headers = {"referer"}
)
public String success(){
return "success";
}
/*
* 6、springMVC支持ant风格的路径
* 在@Reques tMapping注解的value属性值中设置-些特殊 字符
* ?:任意的单个字符(不包括? )
* *:任意个数的任意字符(不包括?和/)
* **:任意层数的任意目录,注意使用方式只能把**写在双斜线中,前后不能有任何的其他字符
*/
@RequestMapping("/test/ant?/test/**/")
public String testAnt(){
return "success";
}
/*
获取路径中的占位符,值
*/
@RequestMapping("/test/path/{name}/{id}")
public String testPathValue(@PathVariable("name")String name,@PathVariable("id") Integer id){
System.out.println("name:"+name+",id:"+id);
return "success";
}
/*
获取请求参数的方式:ServletAPI
在控制方法的形参位置设置HttpServletRequest类型的形参
就可以在控制器方法中使用request对象获取请求参数
*/
@RequestMapping("/getParameter")
public String testGetParameter(HttpServletRequest request){
HttpSession session = request.getSession();
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println(name+password);
return "success";
}
/*
3. @RequestParam:将请求参数和控制器方法的形参绑定
@RequestParam注解的三个属性: value. required. defaultValue
value :设置和形参绑定的请求参数的名字
required;设置是否必须传输value所对应的请求参数
默认值为true,表示value所对应的请求参数必须传输,否则页面报错:
400 - Required string parameter 'xxx' is not present
若设置为false,则表示value所对应的请求参数不是必须传翰,若为传输,则形参值为null
defaultValue:设置当没有传输Value所对应的请求参数时,为形参设置的默认值,此时和required属性
@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@CookieValue是将cookie数据和控制器方法的形参创建映射关系
@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
*/
@RequestMapping("/getSpringParameter")
public String testSpringParameter(
@RequestParam(value = "Name",required = false,defaultValue = "zmj") String name,String password,
@CookieValue("JSESSIONID") String jsessionid,
@RequestHeader("referer") String referer
){
System.out.println("name:"+name+",password"+password);
System.out.println(jsessionid);
System.out.println(referer);
return "success";
}
/*
可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实
体类中的属性名一致,那么请求参数就会为此属性赋值
*/
@RequestMapping("/PojoParameter")
public String testPojoParameter(User user){
System.out.println(user);//User{name='123', password='123'}
return "success";
}
}
获取请求参数的方式:
ServletAPI
获取请求参数的方式:ServletAPI
在控制方法的形参位置设置HttpServletRequest类型的形参
就可以在控制器方法中使用request对象获取请求参数
/*
获取请求参数的方式:ServletAPI
在控制方法的形参位置设置HttpServletRequest类型的形参
就可以在控制器方法中使用request对象获取请求参数
*/
@RequestMapping("/getParameter")
public String testGetParameter(HttpServletRequest request){
HttpSession session = request.getSession();
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println(name+password);
return "success";
}
@RequestParam:将请求参数和控制器方法的形参绑定
@RequestParam:将请求参数和控制器方法的形参绑定
@RequestParam注解的三个属性: value、required、 defaultValue
value :设置和形参绑定的请求参数的名字
required;设置是否必须传输value所对应的请求参数
默认值为true,表示value所对应的请求参数必须传输,否则页面报错:
400 - Required string parameter 'xxx' is not present
若设置为false,则表示value所对应的请求参数不是必须传输,若未传输,则形参值为null
defaultValue:设置当没有传输Value所对应的请求参数时,为形参设置的默认值,此时和required属性
@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@CookieValue是将cookie数据和控制器方法的形参创建映射关系
@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@RequestMapping("/getSpringParameter")
public String testSpringParameter(
@RequestParam(value = "Name",required = false,defaultValue = "zmj") String name,String password,
@CookieValue("JSESSIONID") String jsessionid,
@RequestHeader("referer") String referer
){
System.out.println("name:"+name+",password"+password);
System.out.println(jsessionid);
System.out.println(referer);
return "success";
}
<form th:action="@{/getSpringParameter}" th:method="get">
<input type="text" name="Name" placeholder="name">
<input type="password" name="password" placeholder="password">
<input type="submit" value="登陆">
</form>
实体类类型的形参
可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实 体类中的属性名一致,那么请求参数就会为此属性赋值
@RequestMapping("/PojoParameter")
public String testPojoParameter(User user){
System.out.println(user);//User{name='123', password='123'}
return "success";
}
<form th:action="@{/PojoParameter}" th:method="get">
<input type="text" name="Name" placeholder="name">
<input type="password" name="password" placeholder="password">
<input type="submit" value="登陆">
</form>
向域对象共享数据
1.通过ModeLAndView向请求域共享数据
使用ModelAndView时, 可以使用其Model功能向请求域共享数据 使用View功能设置逻辑视图,但是控制器方法一定要将ModeLAndView作为方法的返回值
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/*
ModelAndView包含Model和View的功能
Model:向请求域中共享数据
View:设置逻辑视图实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域中共享数据
mav.addObject("testAttribute","modelAndView");
//设置逻辑视图
mav.setViewName("success");
return mav;
}
2.使用Model向请求域共享数据
//model
@RequestMapping("/model")
public String testModel(Model model){
model.addAttribute("testAttributeModel","model");
return "success";
}
3.使用ModelMap向请求域共享数据
//modelMap
@RequestMapping("/modelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testAttribute","modelMap");
return "success";
}
4.使用map向请求域共享数据
//map
@RequestMapping("/map")
public String testMap(Map<String,Object> map){
map.put("testAttribute","map");
return "success";
}
Model 和ModeLMap和map的关系
其实在底层中,这些类型的形参最终都是通过BindingAwareModeLMap创建的
public class BindingAwareModelMap extends ExtendedModeLMap {}
public class ExtendedModeLMap extends ModeLMap implements Model {}
public class ModeLMap extends LinkedHashMap<string, object>
<a th:href="@{/testModelAndView}">测试通过ModelAndView共享域数据</a><br/>
<a th:href="@{/model}">测试通过model共享request域数据</a><br/>
<a th:href="@{/modelMap}">测试通过modelMap共享request域数据</a><br/>
<a th:href="@{/map}">测试通过map共享request域数据</a><br/>
<a th:href="@{/session}">测试通过session共享域数据</a><br/>
<a th:href="@{/application}">测试通过application共享域数据</a><br/>
整体流程
/**
* Created by KingsLanding on 2022/8/5 13:06
*
*
* 向域对象共享数据:
* 1.通过ModeLAndView向谓求域共享数据
* 使用ModelAndView时, 可以使用其Model功能向请求域共享数据
* 使用View功能设置逻辑视图,但是控制器方法一定要将ModeLAndView作为方法的返回值
*
* 2.使用Model向请求域共享数据
* 3.使用ModelMap向请求域共享数据
* 4.使用map向请求域共享数据
* 5. Model 和ModeLMap和map的关系
* 其实在底层中,这些类型的形参最终都是通BindingAwareModeLMap创建
* public class BindingAwareModelMap extends ExtendedModeLMap {}
* public class ExtendedModeLMap extends ModeLMap implements Model {}
* public class ModeLMap extends LinkedHashMap<string, object>
*
*/
@Controller
public class ModelAndViewController {
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/*
ModelAndView包含Model和View的功能
Model:向请求域中共享数据
View:设置逻辑视图实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向请求域中共享数据
mav.addObject("testAttribute","modelAndView");
//设置逻辑视图
mav.setViewName("success");
return mav;
}
//model
@RequestMapping("/model")
public String testModel(Model model){
model.addAttribute("testAttributeModel","model");
return "success";
}
//modelMap
@RequestMapping("/modelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testAttribute","modelMap");
return "success";
}
//map
@RequestMapping("/map")
public String testMap(Map<String,Object> map){
map.put("testAttribute","map");
return "success";
}
//session域对象
@RequestMapping("/session")
public String testSession(HttpSession session){
session.setAttribute("testAttributeSession","session");
return "success";
}
//application
@RequestMapping("/application")
public String testApplication(HttpSession session){
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("testAttributeApplication","application");
return "success";
}
}
转发视图--重定向视图
转发视图
SpringMVC中默认的转发视图是InternalResourceView
SpringMVC中创建转发视图的情况:
当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,此时的视
图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"forward:"去掉,剩余部
分作为最终路径通过转发的方式实现跳转
例如"forward:/","forward:/employee"
重定向视图
SpringMVC中默认的重定向视图是RedirectView
@RequestMapping("/testHello")
public String testHello(){
return "hello";
}
@RequestMapping("/testForward")
public String testForward(){
return "forward:/testHello";
}
配置默认的servlet处理静态资源
-
因为
DispatcherServlet处理不了静态资源 这个配置必须和注解驱动联合使用,当DispatcherServlet处理不了,那么就用tomcat默认的servlet来处理静态资源 -
当前工程的web.xml配置的前端控制器
DispatcherServlet的url-pattern是/tomcat的web.xml配置的DefaultServlet的url-pattern也是/ -
此时,浏览器发送的请求会优先被
DispatcherServlet进行处理,但是DispatcherServlet无法处理静态资源 -
若配置了**<mvc:default-servlet-handler />,此时浏览器发送的所有请求都会由
DefaultServlet处理 若配置了<mvc:default-servlet .handler />和<mvc:annotation-driven />**浏览器发送的请求会先被
DispatcherServlet处理,无法处理再交给DefaultServlet处理
<mvc:default-servlet-handler/>
<!--注解驱动-->
<mvc:annotation-driven/>
rest风格
REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方 式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性
它们分别对应四种基本操作**:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源**。
HiddenHttpMethodFilter
由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?
SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
- HiddenHttpMethodFilter 处理put和delete请求的条件:
- 当前请求的请求方式必须为post
- 当前请求必须传输请求参数_method 满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数 _method的值,因此请求参数_method的值才是最终的请求方式
在web.xml中注册HiddenHttpMethodFilter
<!--设置处理请求方式的过滤器-->
<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>
注意:浏览器目前只能发送get和post请求 若要发送put和delete清求,需要在web.xmL中配置-个过滤器HiddenHttpMethodFilter 配置了过滤器之后,发送的请求要满足两个条件,才能将请求方式转换 为put或delete 1.当前请求必须为post 2.当前请求必须传输请求参数method,_method的value值才是最终的请求方式
@Controller
public class TestRESTcontroller {
@RequestMapping(
value = "/user",
method = RequestMethod.GET
)
public String testREST(){
System.out.println("查询所有的用户信息-->/user-->get");
return "success";
}
@RequestMapping(
value = "/user/{id}",
method = RequestMethod.GET
)
// @GetMapping("/user")//派生注解
public String getUserById(@PathVariable("id") Integer id){
System.out.println("根据id.查询用户信息-->/user/1-->get"+id);
return "success";
}
@RequestMapping(
value = "/user",
method = RequestMethod.POST
)
// @PostMapping("/user")
public String testPost(){
System.out.println("添加用户信息-->/user-->post");
return "success";
}
@RequestMapping(
value = "/user",
method = RequestMethod.PUT
)
// @PutMapping("/user")
public String testPut(){
System.out.println("修改用户信息-->/user-->put");
return "success";
}
@RequestMapping(
value = "/user/{id}",
method = RequestMethod.DELETE
)
@DeleteMapping("/user/{id}")
public String testDelete(@PathVariable("id")Integer id){
System.out.println("删除用户信息-- >/user/1-->delete"+id);
return "success";
}
}
<body>
<a th:href="@{/user}">测试查询所有用户信息</a>
<a th:href="@{/user/1}">测试通过id查询用户信息</a>
<br/>
<form th:action="@{/user}" th:method="post">
<input type="submit" value="测试添加用户信息post">
</form>
<br/>
<form th:action="@{/user}" th:method="post">
<input type="hidden" name="_method" value="put">
<input type="submit" value="测试修改用户功能put">
</form>
<br/>
<form th:action="@{/user/2}" th:method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="测试删除用户功能delete">
</form>
</body>
测试案例
/**
* Created by KingsLanding on 2022/8/6 0:13
*/
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
}
private static Integer initId = 1006;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employees.put(employee.getId(), employee);
}
public Collection<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
package com.spring.pojo;
import org.springframework.stereotype.Component;
/**
* Created by KingsLanding on 2022/8/6 0:12
*/
@Component
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Employee(Integer id, String lastName, String email, Integer
gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Employee() {
}
}
controller
/**
* Created by KingsLanding on 2022/8/6 0:14
*/
@Controller
public class EmployController {
@Autowired
private EmployeeDao employeeDao;
@RequestMapping(
value = "/index",
method = RequestMethod.GET
)
public String getAllEmploy(HttpSession session){
Collection<Employee> listEmploy = employeeDao.getAll();
session.setAttribute("listEmploy",listEmploy);
return "success";
}
@RequestMapping(
value = "/to/delete/{id}",
method = RequestMethod.DELETE
)
public String deleteEmploy(@PathVariable("id") Integer id){
System.out.println(id);
employeeDao.delete(id);
return "redirect:/index";
}
@RequestMapping(
value = "/to/add",
method = RequestMethod.POST
)
public String addEmploy(Employee employee){
employeeDao.save(employee);
return "redirect:/index";
}
@RequestMapping(
value = "/to/update/{id}",
method = RequestMethod.GET
)
public String getEmploy(@PathVariable("id") Integer id, Model model){
System.out.println(id);
Employee employee = employeeDao.get(id);
model.addAttribute("employee",employee);
return "/update";
}
@RequestMapping(
value = "/employee",
method = RequestMethod.PUT
)
public String updateEmploy(Employee employee){
employeeDao.save(employee);
return "redirect:/index";
}
}
add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>add employee</title>
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<form th:action="@{/to/add}" method="post">
<table>
<tr>
<th colspan="2">add employee</th>
</tr>
<tr>
<td>lastName</td>
<td>
<input type="text" name="lastName">
</td>
</tr>
<tr>
<td>email</td>
<td>
<input type="text" name="email">
</td>
</tr>
<tr>
<td>gender</td>
<td>
<input type="radio" name="gender" value="1">male
<input type="radio" name="gender" value="0">female
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="add">
</td>
</tr>
</table>
</form>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>update employee</title>
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<form th:action="@{/employee}" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="id" th:value="${employee.id}">
<table>
<tr>
<th colspan="2">update employee</th>
</tr>
<tr>
<td>lastName</td>
<td>
<input type="text" name="lastName" th:value="${employee.lastName}">
</td>
</tr>
<tr>
<td>email</td>
<td>
<input type="text" name="email" th:value="${employee.email}">
</td>
</tr>
<tr>
<td>gender</td>
<td>
<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
<input type="radio" name="gender" value="0" th:field="${employee.gender}">female
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="update">
</td>
</tr>
</table>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<div id="app">
<table border="1">
<tr>
<td>id</td>
<td>lastName</td>
<td>email</td>
<td>gender</td>
<td colspan="2"><a th:href="@{/add}">添加</a></td>
</tr>
<tr th:each="listEmploy : ${session.listEmploy}">
<td th:text="${listEmploy.id}"></td>
<td th:text="${listEmploy.lastName}"></td>
<td th:text="${listEmploy.email}"></td>
<td th:text="${listEmploy.gender}"></td>
<td><a @click="deleteEmployee()" th:href="@{'/to/delete/'+${listEmploy.id}}">删除</a> </td>
<td><a th:href="@{'/to/update/'+${listEmploy.id}}">修改</a> </td>
</tr>
</table>
<form action="" th:method="post">
<input type="hidden" name="_method" value="delete">
</form>
</div>
<script language="JavaScript" th:src="@{static/js/vue.js}"></script>
<script type="text/javascript">
var vue = new Vue({
el:"#app",
methods:{
deleteEmployee(){
//获取form表单
var form = document.getElementsByTagName("form")[0];
//将超链接的href属性值赋值给form表单的action属性
//event.target表示当前触发事件的标签
form.action = event.target.href;
//表单提交
form.submit();
//阻止超链接的默认行为
event.preventDefault();
}
}
});
</script>
</body>
</html>
SpringMVC处理ajax请求
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
@RequestBody
1、@RequestBody:将请求体中的内容和控制器方法的形参进行绑定
2、使用@RequestBody注解将json格式的请求参数转换为java对象
a>导入jackson的依赖
b>在SpringMVC的配置文件中设置**<mvc:annotation-driven />**
c>在处理请求的控制器方法的形参位置,直接设置json格式的请求参数要转换的java类型的形参,使用@RequestBody注解标识即可
@RequestMapping(
"/test/ajax"
)
public void testGetAjax(Integer id, @RequestBody String requestBody, HttpServletResponse response) throws IOException {
System.out.println(requestBody);
System.out.println("id:"+id);
response.getWriter().write("hello");
//{"username":"admin","password":"123123"}
//id:1001
}
// @RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
System.out.println(map);
response.getWriter().write("hello,RequestBody");
}
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody User user, HttpServletResponse response) throws IOException {
System.out.println(user);
response.getWriter().write("hello,RequestBody");
}
前端json数据发送
<input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br>
<input type="button" value="使用@RequestBody注解处理json格式的请求参数" @click="testRequestBody()"><br>
var vue = new Vue({
el:"#app",
methods:{
testAjax(){
axios.post(
"/SpringMVC/test/ajax?id=1001",
{username:"admin",password:"123123"}
).then(function (value) {
console.log(data)
});
},
testRequestBody(){
axios.post(
"/SpringMVC/test/RequestBody/json",
{username:"admin",password:"123456",age:23,gender:"男"}
).then(function (value){
console.log(data);
});
},
testResponseBody(){
axios.post(
"/SpringMVC/test/ResponseBody/json"
).then(function (value) {
console.log(value)
})
}
}
});
axios({
url:"",//请求路径
method:"",//请求方式
//以name=value&name=value的方式发送的请求参数
//不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
//此种方式的请求参数可以通过request.getParameter()获取
params:{},
//以json格式发送的请求参数
//请求参数会被保存到请求报文的请求体传输到服务器
//此种方式的请求参数不可以通过request.getParameter()获取
data:{}
}).then(response=>{
console.log(response.data);
});
@ResponseBody
3、@ResponseBody:将所标识的控制器方法的返回值作为响应报文的响应体响应到浏览器
4、使用@ResponseBody注解响应浏览器json格式的数据
a>导入jackson的依赖
b>在SpringMVC的配置文件中设置<mvc:annotation-driven />
c>将需要转换为json字符串的java对象直接作为控制器方法的返回值,使用@ResponseBody注解标识控制器方法,就可以将java对象直接转换为json字符串,并响应到浏览器
常用的Java对象转换为json的结果: 实体类-->json对象 map-->json对象 list-->json数组
@RequestMapping("/test/ResponseBody/json1")
@ResponseBody
public User testResponseBody(){
/*
将需要转换为json字符串的java对象直接作为控制器方法的返回值,
使用@ResponseBody注解标识控制器方法就可以将java对象直接转换为json字符串,并响应到浏览器
*/
User user = new User(1, "zmj", "123123", 22, "男");
return user;
}
@RequestMapping("/test/ResponseBody/json")
@ResponseBody
public Map<String,User> testMapResponseJson(){
User user1 = new User(1, "zmj1", "123123", 22, "男");
User user2 = new User(2, "zmj2", "123123", 23, "男");
User user3 = new User(3, "zmj3", "123123", 24, "男");
Map<String, User> userMap = new HashMap<>();
userMap.put("1",user1);
userMap.put("2",user2);
userMap.put("3",user3);
return userMap;
}
<input type="button" value="使用@ResponseBody注解响应json格式的数据" @click="testResponseBody()"><br>
testResponseBody(){
axios.post(
"/SpringMVC/test/ResponseBody/json"
).then(function (value) {
console.log(value)
})
}
查看浏览器信息F12
@RestController
@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了 @Controller注解,并且为其中的每个方法添加了@ResponseBody注解
文件上传下载
/**
* Created by KingsLanding on 2022/8/6 21:57
*/
@Controller
public class FileDownAndUp {
@RequestMapping("/test/up")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
//获取上传的文件的后缀名
String hzName = fileName.substring(fileName.lastIndexOf("."));
//获取uuid
String uuid = UUID.randomUUID().toString();
//拼接一个新的文件名
fileName = uuid + hzName;
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取当前工程下photo目录的真实路径
String photoPath = servletContext.getRealPath("photo");
//创建photoPath所对应的File对象
File file = new File(photoPath);
//判断file所对应目录是否存在
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//上传文件
photo.transferTo(new File(finalPath));
return "redirect:index";
}
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("img");
realPath = realPath + File.separator + "wallhaven-o3orj7.jpg";
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组,is.available()获取输入流所对应文件的字节数
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}
}
文件上传
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象
并且该bean必须设置id="multipartResolver",因为ByName
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
点击:<input type="file" name="photo">
<input type="submit" value="上传">
</form>
</div>
<img th:src="@{img/wallhaven-o3orj7.jpg}" width="500px" height="500px">
<a th:href="@{/test/down}">下载图片</a>
拦截器
拦截器的三个方法:
preHandle():在控制器方法执行之前执行,其返回值表示对控制器方法的拦截(false)或放行(true)
postHandle():在控制器方法执行之后执行
afterCompletion():在控制器方法执行之后,且渲染视图完毕之后执行
多个拦截器的执行顺序和在SpringMVC的配置文件中配置的顺序有关 preHandle()按照配置的顺序执行,而postHandle()和afterCompletion()按照配置的反序执行
<mvc:interceptors>
<!--bean和ref标签所配置的拦截器默认对DispatcherServlet处理的所有请求进行拦截-->
<!--<bean class="com.spring.interceptor.FirstInterceptor"></bean>-->
<!--扫描到了这个组件,默认名-->
<!--<ref bean="firstInterceptor"></ref>-->
<!--这种配置更加精确-->
<mvc:interceptor>
<!--设置拦截请求路径/*代表只拦截一层目录的请求,/**表示拦截所有请求-->
<mvc:mapping path="/**"/>
<!--设置不拦截的请求路径-->
<mvc:exclude-mapping path="/app"/>
<ref bean="firstInterceptor"/>
</mvc:interceptor>
<ref bean="secondInterceptor"></ref>
</mvc:interceptors>
测试
FirstInterceptor
@Component
public class FirstInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
SecondInterceptor
@Component
public class SecondInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("SecondInterceptor_preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("SecondInterceptor_postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("SecondInterceptor_afterCompletion");
}
}
请求测试
@Controller
public class testController {
@RequestMapping("/test/extension")
public String testFirstInterceptor(){
//System.out.println(1/0);
return "success";
}
}
测试结果
多个拦截器的执行顺序和在SpringMVC的配置文件中配置的顺序有关 preHandle()按照配置的顺序执行,而postHandle()和afterCompletion()按照配置的反序执行
preHandle
SecondInterceptor_preHandle
SecondInterceptor_postHandle
postHandle
SecondInterceptor_afterCompletion
afterCompletion
异常处理器
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和 SimpleMappingExceptionResolver SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<!--
properties的键表示处理器方法执行过程中出现的异常
properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
-->
<props>
<!--key设置要处理的异常,value设置出现该异常时要跳转的页面所对应的逻辑视图-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--设置共享在请求域中的异常信息的属性名-->
<!--
exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
基于注解的异常处理
//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(ArithmeticException.class)
//ex表示当前请求处理中出现的异常对象
public String handleArithmeticException(Exception ex, Model model){
model.addAttribute("ex", ex);
return "error";
}
}
SpringMVC执行流程
SpringMVC常用组件
DispatcherServlet:前端控制器,不需要工程师开发,由框架提供
作用:统一处理请求和响应,整个流程控制的中心,由它调用其它组件处理用户的请求
HandlerMapping:处理器映射器,不需要工程师开发,由框架提供
作用:根据请求的url、method等信息查找Handler,即控制器方法
Handler:处理器,需要工程师开发
作用:在DispatcherServlet的控制下Handler对具体的用户请求进行处理
HandlerAdapter:处理器适配器,不需要工程师开发,由框架提供
作用:通过HandlerAdapter对处理器(控制器方法)进行执行
ViewResolver:视图解析器,不需要工程师开发,由框架提供
作用:进行视图解析,得到相应的视图,例如:ThymeleafView、InternalResourceView、
RedirectView
View:视图
作用:将模型数据通过页面展示给用户
流程概述
1) 用户向服务器发送请求,请求被SpringMVC 前端控制器 DispatcherServlet捕获。
2) DispatcherServlet对请求URL进行解析,得到请求资源标识符(URI),判断请求URI对应的映射:
a) 不存在
i. 再判断是否配置了mvc:default-servlet-handler
ii. 如果没配置,则控制台报映射查找不到,客户端展示404错误
iii. 如果有配置,则访问目标资源(一般为静态资源,如:JS,CSS,HTML),找不到客户端也会展示404
错误
b) 存在则执行下面的流程
3) 根据该URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及
Handler对象对应的拦截器),最后以HandlerExecutionChain执行链对象的形式返回。
4) DispatcherServlet 根据获得的Handler,选择一个合适的HandlerAdapter。
5) 如果成功获得HandlerAdapter,此时将开始执行拦截器的preHandler(…)方法【正向】
6) 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)方法,处理请求。
在填充Handler的入参过程中,根据你的配置,Spring将帮你做一些额外的工作:
a) HttpMessageConveter: 将请求消息(如Json、xml等数据)转换成一个对象,将对象转换为指定
的响应信息
b) 数据转换:对请求消息进行数据转换。如String转换成Integer、Double等
c) 数据格式化:对请求消息进行数据格式化。 如将字符串转换成格式化数字或格式化日期等
d) 数据验证: 验证数据的有效性(长度、格式等),验证结果存储到BindingResult或Error中
7) Handler执行完成后,向DispatcherServlet 返回一个ModelAndView对象。
8) 此时将开始执行拦截器的postHandle(...)方法【逆向】。
9) 根据返回的ModelAndView(此时会判断是否存在异常:如果存在异常,则执行
HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver进行视图解析,根据Model
和View,来渲染视图。
10) 渲染视图完毕执行拦截器的afterCompletion(…)方法【逆向】。
11) 将渲染结果返回给客户端。