springboot配置拦截器

在springboot中配置拦截器
springboot版本:2.0.8.RELEASE

定义拦截器

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

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class MyInterceptor extends HandlerInterceptorAdapter {


/**
* 在请求处理之前进行调用(Controller方法调用之前)
* 返回true则将请求传给下一个拦截器,返回false则表明该拦截器自己会处理response,不会将请求往下传
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
String ip = request.getRemoteAddr();
long startTime = System.currentTimeMillis();
request.setAttribute("requestStartTime", startTime);
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
System.out.println("用户"+ip+",访问目标"+method.getDeclaringClass().getName()+"."+method.getName());
System.out.println("session:"+request.getSession().getId());
String user = (String)request.getSession().getAttribute("username");
if(null == user){
request.getSession().setAttribute("isLogin","no");
request.getSession().setAttribute("username","notLogin");
response.sendRedirect("login");
flag = false;
}
else
{
System.out.println("username " + user);
}
return true; //放行
}

/**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
* (主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
//after

}

/**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
//post

}

}

配置拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Configuration
public class WebMvcConfigurer implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 拦截器按照顺序执行
* 可添加多个拦截器
*/
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**") //拦截所有请求
.excludePathPatterns("login*","/static/**"); //不拦截的请求

super.addInterceptors(registry);
}

}
打赏

请我喝杯咖啡吧~

支付宝
微信