java写的一个防注入的filter
1.首先编写一个PreventIntoScriptFilter.java,代码如下
package com.questionnaire.common.filter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PreventIntoScriptFilter implements Filter {
private static Log log = LogFactory.getLog(PreventIntoScriptFilter.class);
@Override
public void destroy() {
}
@SuppressWarnings("deprecation")
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
try {
String s = request.getQueryString();
if (s != null) {
// System.out.println("+++++++++++++++++++++++" + s);
Pattern pattern = Pattern
.compile("(?i)[|;$@'\"<>()+,\\\\#]|%7C|%3B|%24|%40|%27|%22|%3C|%3E|%28|%29|%2B|%2C|%5C|%23");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String s3 = s
.replaceAll(
"(?i)[|;$@'\"<>()+,\\\\#]|%7C|%3B|%24|%40|%27|%22|%3C|%3E|%28|%29|%2B|%2C|%5C|%23",
"");
// System.out.println("+++++++++++++++++++++++" + s3);
response.sendRedirect(request.getRequestURL() + "?" + s3);
}
}
} catch (Exception e) {
log.error("PreventIntoScriptFilter 出错了:" + e);
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2.在web.xml中添加如下配置即可
<filter>
<filter-name>preventIntoScriptFilter</filter-name>
<filter-class>com.questionnaire.common.filter.PreventIntoScriptFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>preventIntoScriptFilter</filter-name>
<url-pattern>*.view</url-pattern>
</filter-mapping>
摘自:wuneng94zui
补充:综合编程 , 安全编程 ,