拦截器和异常处理器
拦截器
拦截器(Interceptor),主要完成请求参数的解析、将页面表单参数赋给值栈中相应属性、执行功能检验、程序异常调试等工作。
准备
创建模块
如下为完整的项目结构
web.xml
<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"><!--配置编码过滤器--><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><!--配置请求方式put和delete的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><!--配置springMVC的前端控制器DispatcherServlet--><servlet><servlet-name>DispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springMVC.xml</param-value></init-param><!--将前端控制器的时间提前到服务器启动时--><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>DispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--开启扫描组件--><context:component-scan base-package="com.louis"></context:component-scan><!--配值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>
</beans>
创建拦截器类FirstInterceptor
package com.louis.interceptors;import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @author XRY* @date 2023年07月04日18:35*/
@Component
public class FirstInterceptor implements HandlerInterceptor {@Override//控制器方法执行之前执行public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("FirstInterceptor----->preHandle");return HandlerInterceptor.super.preHandle(request, response, handler);}@Override//控制器方法执行之后执行public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("FirstInterceptor----->postHandle");HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);}@Override//在视图渲染之后执行public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("FirstInterceptor----->afterCompletion");HandlerInterceptor.super.afterCompletion(request, response, handler, ex);}
}
1、拦截器的配置
SpringMVC中的拦截器用于拦截控制器方法的执行,它需要实现
HandlerInterceptor
或继承HandlerInterceptorAdapter
类(过时)并且必须在SpringMVC的配置文件中进行配置。
法一
<!--法一:该方法会对DispartureServlet所处理的所有请求进行拦截-->
<mvc:interceptors><bean class="com.louis.interceptors.FirstInterceptor"></bean>
</mvc:interceptors>
法二
<!--法二:在FirstInterceptor上添加@Component注解,开启组件扫描,然后使用ref标签,该方法会对DispartureServlet所处理的所有请求进行拦截-->
<mvc:interceptors><ref bean="firstInterceptor"></ref>
</mvc:interceptors>
法三
<!--法三:使用<mvc:interceptor>标签,它可以设置当前的拦截路径-->
<mvc:interceptors><mvc:interceptor><!--/*表示只拦截一层目录,/**表示拦截所有操作--><mvc:mapping path="/**"/><!--排除拦截--><mvc:exclude-mapping path="/"/><ref bean="firstInterceptor"></ref></mvc:interceptor>
</mvc:interceptors>
2、拦截器的三个抽象方法
preHandle
:控制器方法执行之前执行preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法,返回false表示拦截,即不调用控制器方法。
postHandle
:控制器方法执行之后执行postHandle()
afterComplation
:处理完视图和模型数据,渲染视图完毕之后执行afterComplation()
3、多个拦截器的执行顺序
①若多个拦截器的preHandle()都返回true
此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关,preHandle()会按照配置的顺序执行,而postHandle()和afterHandle()会按照配置的反顺序执行。
②若某个拦截器的preHandle返回了false
preHandle()返回false和它之前的拦截器的preHandle()都会执行,postHandle()都不执行,返回false拦截器之前的拦截器的afterComplation()会执行。
实例
创建两个拦截器FirstInterceptor和SecondInterceptor它们的内容除了输出语句都相同
SecondInterceptor
package com.louis.interceptors;import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @author XRY* @date 2023年07月04日18:35*/
@Component
public class SecondInterceptor implements HandlerInterceptor {@Override//控制器方法执行之前执行public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("SecondInterceptor----->preHandle2");return false;}@Override//控制器方法执行之后执行public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("SecondInterceptor----->postHandle2");HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);}@Override//在视图渲染之后执行public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("SecondInterceptor----->afterCompletion2");HandlerInterceptor.super.afterCompletion(request, response, handler, ex);}
}
SpringMVC.xml
<!--配置拦截器-->
<mvc:interceptors><ref bean="firstInterceptor"></ref><ref bean="secondInterceptor"></ref>
</mvc:interceptors>
结果
所有拦截器的preHandle返回都会true
FirstInterceptor----->preHandle
SecondInterceptor----->preHandle2
SecondInterceptor----->postHandle2
FirstInterceptor----->postHandle
SecondInterceptor----->afterCompletion2
FirstInterceptor----->afterCompletion
设置SecondeInterceptor的preHandle为false
FirstInterceptor----->preHandle
SecondInterceptor----->preHandle2
FirstInterceptor----->afterCompletion
异常处理器
分类
1、基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:
HandlerExceptionResolver
,它的实现类有:DefaultHandlerExceptionResolver
和SimpleMappingExceptionResolver
SimpleMappingExceptionResolver
为自定义异常处理器,使用方式如下:
在SpringMVC.xml中进行配置
<!--配置异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><!--key表示的指定的异常,标签内容为新的视图名称,创建新的视图名称error,表示当出现该错误时跳转到该页面--><prop key="java.lang.ArithmeticException">error</prop></props></property><!--显示异常信息,默认存储在请求域中--><property name="exceptionAttribute" value="exception"></property>
</bean>
创建异常跳转视图error
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org"><title>Title</title>
</head>
<body>
出错了!!
<!--获取在请求域中的信息-->
<p th:text="${exception}"></p>
</body>
</html>
index.html
<a th:href="@{/testExceptionHandler}">测试异常处理</a>
控制器
@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){System.out.println(1/0);return "success";
}
测试
2、基于注解的异常处理
异常类
@ControllerAdvice
public class ExceptionAnnotation {@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})/*参数用来显示异常信息*/public String testExcept(Exception exception, Model model){model.addAttribute("exception", exception);return "error";}
}