Java Web 过滤Xss 代码

    随着社会的发展,企业对项目的要求越来越高,特别是和安全相关的项目,要求不能有注入,Xss等等。博主今天分享一个过滤Xss代码的过滤器。

 

package com.vti.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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;

public class RequestParameterFilter implements Filter {
       //此处是不过滤的参数
	private List<String> excludeNames;

	public List<String> getExcludeNames() {
		return excludeNames;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request = new MyHttpServletRequestWrapper((HttpServletRequest) request);
		chain.doFilter(request, response);
	}
	
	public void init(FilterConfig config) throws ServletException {
		String exclude = config.getInitParameter("exclude");
		if (exclude != null && exclude.length() > 0) {
			excludeNames = Arrays.asList(exclude.split(","));
		}
	}

	public void destroy() {};
	
	private class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

		public MyHttpServletRequestWrapper(HttpServletRequest request) {
			super(request);
		}

		public String getParameter(String name) {
			if (excludeNames != null && excludeNames.contains(name)) {
				return super.getParameter(name);
			}
			return replaceXss(super.getParameter(name));
		}

		public String[] getParameterValues(String name) {
			if (excludeNames != null && excludeNames.contains(name)) {
				return super.getParameterValues(name);
			}
			
			String [] params=super.getParameterValues(name);
			
			for (int i = 0; i < params.length; i++) {
				params[i]=replaceXss(params[i]);
			}
			
			return params;
		}
	}
	
	protected String replaceXss(String value) {
		if (value != null && value.length() > 0) {
			//此处还能加更多的过滤规则
			value=value.replace("<","&lt;");
			value=value.replace(">","&gt;");
			return value;
		}
		return value;
	}
	
}

 

看到这,想必大家都懂了。最后演示下怎么使用:

 

	<filter>
		<filter-name>Xss Filter</filter-name>
		<filter-class>com.vti.filter.RequestParameterFilter</filter-class>
		<init-param>
			<param-name>exclude</param-name>
			<param-value>option</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Xss Filter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

展开阅读全文

没有更多推荐了,返回首页