jsp过滤非法字符输入 防止XSS跨站攻击

2017-05-09     浏览次数:

一。写一个过滤器
代码如下:
package com.liufeng.sys.filter;
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;
public class IllegalCharacterFilter implements Filter {
 private String[] characterParams = null;
 private boolean OK=true;
 public void destroy() {
  // TODO Auto-generated method stub
 }
 /**
  * 此程序块主要用来解决参数带非法字符等过滤功能
  */
 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[] values = request.getParameterValues(param);
    paramValue = "";
    if(OK){//过滤字符串为0个时 不对字符过滤
    for (int i = 0; i < values.length; i++)
      paramValue=paramValue+values[i];
    for(int i=0;i<characterParams.length;i++)
     if (paramValue.indexOf(characterParams[i]) >= 0) {
      status = true;
      break; www.2cto.com
     }
    if(status)break;
    }
   }
//   System.out.println(param+"="+paramValue+";");
   if (status) {
    PrintWriter out = servletresponse.getWriter();
    out
       .print("<script language='javascript'>alert(\"对不起!您输入内容含有非法字符。如:\\\"'\\\".等\");"
        // + servletrequest.getRequestURL()
         + "window.history.go(-1);</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>IllegalCharacterFilter</filter-name>
  <filter-class>
   com.liufeng.sys.filter.IllegalCharacterFilter
  </filter-class>
  <init-param>
   <param-name>characterParams</param-name>
   <param-value>',@</param-value><!-- 此处加入要过滤的字符或字符串,以逗号隔开 -->
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>IllegalCharacterFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
重启你的服务器就OK了。
这样,增加此过滤器后能提高网站的安全,防止SQL注入,防止跨站脚本XSS等。
*转载请注明出处,更多资料尽在 吾爱编程
返回吾爱编程首页