SpringMvc
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视图,渲染数据最终响应给浏览器。
2.什么是SpringMvc
SpringMvc是Spring的一个后续产品,是Spring的一个子项目
三层架构分别为表述层、业务逻辑层、数据访问层,表述层表示前台页面和后台servlet
3.SpringMvc跳转首页
- 在web.xml中配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置SpringMVC的前端控制器,对浏览器发送的请求进行统一处理-->
<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.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>
</web-app>
- 在初始化参数标签中配置参数路径pringMVC.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描组件-->
<context:component-scan base-package="com.wyf.controller"></context:component-scan>
<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>
</beans>
- 测试
@Controller
public class HelloController {
//当前请求路径"/"--->WEB-INF/templates/index.html
@RequestMapping("/")
public String index(){
//返回视图名称
return "index";
}
}
4.SpringMvc跳转指定页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/target}">访问目标页面</a>
</body>
</html>
@RequestMapping("/target")
public String toTarget(){
return "target";
}
-
流程总结:
浏览器发送请求,若请求地址符合前端控制器的url-pattern(访问路径),该请求就会被前端控制器DispatcherServlet(在web.xml中已经配好)处理。前端控制器会读取SpringMvc的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应界面。
5.@RequestMapping注解
1、@RequestMapping注解的功能
从注解名称上可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器关联起来,建立映射关系。SpringMVC接收到指定的请求,就会找到在映射关系中对应的控制器方法来处理这个请求。
2、@RequestMapping注解的位置
@RequestMapping注解可以标识一个类,也可以标识一个方法
@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
return "success";
}
}
3、@RequestMapping注解的value属性
@RequestMapping注解的value属性通过请求的请求地址匹配请求映射
@RequestMapping注解的value属性是一个字符串类型的数组,标识该请求映射能够匹配多个请求地址所对应的请求,请求满足value属性中String数组中一个就可以。
@RequestMapping注解的value属性必须设置值,至少通过请求地址匹配请求映射
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping
@RequestMapping({"/testRequestMapping","/hello"})
public String testRequestMapping(){
return "success";
}
}
4、@RequestMapping注解的method属性
@RequestMapping注解的method属性通过请求方式(get或post)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求能够匹配多种请求方式的请求
若当前的请求地址满足请求映射的value属性,但是请求方式不满足method属性,浏览器报错405
@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射的请求路径为:/test/testRequestMapping,请求方式get和post都可以
@RequestMapping(value = {"/testRequestMapping","/hello"},
method = {RequestMethod.GET,RequestMethod.POST})
public String testRequestMapping(){
return "success";
}
}
5、SpringMVC提供的@RequestMapping派生注解
处理get请求的映射—>@GetMapping
处理post请求的映射—>@PostMapping
处理put请求的映射—>@PutMapping
处理delete请求的映射—>@DeleteMapping
- 常用的请求方式有get、post、put、delete,但是浏览器只支持get和pos若在form表单提交时,为method设置了其它请求方式(put或者delete),则按照默认的请求方式get来处理
6、@RequestMapping注解的params属性
@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置参数和请求映射的匹配关系
“param”:要求请求映射所匹配的请求必须携带param请求参数
params = {“username”}
“!param”:要求请求映射所匹配的请求必须不能携带param请求参数
params = {“!username”}
“param”:要求请求映射所匹配的请求必须携带param请求参数且参数值param=value
params = {“username=admin”}
“param!=value”:要求请求映射所匹配的请求必须携带param请求参数且参数值param=!value
params = {“username=!admin”}
6.SpringMVC支持ant风格的路径
?:表示任意的单个字符
@RequestMapping(“/a?a/testAnt”)
*:表示任意的0个或多个字符
@RequestMapping(“/a*a/testAnt”)
**:表示任意的一层或多层目录
@RequestMapping(“/a/**/a/testAnt”)
注意:在使用 * * 时,只能使用/ * * /xxx的方式
7.SpringMVC支持路径中的占位符(重点)
原始方式:/deleteUser?id=1
rest方式:/deleteUser/1
SpringMVC路径中的占位符常用于restful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参
@RequestMapping("/rest/{id}/{username}")
public String rest(@PathVariable("id") String id,
@PathVariable("username") String username){
System.out.println("id:" + id + ",username:" + username);
return "success";
}
8.SpringMVC获取请求参数
1.通过ServletAPI获取
<h1>测试请求参数</h1>
<a th:href="@{/testServletAPI(username='admin',password=123456)}">测试使用ServletAPI获取请求参数</a>
@Controller
public class ParamController {
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:" + username + ",password:" + password);
return "success";
}
}
2.通过控制器方法的形参获取请求参数
<form th:action="@{/testParam}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:<input type="checkbox" name="hobby" value="a">a
<input type="checkbox" name="hobby" value="b">b
<input type="checkbox" name="hobby" value="c">c<br>
<input type="submit" value="使用控制器的形参获取请求参数">
</form>
@RequestMapping("/testParam")
public String testParam(String username,String password,String[] hobby){
//多请求参数中出现多个同名的请求参数,http://localhost:8080/testParam? username=admin&password=123&hobby=a&hobby=b
//可以在控制器方法的形参中设置字符串或者字符串数组类型的形参来接收请求参数
System.out.println(username + password + Arrays.toString(hobby));
return "success";
}
3.@RequestParam
@RequestParam是将请求参数和控制器方法的形参创建映射关系
该注解一共有三个属性:
value:指定为形参赋值的请求参数的参数名
required:设置是否必须传输此参数,默认值为true
defaultValue:不管required的属性值为true或false,当value指定的请求参数没有传输或传输值为空时,使用默认值为形参赋值
@RequestMapping("/testParam")
public String testParam(@RequestParam(value = "user_name",required = false,
defaultValue = "hello") String username, String password, String[] hobby){
return "success";
}
4.@RequestHeader
@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@RequestMapping("/testParam")
public String testParam(@RequestHeader("Host") String host){
System.out.println(host);//localhost:8080
return "success";
}
5.@CookieValue
@CookieValue是将cookie数据和控制器方法的形参创建映射关系
@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam
@RequestMapping("/testParam")
public String testParam(@CookieValue("JSESSIONID") String JSESSIONID){
//request.getSession();需要获取Session,JSESSIONID才能够存在
System.out.println(JSESSIONID);
return "success";
}
9.通过POJO获取请求参数
<form th:action="@{testPOJO}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
年龄:<input type="text" name="age"><br>
邮箱:<input type="text" name="email"><br>
<input type="submit" value="实体类接收请求参数">
</form>
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String email;
}
@RequestMapping("/testPOJO")
public String testPOJO(User user){
System.out.println(user);
//User{id=null, username='admin', password='123456', age=18, email='861364173@qq.com'}
return "success";
}
- 处理响应乱码问题(在web.xml中配置filter)
<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>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
10. 域对象共享数据
1.使用servletAPI向request域对象共享数据(不建议)
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){
request.setAttribute("testRequestScope","wyf");
Object attribute = request.getAttribute("testRequestScope");
System.out.println(attribute);//wyf
return "success";
}
<p th:text="${testRequestScope}"></p>//显示request域中对应的值wyf
2.使用ModelAndView向request域对象共享数据(SpringMVC推荐使用)
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
/*
* ModelAndView有Model和View功能
* Model主要用于向请求域中共享数据
* View主要用于设置视图,实现页面跳转
* 方法的返回值必须是ModelAndView
* */
ModelAndView modelAndView = new ModelAndView();
//向请求域中共享数据
modelAndView.addObject("testModelAndView","wyf");
//设置视图,实现页面跳转
modelAndView.setViewName("success");
return modelAndView;
}
<p th:text="${testModelAndView}"></p>//显示request域中对应的值wyf
3.使用Model向request域对象共享数据
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testModel","wyf");
return "success";
}
<p th:text="${testModel}"></p>//显示request域中对应的值wyf
4.使用map向request域对象共享数据
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("testMap","wyf");
return "success";
}
<p th:text="${testMap}"></p>//显示request域中对应的值wyf
5.使用ModelMap向request域对象共享数据
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute("testModelMap","csq");
return "success";
}
<p th:text="${testModelMap}"></p>//显示request域中对应的值csq
6.Model、ModelMap、Map的关系
Model、ModelMap、Map类型的参数其实本质上都是BindingAwareModelMap类型的
- 观察源码后,控制器方法执行后都会返回统一的ModelAndView对象
7.向session域中共享数据
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSession","hello session");
return "success";
}
<p th:text="${session.testSession}"></p>显示session域中对应的值hello session
- 浏览器不关,session中的数据就不会消失(或者半个小时未操作session数据)
8.向application域共享数据
@RequestMapping("/testApplication")
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("testApplication","hello application");
return "success";
}
<p th:text="${application.testApplication}"></p>显示application域中对应的值hello application
- 服务器不关,application中的数据就会一直存在
11.SpringMVC的视图
SpringMVC中的视图是View接口,视图的作用是渲染数据,将模型Model中的数据展示给用户
SpringMVC视图种类有很多,默认有转发视图InternalResourceView和重定向视图RedirectView
1.转发视图(转发请求)
@Controller
public class ViewController {
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
return "success";
}
@RequestMapping("/testForward")
public String testForward(){
return "forward:/testThymeleafView";
}
}
2.重定向视图
@Controller
public class ViewController {
@RequestMapping("/testThymeleafView")
public String testThymeleafView(){
return "success";
}
@RequestMapping("/testRedirect")
public String testForward(){
return "redirect:/testThymeleafView";
}
}
3.视图控制器view-controller
当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用view-controller标签进行表示
<!--
path:设置处理的请求地址
view-name:设置请求地址所对应的视图名称
当SpringMVC中设置任何一个view-controller时,其他控制器的请求映射将全部失效
需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签
-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--开启MVC的注解驱动-->
<mvc:annotation-driven/>
<!--开启对静态资源的访问-->
<mvc:default-servlet-handler/>
12.RESTFul
1.模拟get和post请求方式
@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
public String getUserById(@PathVariable("userId") Integer userId ){
System.out.println("根据" + userId + "查询用户信息");
return "success";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String insertUser(String username,String password){
System.out.println("添加用户信息:" + username + password);
return "success";
}
2.模拟put和delete请求方式
- 根据源码,处理put请求,需要配置过滤器,浏览器method需要为post,需要传递一个隐藏参数为PUT
<!-- 配置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>
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="PUT">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="修改"><br>
</form>
3.CharacterEncodingFilter和HiddenHttpMethodFilter执行顺序
- 如果url-pattern一样,默认从上至下
- HiddenHttpMethodFilter中有了请求参数,在CharacterEncodingFilter上方,CharacterEncodingFilter就会失效,应该把没有请求参数的CharacterEncodingFilter放在HiddenHttpMethodFilter上面
13.HttpMessageConverter
HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文
HttpMessageConverter提供了两个注解和两个类型:@RequestBody,@ResponseBody,RequestEntity,ResponeEntity
1.@RequestBody
@RequestBody可以获取请求体,需要在控制方法中设置一个形参,使用@RequestBody进行标识。当前请求的请求体就会为当前注解所标识的形参赋值
<form th:action="@{/testRequestBody}" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="测试RequestBody">
</form>
@RequestMapping("/testRequestBody")//注意@RequestParam的变量名要和前端input标签的name属性一致
public String testRequestBody(@RequestBody String requestBody ,@RequestParam String username,@RequestParam String password){
System.out.println("requestBody:" + requestBody);//username=admin&password=123456
System.out.println(username);//admin
System.out.println(password);//123456
return "success";
}
2.RequestEntity
<form th:action="@{/testRequestEntity}" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="测试RequestEntity">
</form>
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity<String> requestEntity){
//当前RequestEntity表示的是整个请求报文的信息
System.out.println(requestEntity.getHeaders());
//[host:"localhost:8080", connection:"keep-alive", content-length:"30"...
System.out.println(requestEntity.getBody());
//username=admin&password=123123
return "success";
}
3.@ResponseBody
@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器
加上@ResponseBody注解之后,return “success”;不在作为视图被解析,而是响应给浏览器的数据字符串 “success”
@RequestMapping("/testResponseBody")
@ResponseBody
public String testResponseBody(){
return "success";
}
4.ResponseEntity
ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
ResponseEntity实现文件下载
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContest对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.jpg");
//创建输入流
FileInputStream is = new FileInputStream(realPath);
//创建字节数组
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;
}
5.@RestController(重点)
用在控制器(Controller)的类上,相当于@Controller和@ResponseBody的合体,给控制器类中的所有方法都加上了@ResponseBody,所以方法返回的对象可以转换为响应浏览器数据的响应体传到前端。
14.SpringMVC处理json
@ResponseBody处理json的步骤
-
导入jackson的依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.2.2</version> </dependency>
-
开启mvc的注解驱动
<!--开启MVC的注解驱动--> <mvc:annotation-driven/>
-
在处理器方法上使用@ResponseBody注解进行标识
-
将Java对象直接作为方法的返回值返回,就会自动转换为json格式的字符串,JavaScript会把json格式字符串转换为json对象
@RequestMapping("/testResponseUser") @ResponseBody public User testResponseUser(){ return new User(1,"wyf",18); }
-
浏览器结果
{"id":1,"userName":"wyf","age":18}//json对象
15.实现文件上传
- 导入文件上传依赖包(pom.xml)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 配置文件上传解析器(springMvc.xml)
<!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
- 控制器方法
@RequestMapping("/testUp")
public String testUp(MultipartFile photo,HttpSession session) throws IOException {
String originalFilename = photo.getOriginalFilename();
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath所对应路径是否存在
if (!file.exists()){
//若不存在,则创建目录
file.mkdir();
}
String finalPath = photoPath + File.separator + originalFilename;
photo.transferTo(new File(finalPath));
return "success";
}
- 解决上传文件名重名问题
//获取上传文件的文件名
String originalFilename = photo.getOriginalFilename();
//获取上传文件的文件名,并截取后缀
String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
//将UUID作为文件名
String uuid = UUID.randomUUID().toString();
//将uuid和后缀名拼接后的结果作为最终的文件名
originalFilename = uuid + suffixName;
16.拦截器
1.创建拦截器
- 拦截器执行的三个位置:控制器方法的前后和视图渲染之后
- SpringMVC的拦截器必须在SpringMVC的配置文件中配置
public class FirstInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("-------preHandle-------------");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("--------postHandle-----------");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("-----------afterCompletion---------");
}
}
<!--以下两种配置方式都是对DispatcherServlet所处理的所有请求进行拦截-->
<bean class="com.wyf.Interceptor.FirstInterceptor"></bean>
<ref bean="firstInterceptor"></ref>
<mvc:interceptor>
<!--通过mvc:mapping设置拦截的请求,通过mvc:exclude-mapping设置需要不需要拦截的请求-->
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/testHello"/>
<ref bean="firstInterceptor"></ref>
</mvc:interceptor>
2.拦截器的三个方法
SpringMVC中的拦截器有三个抽象方法:
preHandler:控制器方法执行之前执行,返回值为boolean,返回true表示放行,返回false表示拦截
postHandler:控制器方法执行之后执行
afterComplation:处理完视图和模型数据,渲染视图完毕后执行
3.多个拦截器的执行顺序
- 若每个拦截器的preHandler()都返回true
此时多个拦截器的执行顺序和拦截器在SpringMVC配置文件的顺序有关:
preHandler()会按照配置的顺序执行,而postHandler()和afterComplation会按照配置的反序执行
- 若某个拦截器的preHandler()返回false
preHandler()返回false和它之前的拦截器的preHandler()都会执行,postHandler()都不执行,返回false的拦截器之前的拦截器的afterComplation()都会执行
17.基于注解的异常处理
//执行控制器方法制造异常
@RequestMapping("/testControllerAdvice")
public String testControllerAdvice(){
System.out.println(1/0);
return "success";
}
- 当执行某个控制器方法出现ArithmeticException或NullPointerException异常时,会走@ControllerAdvice标识类中的方法
@ControllerAdvice//将当前类标识为异常处理的组件
public class ExceptionController {
// @ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
public String testException(Exception ex, Model model){
//ex标识当前请求处理中出现的异常对象
model.addAttribute("ex",ex);
return "error";
}
}
18.注解配置SpringMVC
使用配置类和注解代替web.xml和SpringMVC配置文件的功能
1.创建初始化类,代替web.xml
编写WebInit继承AbstractAnnotationConfigDispatcherServletInitializer代替web.xml
//web工程的初始化类,用来代替web.xml
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定spring的配置类
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//指定springMVC的配置类
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
//指定DispatcherServlet的映射规则,即url-pattern
protected String[] getServletMappings() {
return new String[]{"/"};
}
//注册过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceResponseEncoding(true);
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
}
//spring的配置类
@Configuration
public class SpringConfig {
//没有进行具体配置
}
//代替springMvc的配置文件
/* 1.扫描组件
2.视图解析器
3.view-controller
4.default-servlet-handler
5.mvc注解驱动
6.文件上传解析器
7.异常处理
8.拦截器
*/
//将当前类标识为配置类
@Configuration
//1.扫描组件
@ComponentScan("com.wyf")
//5.注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
//4.default-servlet-handler
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}