Servlet Filter 权限过滤

本文最后更新于:2024年3月18日 凌晨

Servlet Filter 权限过滤

pom.xml

1
2
3
4
5
6
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

代码实现

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
@WebFilter(filterName = "loginFilter",
urlPatterns = "/*",
initParams = {
@WebInitParam(name = "loginUI", value = "/home/loginUI"),
@WebInitParam(name = "loginProcess", value = "home/login"),
@WebInitParam(name = "encoding", value = "utf-8")
})
public class LoginFilter implements Filter {
private FilterConfig config;

@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}


@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// 获取配置参数。
String loginUI = config.getInitParameter("loginUI");
String loginProcess = config.getInitParameter("loginProcess");
String encoding = config.getInitParameter("encoding");


HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

// 设置请求的字符集(post请求方式有效)
request.setCharacterEncoding(encoding);

// 不带http:// 域名:端口的地址。
String uri = request.getRequestURI();
if (uri.contains(loginUI) || uri.contains(loginProcess)) {
// 请求的登录,放行。
chain.doFilter(request, response);
} else {
if (request.getSession().getAttribute("user") == null) {
// 重定向到登录页面。
response.sendRedirect(request.getContextPath() + loginUI);
} else {
// 已经登录,放行。
chain.doFilter(request, response);
}
}
}

@Override
public void destroy() {
this.config = null;
}
}