Fork me on GitHub
时钟canvas

springboot项目配置拦截器

配置拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
 
    @Autowired
    private ResponseInteceptor appInteceptor;
  
    @Autowired
    private PersonInterceptorConfig personInteceptor;
    /**
     * 拦截器,在这里加拦截路径
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("加载 InterceptorConfig...");
        // 全局拦截器
        registry.addInterceptor(appInteceptor).addPathPatterns("/**");
        //个人端登录页面拦截器,拦截特定的请求
        registry.addInterceptor(personInteceptor).addPathPatterns("/**/person/**");
        System.out.println("已开启拦截器!");
    }
}

  处理拦截页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Component
public class PersonInterceptorConfig extends HandlerInterceptorAdapter {
 
    @Resource
    private RedisCache<Object> redisCache;
 
    // 在控制器执行前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
 
        // 获取当前登录账户信息
        String struuid = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(Constants.CookieKey)) {
                struuid = cookie.getValue();
            }
        }
 
        if (struuid == null) {
            System.out.println("验证不通过");
            return false;
        }
        String userName = redisCache.get(struuid).toString();
        if (userName == null) {
            System.out.println("验证不通过");
            return false;
        } else {
            System.out.println("***********************************************");
            return true;
        }
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
 
    // 在后端控制器执行后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}

  

1
2
3
4
5
public interface Constants {
     //自定义cookie的key
     static String CookieKey="userid";
     static String RedisUserKey="userid";
    }

  登录页面处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Resource
    private RedisCache<Object> redisCache;
     
    /**
     * 个人端登录页面
     *
     * @param
     */
    @RequestMapping(value = "/personLoginById", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONResponse personLoginById(@PathVariable("name") String name,@PathVariable("id") String id,
            HttpServletRequest request,HttpServletResponse response) {
        try {
            // @PathVariable("code") String code,@PathVariable("phoneCode") String phoneCode,
            String uuid = UUIDUtils.getUUID();
            //Map<String,Object> map = new HashMap<String,Object>();
            Cookie cookie = new Cookie(Constants.CookieKey, uuid);
            response.addCookie(cookie);//返回客户端
            redisCache.set(uuid, name);
            return ResultUtil.success();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }
    }
1
redisCache类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
public class RedisCache<T> {
 
    private final Logger logger = LoggerFactory.getLogger(getClass());
     
    @Autowired
    private RedisTemplate<String, T> redisTemplate;
 
    public static final String KEY_SET_PREFIX = "_set:";
    public static final String KEY_LIST_PREFIX = "_list:";
 
    public T get(String key) {
        logger.debug("get key [{}]", key);
        try {
            if (key == null) {
                return null;
            }
            else {
                return redisTemplate.opsForValue().get(key);
            }
        }
        catch (Throwable t) {
            logger.error("get key [{}] exception!", key, t);
            throw new CacheException(t);
        }
 
    }
 
    public T set(String key, T value) {
        logger.debug("set key [{}]", key);
        try {
            redisTemplate.opsForValue().set(key, value);
            return value;
        }
        catch (Throwable t) {
            logger.error("set key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public T set(String key, T value, long timeout) {
        logger.debug("set key [{}]", key);
        try {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            return value;
        }
        catch (Throwable t) {
            logger.error("set key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void delete(String key) {
        logger.debug("delete key [{}]", key);
        try {
            redisTemplate.delete(key);
        }
        catch (Throwable t) {
            logger.error("delete key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    @SuppressWarnings("unchecked")
    public void setSet(String k, T value, long time) {
        String key = KEY_SET_PREFIX + k;
        logger.debug("setSet key [{}]", key);
        try {
            SetOperations<String, T> valueOps = redisTemplate.opsForSet();
            valueOps.add(key, value);
            if (time > 0)
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        catch (Throwable t) {
            logger.error("setSet key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setSet(String k, T value) {
        setSet(k, value, -1);
    }
 
    @SuppressWarnings("unchecked")
    public void setSet(String k, Set<T> v, long time) {
        String key = KEY_SET_PREFIX + k;
        logger.debug("setSet key [{}]", key);
        try {
            SetOperations<String, T> setOps = redisTemplate.opsForSet();
            setOps.add(key, (T[]) v.toArray());
            if (time > 0)
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        catch (Throwable t) {
            logger.error("setSet key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setSet(String k, Set<T> v) {
        setSet(k, v, -1);
    }
 
    public Set<T> getSet(String k) {
        String key = KEY_SET_PREFIX + k;
        logger.debug("getSet key [{}]", key);
        try {
            SetOperations<String, T> setOps = redisTemplate.opsForSet();
            return setOps.members(key);
        }
        catch (Throwable t) {
            logger.error("getSet key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setList(String k, T v, long time) {
        String key = KEY_LIST_PREFIX + k;
        logger.debug("setList key [{}]", key);
        try {
            ListOperations<String, T> listOps = redisTemplate.opsForList();
            listOps.rightPush(key, v);
            if (time > 0)
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        catch (Throwable t) {
            logger.error("setList key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setList(String k, List<T> v, long time) {
        String key = KEY_LIST_PREFIX + k;
        logger.debug("setList key [{}]", key);
        try {
            ListOperations<String, T> listOps = redisTemplate.opsForList();
            listOps.rightPushAll(key, v);
            if (time > 0)
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        catch (Throwable t) {
            logger.error("setList key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setList(String k, List<T> v) {
        setList(k, v, -1);
    }
 
    public List<T> getList(String k, long start, long end) {
        String key = KEY_LIST_PREFIX + k;
        logger.debug("setList key [{}]", key);
        try {
            ListOperations<String, T> listOps = redisTemplate.opsForList();
            return listOps.range(key, start, end);
        }
        catch (Throwable t) {
            logger.error("getList key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public long getListSize(String k) {
        String key = KEY_LIST_PREFIX + k;
        logger.debug("setList key [{}]", key);
        try {
            ListOperations<String, T> listOps = redisTemplate.opsForList();
            return listOps.size(key);
        }
        catch (Throwable t) {
            logger.error("getListSize key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public long getListSize(ListOperations<String, String> listOps, String k) {
        String key = KEY_LIST_PREFIX + k;
        logger.debug("getListSize key [{}]", key);
        try {
            return listOps.size(key);
        }
        catch (Throwable t) {
            logger.error("getListSize key [{}] exception!", key, t);
            throw new CacheException(t);
        }
    }
 
    public void setMap(String key, String mapkey, T mapValue) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        hashOperations.putIfAbsent(key, mapkey, mapValue);
    }
 
    public void deleteMap(String key, String mapkey) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, mapkey);
    }
 
    public T getMap(String key, String mapkey) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        return hashOperations.get(key, mapkey);
    }
 
    public List<T> getMapValues(String key) {
        HashOperations<String, String, T> hashOperations = redisTemplate.opsForHash();
        return hashOperations.values(key);
    }
 
    public void setRedisTemplate(RedisTemplate<String, T> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}

  

 

posted @   dragonKings  阅读(827)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
欢迎阅读『springboot项目配置拦截器』
     
点击右上角即可分享
微信分享提示