SpringBoot:Filter、Listener、Servlet、Interceptor

SpringBoot:Filter、Listener、Servlet、Interceptor

Filter过滤器

示例为请求和返回的编码处理,和常见的url过滤

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.fufu.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {

private static Logger logger = LoggerFactory.getLogger(MyFilter.class);

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
//对request和response进行一些预处理
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//请求的地址
String url = httpRequest.getRequestURI();
logger.info("请求的地址: {}", url);
//这里可以加过滤条件
//response.sendRedirect(request.getContextPath()+"/fail.jsp"); 过滤失败可以重定向
//过滤成功,进入下一个过滤器
chain.doFilter(httpRequest, httpResponse);
}

@Override
public void destroy() {

}
}

Listener监听器

常见的session监听在线用户各户

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
package com.fufu.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener("MyListener")
public class MyListener implements HttpSessionListener {
private static Logger logger = LoggerFactory.getLogger(MyListener.class);

@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
logger.info("session监听器启动");
ServletContext context = httpSessionEvent.getSession().getServletContext();
Integer onLineCount = (Integer) context.getAttribute("onLineCount");
if(onLineCount==null){
context.setAttribute("onLineCount", 1);
}else{
onLineCount++;
context.setAttribute("onLineCount", onLineCount);
}

}

@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
logger.info("session监听器销毁");
ServletContext context = httpSessionEvent.getSession().getServletContext();
Integer onLineCount = (Integer) context.getAttribute("onLineCount");
if(onLineCount==null){
context.setAttribute("onLineCount", 1);
}else{
onLineCount--;
context.setAttribute("onLineCount", onLineCount);
}
}
}

###Servlet

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
package com.fufu.sevlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "myServlet", urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
private static Logger logger = LoggerFactory.getLogger(MyServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("发起servlet请求:{}",req.getPathInfo());
PrintWriter writer = resp.getWriter();
writer.write("hello world!");
writer.flush();
}
}

Interceptor拦截器

示例为token鉴权拦截器,拦截有@AuthToken注释的方法进行token鉴权

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
package com.fufu.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fufu.annotation.AuthToken;
import com.fufu.constant.SysConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
* token鉴权拦截器
*/
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
private final static Logger log = LoggerFactory.getLogger(AuthorizationInterceptor.class);
//存放鉴权信息的Header名称,默认是Authorization
private String httpHeaderName = "token";
//鉴权失败后返回的错误信息,默认为401 unauthorized
private String unauthorizedErrorMessage = "401 unauthorized";
//鉴权失败后返回的HTTP错误码,默认为401
private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;
/**
* 存放登录用户模型Key的Request Key
*/
public static final String REQUEST_CURRENT_KEY = "REQUEST_CURRENT_KEY";

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 如果打上了AuthToken注解则需要验证token
if (method.getAnnotation(AuthToken.class) != null || handlerMethod.getBeanType().getAnnotation(AuthToken.class) != null) {
String token = request.getHeader(httpHeaderName)==null?request.getParameter(httpHeaderName):request.getHeader(httpHeaderName);
log.info("token is {}", token);
String username = "";
Jedis jedis = new Jedis("localhost", 6379);
if (token != null && token.length() != 0) {
username = jedis.get(token);
log.info("username is {}", username);
}
if (username != null && !username.trim().equals("")) {
//log.info("token birth time is: {}",jedis.get(username+token));
Long tokeBirthTime = Long.valueOf(jedis.get(token + username));
log.info("token Birth time is: {}", tokeBirthTime);
Long diff = System.currentTimeMillis() - tokeBirthTime;
log.info("token is exist : {} ms", diff);
if (diff > SysConstant.TOKEN_RESET_TIME) {
jedis.expire(username, SysConstant.TOKEN_EXPIRE_TIME);
jedis.expire(token, SysConstant.TOKEN_EXPIRE_TIME);
log.info("Reset expire time success!");
Long newBirthTime = System.currentTimeMillis();
jedis.set(token + username, newBirthTime.toString());
}
//用完关闭
jedis.close();
request.setAttribute(REQUEST_CURRENT_KEY, username);
return true;
} else {
JSONObject jsonObject = new JSONObject();
PrintWriter out = null;
try {
response.setStatus(unauthorizedErrorCode);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
jsonObject.put("ret", ((HttpServletResponse) response).getStatus());
jsonObject.put("msg", HttpStatus.UNAUTHORIZED);
out = response.getWriter();
out.println(jsonObject);
return false;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
out.flush();
out.close();
}
}
}
}
request.setAttribute(REQUEST_CURRENT_KEY, null);
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}

Config

Filter、Listener、Servlet的config

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

import com.fufu.filter.MyFilter;
import com.fufu.listener.MyListener;
import com.fufu.sevlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig {

@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
MyFilter filter = new MyFilter();
registrationBean.setFilter(filter);

List<String> urlPatterns = new ArrayList<>();
urlPatterns.add("/*");
registrationBean.setUrlPatterns(urlPatterns);
registrationBean.setOrder(1);

return registrationBean;
}

@Bean
public ServletRegistrationBean myServlet() {
MyServlet demoServlet = new MyServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.setServlet(demoServlet);
List<String> urlMappings = new ArrayList<String>();
urlMappings.add("/myServlet");////访问,可以添加多个
registrationBean.setUrlMappings(urlMappings);
registrationBean.setLoadOnStartup(1);
return registrationBean;
}

@Bean
public ServletListenerRegistrationBean myListener() {
ServletListenerRegistrationBean registrationBean
= new ServletListenerRegistrationBean<>();
registrationBean.setListener(new MyListener());
registrationBean.setOrder(1);
return registrationBean;
}
}

Interceptor的config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.fufu.config;

import com.fufu.interceptor.AuthorizationInterceptor;
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 WebAppConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] patterns = new String[] { "/loginToken","/*.html","/swagger-resources/**"};
registry.addInterceptor(new AuthorizationInterceptor()).addPathPatterns("/**").excludePathPatterns(patterns);
}
}

源码:https://github.com/qq1028951741/springbootdemo or 右上角github进去,springbootdemo项目,如果对您有帮助,麻烦点下star,谢谢


人生两苦:想要却不得,拥有却失去。 –褚禄山
珍惜当下,与君共勉~


本文标题:SpringBoot:Filter、Listener、Servlet、Interceptor

文章作者:fufua

发布时间:2018年12月17日 - 10:49:13

最后更新:2018年12月17日 - 10:50:19

原始链接:https://qq1028951741.github.io/2018/12/17/SpringBoot:Filter、Listener、Servlet、Interceptor/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

this is end, thank you for reading