在SpringBoot框架中使用拦截器
Posted 林深时见鹿的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在SpringBoot框架中使用拦截器相关的知识,希望对你有一定的参考价值。
1.继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册我们自定义的拦截器
1 package com.eth.wallet.config; 2 3 4 import com.eth.wallet.interceptor.MyInterceptor; 5 import org.springframework.boot.SpringBootConfiguration; 6 import org.springframework.web.servlet.config.annotation.*; 7 8 /** 9 * @CLassName WebAppConfig 10 * @Description TODO 11 * @Author wangpengfei 12 * @Email [email protected] 13 * @Date 2018/12/3 17:40 14 * @Version 1.0 15 **/ 16 @SpringBootConfiguration 17 public class WebAppConfig extends WebMvcConfigurerAdapter { 18 19 /** 20 * 注册拦截器 21 */ 22 @Override 23 public void addInterceptors(InterceptorRegistry registry) { 24 //addPathPattern后跟拦截地址,excludePathPatterns后跟排除拦截地址 25 registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**") 26 .excludePathPatterns("/WalletUser/toLogin") 27 .excludePathPatterns("/WalletUser/toRegister") 28 .excludePathPatterns("/WalletUser/login"); 29 } 30 }
2.实现HandlerInterceptor接口,重写接口中的三个方法
package com.eth.wallet.interceptor; /** * @CLassName MyInterceptor * @Description TODO * @Author wangpengfei * @Email [email protected] * @Date 2018/12/3 17:44 * @Version 1.0 **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 拦截器 */ @Component public class MyInterceptor implements HandlerInterceptor{ //在请求处理之前进行调用(Controller方法调用之前 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { HttpSession session = httpServletRequest.getSession(); //获取登录的session信息 String user = (String) session.getAttribute("user"); if(user!=null){ return true; } else{ //未登录自动跳转界面 httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/WalletUser/toLogin"); return false; } } //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("postHandle被调用 "); } //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作) @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("afterCompletion被调用 "); } }
以上是关于在SpringBoot框架中使用拦截器的主要内容,如果未能解决你的问题,请参考以下文章
Springboot第三章 SpringBoot 和 web 组件