servlet Filter过滤javascript

新建HttpServletRequestWrapper子类XssHttpServletRequestWrapper

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

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
	public XssHttpServletRequestWrapper(HttpServletRequest request){
		super(request);
	}

	public String[] getParameterValues(String parameter){
		String[] values = super.getParameterValues(parameter);
		if(values==null){
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0;i<count;i++){
			encodedValues[i] = this.cleanXss(values[i]);
		}
		return encodedValues;
	}

	public String getParameter(String parameter){
		String value = super.getParamerter(parameter);
		if(valuee == null){
			return null;
		}
		return cleanXss(value);
	}

	private String cleanXss(String value){
		value = value.replaceAll("<","&lt").replaceAll(">","&gt");
		value = value.replaceAll("script","");
		return value;
	}
}

 在Fileter中调用

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpMethodFilter implements Filter {
    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException {
        HttpServletRequest hsreq = (HttpServletResponse) request;
        HttpServletResponse hsrep = (HttpServletResponse) response;
        chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request),response);
    }
}

 

posted @ 2016-09-21 17:50  为牛马者,背负前行  阅读(259)  评论(0编辑  收藏  举报

如果本页面列出的内容侵犯了您的权益,请告知。
知识共享许可协议
996.icu