jsp過濾非法字元輸入 防止XSS跨站攻擊

NO IMAGE

 一。寫一個過濾器

 
程式碼如下:
 
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等。
轉載 :http://www.2cto.com/article/201212/174976.html