SpringBoot 拦截器
web拦截器作用有权限控制,日志记录等等。SpringBoot 提供 HandlerInterceptor方便我们开发;
我们定义一个自定义拦截器 实现HandlerInterceptor接口,实现三个方法,preHandle是 请求处理之前调用,postHandle是请求处理之后并且视图渲染之前调用,afterCompletion请求结束之后并且视图渲染之后调用;
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
|
package com.java1234.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * 自定义拦截器 * @author Administrator * */ public class MyInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println( "========MyInterceptor preHandle 请求处理之前调用=================" ); return true ; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println( "========MyInterceptor postHandle 请求处理之后并且视图渲染之前调用=================" ); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println( "========MyInterceptor afterCompletion 请求结束之后并且视图渲染之后调用=================" ); } } |
我们再定义一个类继承WebMvcConfigurerAdapter,重写addInterceptors,我们把自定义拦截器添加到拦截器链中去。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.java1234.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.java1234.interceptor.MyInterceptor; @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor( new MyInterceptor()).addPathPatterns( "/**" ); // 添加拦截器 以及 拦截器规则 super .addInterceptors(registry); } } |
简单搞个控制器类测试下;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.java1234.action; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 用户Controller * @author Administrator * */ @Controller @RequestMapping (value = "/user" ) public class UserController { @ResponseBody @RequestMapping (value = "/login" ) public String login(){ System.out.println( "login" ); return "测试拦截器" ; } } |
项目配置文件配置下:
1
2
3
|
server: port: 80 context-path: / |
启动项目,运行 http://localhost/user/login
执行结果如下:
========MyInterceptor preHandle 请求处理之前调用=================
login
========MyInterceptor postHandle 请求处理之后并且视图渲染之前调用=================
========MyInterceptor afterCompletion 请求结束之后并且视图渲染之后调用=================
测试代码: