SpringBoot使用自定义拦截器

1. 定义拦截器配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.pibigstar.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer{

/**
* 拦截器配置
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//只拦截 /admin/路径下的请求
registry.addInterceptor(new AdminInterceptor()).addPathPatterns("/admin/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}

2. 定义拦截器

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
package com.pibigstar.config;

import static org.springframework.test.web.client.match.MockRestRequestMatchers.queryParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

/**
* 管理员拦截器
* 如果不是管理员则不让其访问
* @author pibigstar
*
*/
public class AdminInterceptor implements HandlerInterceptor{

/**
* 在请求处理之前进行调用(controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {

if (request.getAttribute("userId").equals("admin")) {
//放行
return true;
}
//拦截
return false;
}

/**
* 在整个请求结束之后被调用
* 主要用来进行资源清理 ,一些缓存什么的。
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
-------------本文结束感谢您的阅读-------------