SpringBoot开发(3)——拦截器

  1. 配置登录拦截器,根据传过来的token判断是否登录,从而进行拦截
  2. 在cxsbg包下创建interceptor包,在interceptor包中新建登录拦截器,实现拦截功能
    package com.cxsbg.interceptor;
    
    import com.cxsbg.utils.JwtUtil;
    import io.jsonwebtoken.Claims;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @Component //注入
    //实现登录拦截器,验证token是否有效,如果有效就放行
    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //获取请求头中的token
            String token = request.getHeader("token");
            //判断token是否为空,如果为空,说明未登录,不放行
            if(!StringUtils.hasText(token)){
                //发送错误码
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            //判断token是否有效,如果无效,不放行
            try {
                Claims claims = JwtUtil.parseJWT(token);
                String subject = claims.getSubject();
                System.out.println(subject);
            }catch (Exception e){
                //发送错误码
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            return true;
        }
    }
    
  3. 配置拦截路径,在config包下新建配置类,例如LoginConfig
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration //注入
    public class LoginConfig implements WebMvcConfigurer{
    
        @Autowired
        private LoginInterceptor loginInterceptor;
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //首先添加拦截器
            //添加拦截路径
            //排除拦截路径
            registry.addInterceptor(loginInterceptor)//添加拦截器
                    .addPathPatterns("/**")//拦截任意路径
                    .excludePathPatterns("/sys_user/login");//排除登录路径
        }
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注