提交 | 用户 | 时间
|
fd2207
|
1 |
package com.jcdm.common.filter; |
懒 |
2 |
|
|
3 |
import java.io.IOException; |
|
4 |
import java.util.ArrayList; |
|
5 |
import java.util.List; |
|
6 |
import javax.servlet.Filter; |
|
7 |
import javax.servlet.FilterChain; |
|
8 |
import javax.servlet.FilterConfig; |
|
9 |
import javax.servlet.ServletException; |
|
10 |
import javax.servlet.ServletRequest; |
|
11 |
import javax.servlet.ServletResponse; |
|
12 |
import javax.servlet.http.HttpServletRequest; |
|
13 |
import javax.servlet.http.HttpServletResponse; |
|
14 |
import com.jcdm.common.utils.StringUtils; |
|
15 |
import com.jcdm.common.enums.HttpMethod; |
|
16 |
|
|
17 |
/** |
|
18 |
* 防止XSS攻击的过滤器 |
|
19 |
* |
|
20 |
* @author jc |
|
21 |
*/ |
|
22 |
public class XssFilter implements Filter |
|
23 |
{ |
|
24 |
/** |
|
25 |
* 排除链接 |
|
26 |
*/ |
|
27 |
public List<String> excludes = new ArrayList<>(); |
|
28 |
|
|
29 |
@Override |
|
30 |
public void init(FilterConfig filterConfig) throws ServletException |
|
31 |
{ |
|
32 |
String tempExcludes = filterConfig.getInitParameter("excludes"); |
|
33 |
if (StringUtils.isNotEmpty(tempExcludes)) |
|
34 |
{ |
|
35 |
String[] url = tempExcludes.split(","); |
|
36 |
for (int i = 0; url != null && i < url.length; i++) |
|
37 |
{ |
|
38 |
excludes.add(url[i]); |
|
39 |
} |
|
40 |
} |
|
41 |
} |
|
42 |
|
|
43 |
@Override |
|
44 |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) |
|
45 |
throws IOException, ServletException |
|
46 |
{ |
|
47 |
HttpServletRequest req = (HttpServletRequest) request; |
|
48 |
HttpServletResponse resp = (HttpServletResponse) response; |
|
49 |
if (handleExcludeURL(req, resp)) |
|
50 |
{ |
|
51 |
chain.doFilter(request, response); |
|
52 |
return; |
|
53 |
} |
|
54 |
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); |
|
55 |
chain.doFilter(xssRequest, response); |
|
56 |
} |
|
57 |
|
|
58 |
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) |
|
59 |
{ |
|
60 |
String url = request.getServletPath(); |
|
61 |
String method = request.getMethod(); |
|
62 |
// GET DELETE 不过滤 |
|
63 |
if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method)) |
|
64 |
{ |
|
65 |
return true; |
|
66 |
} |
|
67 |
return StringUtils.matches(url, excludes); |
|
68 |
} |
|
69 |
|
|
70 |
@Override |
|
71 |
public void destroy() |
|
72 |
{ |
|
73 |
|
|
74 |
} |
|
75 |
} |