SpringMVC 拦截器
<!--配置拦截器,可定义多个拦截器-->
<mvc:interceptors>
<!--定义1个拦截器-->
<mvc:interceptor>
<!--用于指定拦截器匹配url-->
<mvc:mapping path="/user/**"/>
<!--用于指定拦截器排除的url-->
<mvc:exclude-mapping path="/"/>
<!--用来指定拦截器-->
<bean class="com.tobie.interceptor.MyHandlerInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
package com.tobie.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Tobieance
* @description 自定义拦截器
* @date 2023-09-14 16:02
*/
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(this.getClass().getSimpleName()+".preHandler");
request.setAttribute("msg","<h1>拦截</h1>");
request.getRequestDispatcher("/WEB-INF/view/result.jsp").forward(request,response);
//返回值为true表示通过(默认),false表示拦截
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println(this.getClass().getSimpleName()+".postHandler");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println(this.getClass().getSimpleName()+".afterCompletion");
}
}