1.web.xml中配置filter
- <filter>
- <filter-name>XssFilter</filter-name>
- <filter-class>com.wk.util.XssFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>XssFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
2.编写相应的filter的java类
- package com.wk.util;
- 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 destroy() {
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- chain.doFilter(new XssHttpServletRequestWraper(
- (HttpServletRequest)request), response);//对request和response进行过滤
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- }
- }
- package com.wk.util;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- /**
- *
- * @author wk
- * @date 2015-8-6
- */
- public class XssHttpServletRequestWraper extends HttpServletRequestWrapper {
- public XssHttpServletRequestWraper(HttpServletRequest request) {
- super(request);
- }
- @Override
- public String getParameter(String name) {
- return clearXss(super.getParameter(name));
- }
- @Override
- public String getHeader(String name) {
- return clearXss(super.getHeader(name));
- }
- @Override
- public String[] getParameterValues(String name) {
- String[] values = super.getParameterValues(name);
- if (values == null) {
- return null;
- }
- String[] newValues = new String[values.length];
- for (int i = 0; i < values.length; i++) {
- newValues[i] = clearXss(values[i]);
- }
- return newValues;
- }
- /**
- * 处理字符转义
- *
- * @param value
- * @return
- */
- private String clearXss(String value) {
- if (value == null || "".equals(value)) {
- return value;
- }
- value = value.replaceAll("<", "<").replaceAll(">", ">");
- value = value.replaceAll("\\(", "(").replace("\\)", ")");
- value = value.replaceAll("'", "'");
- value = value.replaceAll("eval\\((.*)\\)", "");
- value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
- "\"\"");
- value = value.replace("script", "");
- return value;
- }
- }
4.当然喽,此处多说一句,在装饰类中不仅可以拦截XSS脚本攻击,还可以将请求参数中的空格去掉,这样就不用在每一个action中都要去掉提交参数值的前后空格了,至于Injection Flows等sql注入的问题也可以一概解决了
转载:http://blog.csdn.net/woniumenga/article/details/47323829