SpringMVC(六):拦截器
之前在学习servlet和jsp时学习了过滤器Filter,使用过滤器需要实现Filter接口,它能够在请求到servlet之前拦截请求,并且根据需求对请求进行相应的处理。
拦截器跟过滤器非常相似,SpringMVC拦截器是通过实现HandlerInterceptor接口实现的,它其实是AOP的一种应用。
这个接口与三个方法,我们来看一下源码:
public interface HandlerInterceptor { default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
preHandle是在Handler执行之前执行;
postHandle是在Handler执行成功之后执行;
afterCompletion是在请求处理完毕后执行。
下面我们来具体实现一下:
实现接口:
public class UserInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if (session.getAttribute("UserName") != null) { return true; } response.sendRedirect("/tlp"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
return true是给其他拦截器放行。
在Spring配置文件中配置拦截器:
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/**"/> <bean class="com.jms.config.UserInterceptor"/> </mvc:interceptor> </mvc:interceptors>
这里是对/user下面的所有请求进行拦截。
(本文仅作个人学习记录用,如有纰漏敬请指正)