拦截器(Interceptor),主要完成请求参数的解析、将页面表单参数赋给值栈中相应属性、执行功能检验、程序异常调试等工作。
如下为完整的项目结构
<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>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.louis">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>
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);
}
}
SpringMVC中的拦截器用于拦截控制器方法的执行,它需要实现
HandlerInterceptor
或继承HandlerInterceptorAdapter
类(过时)并且必须在SpringMVC的配置文件中进行配置。
<mvc:interceptors>
<bean class="com.louis.interceptors.FirstInterceptor">bean>
mvc:interceptors>
<mvc:interceptors>
<ref bean="firstInterceptor">ref>
mvc:interceptors>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/"/>
<ref bean="firstInterceptor">ref>
mvc:interceptor>
mvc:interceptors>
preHandle
:控制器方法执行之前执行preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法,返回false表示拦截,即不调用控制器方法。
postHandle
:控制器方法执行之后执行postHandle()
afterComplation
:处理完视图和模型数据,渲染视图完毕之后执行afterComplation()
①若多个拦截器的preHandle()都返回true
此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关,preHandle()会按照配置的顺序执行,而postHandle()和afterHandle()会按照配置的反顺序执行。
②若某个拦截器的preHandle返回了false
preHandle()返回false和它之前的拦截器的preHandle()都会执行,postHandle()都不执行,返回false拦截器之前的拦截器的afterComplation()会执行。
创建两个拦截器FirstInterceptor和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);
}
}
<mvc:interceptors>
<ref bean="firstInterceptor">ref>
<ref bean="secondInterceptor">ref>
mvc:interceptors>
FirstInterceptor----->preHandle
SecondInterceptor----->preHandle2
SecondInterceptor----->postHandle2
FirstInterceptor----->postHandle
SecondInterceptor----->afterCompletion2
FirstInterceptor----->afterCompletion
FirstInterceptor----->preHandle
SecondInterceptor----->preHandle2
FirstInterceptor----->afterCompletion
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:
HandlerExceptionResolver
,它的实现类有:DefaultHandlerExceptionResolver
和SimpleMappingExceptionResolver
SimpleMappingExceptionResolver
为自定义异常处理器,使用方式如下:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">errorprop>
props>
property>
<property name="exceptionAttribute" value="exception">property>
bean>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
<title>Titletitle>
head>
<body>
出错了!!
<p th:text="${exception}">p>
body>
html>
<a th:href="@{/testExceptionHandler}">测试异常处理a>
@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){
System.out.println(1/0);
return "success";
}
@ControllerAdvice
public class ExceptionAnnotation {
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
/*参数用来显示异常信息*/
public String testExcept(Exception exception, Model model){
model.addAttribute("exception", exception);
return "error";
}
}