16. 拦截器示例

1.
  1. 拦截器

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 登录拦截器
     *
     * @author sheng_zs@126.com
     * @date 2021-07-17 12:18
     */
    @Slf4j
    @Component
    public class LoginInterceptor implements HandlerInterceptor {
        @Resource
        private RedisTemplate<String, Object> redisTemplate;
        @Resource
        private ValueOperations<String, Object> valueOperations;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            /*
                attention:简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
                反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
             */
            if (Objects.equals("OPTIONS", request.getMethod())) {
                return true;
            }
    
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("message", "登录过期");
            errorMap.put("status", "302");
            errorMap.put("reLogin", "1");
            // 获取用户id,判断 redis 中是否已经过期
            String loginUserId = request.getHeader("loginUserId");
            if (loginUserId == null || "".equals(loginUserId)) {
                HttpSession session = request.getSession();
                loginUserId = session.getAttribute("userId") != null ? session.getAttribute("userId").toString() : "";
            }
            if (loginUserId == null || "".equals(loginUserId)) {
                returnJson(response, errorMap);
                return false;
            }
            Long expire = redisTemplate.getExpire("loginUserId:" + loginUserId);
            // 登录时间未过期
            if (Objects.nonNull(expire) && expire > -2) {
                valueOperations.set("loginUserId:" + loginUserId, loginUserId, 30, TimeUnit.MINUTES);
                return true;
            }
            returnJson(response, errorMap);
            return false;
        }
    
        private void returnJson(HttpServletResponse response, Object json) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try (PrintWriter writer = response.getWriter()) {
                writer.print(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  2. 拦截器注册

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import javax.annotation.Resource;
    
    /**
     * 登录拦截器配置类
     *
     * @author sheng_zs@126.com
     * @date 2021-07-17 12:21
     */
    @Configuration
    public class LoginInterceptorConfig implements WebMvcConfigurer {
        @Resource
        private LoginInterceptor loginInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            InterceptorRegistration registration = registry.addInterceptor(loginInterceptor);
            // 设置顺序,也可在 拦截器上 用 @Order() 注解
            registration.order(1);
            // 拦截所有的方法
            registration.addPathPatterns("/**");
            // 不拦截登录相关方法
            registration.excludePathPatterns("/login/**")
                    // 不拦截微信相关方法
                    .excludePathPatterns("/wx/**")
                    // 不拦截 swagger 相关资源
                    .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值