java 防止 XSS 攻击的常用方法总结

过滤器拦截所有的请求对特殊字符进行转义。

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

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.HttpServletResponse;

public class ContentFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("进入到过滤器方法中.....");
		HttpServletRequest request =(HttpServletRequest)servletrequest;
		HttpServletResponse response =(HttpServletResponse)servletresponse;
		 //设置请求编码格式
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
	    chain.doFilter(new MyRequestWrapper((HttpServletRequest) request), response);
		
	}	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
MyRequestWrapper.java

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringEscapeUtils;

public class MyRequestWrapper extends HttpServletRequestWrapper
{

	/**
	 * 规范化后请求参数map
	 */
	private Map<String, String[]> sanitized;
	/**
	 * 原始请求参数map
	 */
	private Map<String, String[]> orig;
	
	@SuppressWarnings("unchecked")
	public MyRequestWrapper(HttpServletRequest req) 
	{
		super(req);
		orig = req.getParameterMap();	
		sanitized = getParameterMap();
	}		

	@Override
	public String getParameter(String name) 
	{		
		String[] vals = getParameterMap().get(name); 
		if (vals != null && vals.length > 0) 
			return vals[0];
		else        
			return null;        
	}


	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String[]> getParameterMap() 
	{	
		if (sanitized==null)
			sanitized = sanitizeParamMap(orig);
		return sanitized;			

	}

	@Override
	public String[] getParameterValues(String name)
	{	
		return getParameterMap().get(name);
	}


	/**
	 * 规范请求参数
	 * @param raw
	 * @return
	 */
	private  Map<String, String[]> sanitizeParamMap(Map<String, String[]> raw) 
	{		
		Map<String, String[]> res = new HashMap<String, String[]>();
		if (raw==null)
			return res;
	
		for (String key : (Set<String>) raw.keySet())
		{			
			String[] rawVals = raw.get(key);
			String[] snzVals = new String[rawVals.length];
			for (int i=0; i < rawVals.length; i++) 
			{
				//第一种方法
				//snzVals[i] = xssEncode(rawVals[i]);
				
				//第二种方法 (org.apache.commons.lang)
				snzVals[i]=StringEscapeUtils.escapeHtml(rawVals[i]);
				
				//第三种方法( Spring 的优秀工具类盘点)
				//import org.springframework.web.util.HtmlUtils;
				// String str1 = HtmlUtils.htmlEscape(specialStr); ①转换为HTML转义字符表示
			}
			res.put(key, snzVals);
		}			
		return res;
	}
	
	/**
	 * 将特殊字符替换为全角
	 * @param s
	 * @return
	 */
	private  String xssEncode(String s) {
		if (s == null || s.isEmpty()) {
			return s;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '*':
				sb.append('0');// 全角大于号
				break;
			case '<':
				sb.append('1');// 全角小于号
				break;
			case '\'':
				sb.append('2');// 全角单引号
				break;
			case '\"':
				sb.append('“');// 全角双引号
				break;
			case '&':
				sb.append('&');// 全角&
				break;
			case '\\':
				sb.append('\');// 全角斜线
				break;
			case '/':
				sb.append('/');// 全角斜线
				break;
			case '#':
				sb.append('#');// 全角井号
				break;
			case '(':
				sb.append('(');// 全角(号
				break;
			case ')':
				sb.append(')');// 全角)号
				break;
			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}
}
. 自己写 filter 拦截来实现,但要注意的时,在WEB.XML 中配置 filter 的时候,请将这个 filter 放在第一位.

StringEscapeUtils同时也提供了防止sql、js攻击的方法。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。