java过滤非法字符的filter

jsp页面的编码你设成你自己的,我用的是utf-8。
input.jsp输入后,正常跳转到handle.jsp,而禁词已经被过滤。 
filter:
package test;

import java.io.*;
import javax.servlet.*;
import java.util.*;

public class MyFilter implements Filter
{
    private List<String> unString;

    public void init(FilterConfig filterConfig) throws ServletException
    {
        unString = new ArrayList<String>();
        unString.add("日");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException
    {
        String content = request.getParameter("content");//需要过滤的参数
        if(content!=null){
            for (int i = 0; i < unString.size(); i++)
            {
                String strIllegal = unString.get(i);
                if (content.indexOf(strIllegal) >= 0)
                {
                    content = content.replaceAll(strIllegal, "");//非法字符替换成空
                }
                request.setAttribute("content", content);//为request设置属性保存修改后的值
            }
        }
        chain.doFilter(request, response);
    }
    public void destroy()
    {
        //System.out.println("过滤器销毁");
    }
}

//---------------------------//
web.xml:
<filter>
  <filter-name>myfilter</filter-name>
  <filter-class>test.MyFilter</filter-class>
  </filter>

  <filter-mapping>
  <filter-name>myfilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

//---------------------------//
输入页面input.jsp:

<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>input.jsp</title>
 </head>

 <body>
 <form action="handle.jsp" method="post">
  <input type="text" name="content" />
  <input type="submit" value=" 提交 " />
 </form>
 </body>
</html>

//---------------------------//
input提交的页面handle.jsp:
<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> handle.jsp </title>
 </head>

 <body>
 <%
  String content = (String)request.getAttribute("content");
  out.println(content);
 %>
 </body>
</html>



    我用了HttpServletRequestWrapper 重写了 getPartermeter等方法

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值