spring boot配置登录拦截器

登录拦截器功能:开发一个系统时,系统需要登录后才能进行各种访问。如果没有登录,则没有权限进行访问,拦截器将拦截访问请求,跳转到登录页面提示用户进行登录。

编写一个拦截器实现handlerInterceptor接口

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        log.info("拦截的请求:",requestURI);


        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");

        if (loginUser!=null){
            return true;
        }
        request.setAttribute("msg","请登录后访问");
        request.getRequestDispatcher("/login").forward(request,response);

        return false;
    }

将拦截器添加到配置容器中

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")     //拦截所有请求,包括静态资源
                .excludePathPatterns("/","/login","/css","/font","/image","/js","/picture","/webfonts");     //放行的请求
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot配置拦截器需要以下几个步骤: 1. 创建一个拦截器类并实现 HandlerInterceptor 接口,该接口包含了三个方法:preHandle()、postHandle() 和 afterCompletion(),其中 preHandle() 方法在请求处理之前调用,postHandle() 方法在请求处理之后调用,afterCompletion() 方法在视图渲染之后调用。 ``` public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("请求处理之前"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("请求处理之后,视图渲染之前"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("请求处理之后,视图渲染之后"); } } ``` 2. 在配置类中注册拦截器,可以通过实现 WebMvcConfigurer 接口来注册拦截器,也可以用 @Configuration 注解来标注配置类。 ``` @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } } ``` 3. 配置拦截器拦截的请求路径,addPathPatterns() 方法可以传入多个路径参数,表示拦截哪些请求,excludePathPatterns() 方法可以传入多个路径参数,表示排除哪些请求不被拦截。 ``` @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值