在java中对服务器端的部分内容进行过滤

    技术2022-05-11  30

            在做web开发时,很多时候,网页中会包含一些服务器不想展现给用户的内容,这时服务器端就需要先对这些内容过滤。        通常可以使用过滤器Filter进行敏感字符过滤。过滤器捕捉页面的响应内容,并缓存,然后将其中的敏感字替换成别的字。首先建立一个类来接收页面的响应内容,如下:

    package com.hrf.util;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class CharResponseWrapper extends HttpServletResponseWrapper{    private CharArrayWriter output;

        public String toString(){       return output.toString();    }

        public CharResponseWrapper(HttpServletResponse response){      super(response);      output=new CharArrayWriter();    }

        public PrintWriter getWriter(){      return new PrintWriter(output);    }   }

    这个类重载了toString方法,由此可以将网页中的内容转化为字符串,然后在过滤器的类中重写响应的内容,把敏感字去掉。如下是过滤器的

    代码:package com.hrf.util;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

    public class WordFilter implements Filter{    protected FilterConfig filterConfig;

        public void init(FilterConfig config) throws ServletException{       this.filterConfig=config;    }

        public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws        IOException,ServletException{      PrintWriter out=response.getWriter();      CharResponseWrapper wrapper=new CharResponseWrapper((HttpServletResponse)response);      chain.doFilter(request,wrapper);            String resStr=wrapper.toString();      String newStr="";

          if(resStr.indexOf("is")>0){            newStr=resStr.replaceAll("is","***");      }      out.println(newStr);     }

         public void destroy(){       this.filterConfig=null;     }

         public void setFilterConfig(final FilterConfig filterConfig){        this.filterConfig=filterConfig;     }}

    在程序中,out.println(str)就是输出的网页内容,这个字符串在程序中重写过,把网页中的字符串is替换为***。

    最后在web.xml文件中配置这个过滤器:

    web.xml文件

    <?xml version="1.0" encoding="ISO-8859-1"?>

    <!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd">

    <web-app><filter><filter-name>WordFilter</filter-name><filter-class>examples.WordFilter</filter-class></filter>

    <filter-mapping><filter-name>WordFilter</filter-name><url-pattern>/index.jsp</url-pattern></filter-mapping>

    </web-app>

    这个过滤器应用到index.jsp

    <%@ page contentType="text/html; charset=GBK" %>

    <html><head><title>Welcome</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body>Welcome!!<br>This is a String!</body></html>


    最新回复(0)