HandlerInterceptor
拦截器用的机会不多,在这里做数据签名校验不错,不过更多的人喜欢写Filter,
这个切面神奇的地方是:可以在页面渲染的不同阶段使用Writer。
(因为替代方案太多,基本得不到应用)
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 请求拦截器, * * Created by 12614 on 2018/5/11. */ public class TestInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("TestInterceptor: preHandle"); //TODO 请求拦截处理逻辑 return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("TestInterceptor: postHandle"); //TODO 页面渲染前置逻辑 //E.G. httpServletResponse.getWriter().write("-----------------------"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("TestInterceptor: afterCompletion"); //TODO 页面渲染后置逻辑 //E.G. httpServletResponse.getWriter().write("========================"); } }
Spring配置
<mvc:interceptors> <mvc:interceptor> <!--进行拦截的路径--> <mvc:mapping path="/**"/> <!--不进行拦截的路径--> <mvc:exclude-mapping path="/lib/**" /> <beans:bean class="xxxxx全类名"/> </mvc:interceptor> </mvc:interceptors>
SpringBoot配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by 12614 on 2018/5/11. */ @Configuration public class ApplicationConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { super.addInterceptors(registry); registry.addInterceptor(new TestInterceptor()) .addPathPatterns("/**.ftl","/**.json"); } }