在项目中,会遇到关于sql注入,以及跨站脚本,XSS,链接注入等攻击,这里就需要做一些验证,当时接到这个需求,在网上查找了半天终于找到一篇文章,并拿来测试,但是,这个里面是有一些错误的。
package com.cn.util;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
*
* @ClassName: IllegalCharacter
* @Description: 此模块用于非法字符验证
* @author huxd
* @date 2017年3月26日 下午12:07:28
*
*/
public class IllegalCharacter implements Filter{
private String[] characterParams = null;
private boolean OK=true;
public void destroy() {
}
/**
* 此程序块主要用来解决参数带非法字符等过滤功能
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest servletrequest = (HttpServletRequest) request;
HttpServletResponse servletresponse = (HttpServletResponse) response;
boolean status = false;
java.util.Enumeration params = request.getParameterNames();
String param="";
String paramValue = "";
servletresponse.setContentType("text/html");
servletresponse.setCharacterEncoding("utf-8");
while (params.hasMoreElements()) {
param = (String) params.nextElement();
// 这里原代码是用的 String[] 接的数据,这样会造成一些非法字符 <,> 等,这些都是无法转换的!造成是空,这个坑了我2个小时才找到
String values = request.getParameter(param);
paramValue = "";
if(OK){//过滤字符串为0个时 不对字符过滤
paramValue=paramValue+values;
for(int i=0;i<characterParams.length;i++)
if (paramValue.indexOf(characterParams[i]) >= 0) {
status = true;
break;
}
if(status)break;
}
}
if (status) {
PrintWriter out = servletresponse.getWriter();
out
.print("<script language='javascript'>alert(\"您提交的相关表单数据字符含有非法字符。如:\\\"'\\\".\");location.href('"
+ servletrequest.getRequestURL()
+ "');</script>");
}else
arg2.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
if(config.getInitParameter("characterParams").length()<1)
OK=false;
else
this.characterParams = config.getInitParameter("characterParams").split(",");
}
}
web.xml配置
<!-- 跨域脚本攻击防御 -->
<!-- 非法字符过滤器 -->
<filter>
<filter-name>IllegalCharacter</filter-name>
<filter-class>com.cn.util.IllegalCharacter</filter-class>
<init-param>
<param-name>characterParams</param-name>
<param-value><,>,;,",”,“,*,@,IMG,SRC,$,@,',",|,>,+,CR,LF</param-value><!-- 此处加入要过滤的字符或字符串,以逗号隔开 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>IllegalCharacter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>