欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java过滤非法字符的filter

程序员文章站 2024-02-08 17:30:52
...
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等方法