防止xss攻击 --- getParameter getParameterValues getParameterMap的使用

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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;
import javax.servlet.http.HttpServletRequestWrapper;           (wrapper:包装器,封装器)


import org.apache.commons.text.StringEscapeUtils;


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() {
}

//自定义内部类
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 Map getParameterMap() {

Map map1 = super.getParameterMap();
Map escapseMap = new HashMap();
Set keys = map1.keySet();
for (String key : keys) {
String[] valArr = map1.get(key);
if (valArr != null && valArr.length > 0) {
String[] escapseValArr = new String[valArr.length];
for (int i = 0; i < valArr.length; i++) {
String escapseVal = StringEscapeUtils.escapeHtml4(valArr[i]);
escapseValArr[i] = escapseVal;
}
escapseMap.put(key, escapseValArr);
}
}

return escapseMap;
}


@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 < length; i++) {
escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
}
return escapseValues;
}
return super.getParameterValues(name);
}
}


}

你可能感兴趣的:(java)