以下介绍两种防御实现方式。
1-XssFilter的实现方式
1.1 在web.xml加一个filter
XssEscape
XssFilter
XssEscape
/*
REQUEST
1.2 XssFilter 的实现方式是实现servlet的Filter接口
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
}
@Override
public void destroy() {
}
}
1.3 XssHttpServletRequestWrapper的实现方式,继承servlet的HttpServletRequestWrapper,并重写相应的几个有可能带xss攻击的方法
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.StringEscapeUtils;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String name) {
return StringEscapeUtils.escapeHtml4(super.getHeader(name));
}
@Override
public String getQueryString() {
return StringEscapeUtils.escapeHtml4(super.getQueryString());
}
@Override
public String getParameter(String name) {
return StringEscapeUtils.escapeHtml4(super.getParameter(name));
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if(values != null) {
int length = values.length;
String[] escapseValues = new String[length];
for(int i = 0; i
escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
}
return escapseValues;
}
return super.getParameterValues(name);
}
}
2- struts2的拦截器过滤实现方式
2.1- 配置struts.xml
2.2- Java代码,拦截器实现类
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class XssInterceptor extends AbstractInterceptor{
private static final long serialVersionUID = -3393165892157005167L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// System.out.println("*** into XssInterceptor");
ActionContext actionContext = invocation.getInvocationContext();
Map map = actionContext.getParameters();
for (Map.Entry entry : map.entrySet()) {
String[] values = (String[]) (entry.getValue());
int i = 0;
for (String value : values) {
values[i] = StringEscapeUtils.escapeHtml4(value);
i++;
}
entry.setValue(values);
}
return invocation.invoke();
}
}