基于springboot配置拦截器

Posted shouyaya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于springboot配置拦截器相关的知识,希望对你有一定的参考价值。

1.编写拦截器类:

public class loginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute("username")==null){
            request.setAttribute("msg","请先登录");
            request.getRequestDispatcher("/").forward(request,response);
            return  false;
        }
        else return true;
    }
}

2.在mvc配置类中添加拦截器

//导入配置
@Configuration
//继承WebMvcConfigurer
public class mvcConfig implements WebMvcConfigurer {

    //添加自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginHandlerInterceptor()).addPathPatterns("/**")
                //配置不拦截的路径
                .excludePathPatterns("/","/login","/css/**","/js/**","/fonts/**","images/**");
    }
}

 

以上是关于基于springboot配置拦截器的主要内容,如果未能解决你的问题,请参考以下文章