package com.dongao.filter;
import com.alibaba.druid.util.DruidWebUtils;
import com.alibaba.druid.util.PatternMatcher;
import com.alibaba.druid.util.ServletPathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class XssFilter implements Filter {
private String initParameter;
private Set<String> initParameters;
protected PatternMatcher pathMatcher = new ServletPathMatcher();
private String contextPath;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//初始化加载需要排除,无需过滤的后缀
initParameter = filterConfig.getInitParameter("exclude");
if (initParameter != null && initParameter.trim().length() != 0) {
initParameters = new HashSet<String>(Arrays.asList(initParameter.split("\\s*,\\s*")));
}
contextPath = DruidWebUtils.getContextPath(context);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestURI = httpRequest.getRequestURI();
if (isExclusion(requestURI)) { // 无需过滤
chain.doFilter(request, response);
return;
}else { // 需过滤
chain.doFilter(new XssHttpServletRequestWrapper(httpRequest), response);
}
}
@Override
public void destroy() {
}
public boolean isExclusion(String requestURI) {
if (initParameters == null) {
return false;
}
if (contextPath != null && requestURI.startsWith(contextPath)) {
requestURI = requestURI.substring(contextPath.length());
if (!requestURI.startsWith("/")) {
requestURI = "/" + requestURI;
}
}
for (String pattern : initParameters) {
if (pathMatcher.matches(pattern, requestURI)) {
return true;
}
}
return false;
}
}