springboot拦截器(预先处理)
Posted -王二毛-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot拦截器(预先处理)相关的知识,希望对你有一定的参考价值。
一、通过实现HandlerInterceptor 接口的方式
1.1、创建一个登录拦截器
/**
* 登录检查
* 1、配置好拦截器要拦截哪些请求
* 2、把这些配置放在容器中
*/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor
/*目标方法执行之前*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
String requestURI = request.getRequestURI();
log.info("preHandle拦截的请求路径是",requestURI);
//登录检查逻辑
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser != null)
//true放行,执行目标方法
return true;
//拦截住,未登录,跳转到登录页,并添加提示信息
request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/").forward(request,response);
//false拦截
return false;
/*目标方法执行完成以后 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
log.info("postHandle执行",modelAndView);
/*页面渲染以后*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
log.info("afterCompletion执行异常",ex);
1.2、配置和注册登录拦截器
//@EnableWebMvc
@Configuration
//定制springmvc的功能
public class AdminWebConfig implements WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry)
//添加自定义拦截器LoginInterceptor
registry.addInterceptor(new LoginInterceptor())
//所有请求都被拦截包括静态资源
.addPathPatterns("/**")
//放行的请求
.excludePathPatterns(
"/","/login",//放行登录页
"/css/**","/fonts/**","/images/**","/js/**","/aa/**");//放行静态资源
二、web自定义定制化,通过实现WebMvcConfigurer 接口的方式
@Configuration
public class InterceptorConfig implements WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry)
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**") // 拦截所有请求,通过判断token是否合法来决定是否需要登录
.excludePathPatterns(
"/user/login", "/user/register", "/**/exportExcel", "/**/importExcel",
"/file/**","/swagger-resources/**", "/webjars/**", "/v2/**",
"/swagger-ui.html/**","**/swagger-ui/**", "/api", "/api-docs", "/api-docs/**")
// 放行静态文件
.excludePathPatterns( "/**/*.html", "/**/*.js", "/**/*.css", "/**/*.woff", "/**/*.ttf");
@Bean
public JwtInterceptor jwtInterceptor()
return new JwtInterceptor();
以上是关于springboot拦截器(预先处理)的主要内容,如果未能解决你的问题,请参考以下文章