TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
在很多时候,网页中会包含一些服务器不想展现给用户的内容,服务器端需要先对这些内容过滤。
通常可以使用过滤器Filter进行敏感字符过滤。过滤器捕捉页面的响应内容,并缓存,然后将其中的敏感字替换成别的字。首先建立一个类来接收页面的响应内容,如下:
- package examples;
- 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 examples;
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-app
PUBLIC "-//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> 下面是运行结果:
源码下载:http://file.javaxxz.com/2014/10/9/235026218.zip |
|