SpringMVC的拦截器(Interceptor)
2020-11-04 本文已影响0人
_FireFly_
自定义的拦截器类
package interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 这个类是我们自定义的拦截器类
* 继承 HandlerInterceptorAdapter
* 实现 HandlerInterceptor
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("到达资源之前执行");
return true;//返回值true可以放行 返回值false不行啦
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("资源执行之后执行");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("最终执行");
}
}
ApplicationContext.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="controller,service,exception"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:interceptors> <--注册拦截器-->
<mvc:interceptor>
<mvc:mapping path="/*"/> <--拦截所有请求-->
<bean class="interceptor.MyInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/*"/> <--拦截所有请求-->
<bean class="interceptor.MyInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>