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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值