閱讀677 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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

一。寫一個過濾器

代碼如下:

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;
     }
    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等。

最後更新:2017-04-02 16:47:54

  上一篇:go android的開源電話/通訊/IM聊天項目全集
  下一篇:go 移動互聯網產品設計的原則