博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
替换禁用语(指定关键字)的过滤器(StopWordsFilter)
阅读量:4616 次
发布时间:2019-06-09

本文共 4740 字,大约阅读时间需要 15 分钟。

    本系列文章导读:

        

        

        

        

       

功能描述

        将请求响应中所有的禁用关键字替换掉之后再输出。

使用方法

        在 java web 项目的 web.xml 文件中添加如下代码。

StopWordsFilter
com.hmw.filter.StopWordsFilter
需要禁用的关键字,一个关键字占一行
keys
QQ 百度 七一五
StopWordsFilter
*.jsp

过滤器源码

ReplaceKeyWordFilter.java

package com.hmw.filter;import java.io.IOException;import java.io.PrintWriter;import java.util.HashSet;import java.util.Iterator;import java.util.Set;import java.util.StringTokenizer;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.HttpServletResponse;/** * 替换关键字的滤器  *  * @author  */public class StopWordsFilter implements Filter {    private Set keyWords = new HashSet();    /**     * 将需要进行替换的关键字添加到一个定义好的 Set 中     */    @Override    public void init(FilterConfig config) throws ServletException {        String keys =  config.getInitParameter("keys");        StringTokenizer tokenizer = new StringTokenizer(keys);        String token = null;        while (tokenizer.hasMoreTokens()) {            token = tokenizer.nextToken();            if(token != null && token.length() > 0){                keyWords.add(tokenizer.nextToken());            }        }    }    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws ServletException, IOException {        CharArrayWrapper responseWrapper = new CharArrayWrapper(                (HttpServletResponse) response);        // 调用请求资源(使用自己包装的 responseWrapper)        chain.doFilter(request, responseWrapper);        // 取得响应字符串        String responseString = responseWrapper.toString();        // 将需要替换的关键字用“**”替换掉        Iterator iter = keyWords.iterator();        while (iter.hasNext()) {            responseString = replace(responseString, iter.next(), "**");        }                // 修改响应头信息中的 Content-Length        response.setContentLength(responseString.length());        PrintWriter out = response.getWriter();        out.write(responseString);    }    @Override    public void destroy() {    }    /**     * 将字符串中的所有的指定子字符串替换掉     * @param mainString 需要进行替换的字符串     * @param orig 需要被替换的子串     * @param replacement 替换后的新串     * @return 返回替换后的字符串     */    public static String replace(String mainString, String orig, String replacement) {        String result = "";        int oldIndex = 0;        int index = 0;        int origLength = orig.length();        while ((index = mainString.indexOf(orig, oldIndex)) != -1) {            result = result + mainString.substring(oldIndex, index) + replacement;            oldIndex = index + origLength;        }        result = result + mainString.substring(oldIndex);        return result;    }}

CharArrayWrapper.java

package com.hmw.filter;import java.io.CharArrayWriter;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpServletResponseWrapper;/** * A response wrapper that takes everything the client would normally output and * saves it in one big character array. */public class CharArrayWrapper extends HttpServletResponseWrapper {	private CharArrayWriter charWriter;	/**	 * Initializes wrapper.	 * 

* First, this constructor calls the parent constructor. That call is * crucial so that the response is stored and thus setHeader, *setStatus, * addCookie, and so forth work normally. *

* Second, this constructor creates a CharArrayWriter that will be used to * accumulate the response. */ public CharArrayWrapper(HttpServletResponse response) { super(response); charWriter = new CharArrayWriter(); } /** * When servlets or JSP pages ask for the Writer, don't give them the real * one. Instead, give them a version that writes into the character array. * The filter needs to send the contents of the array to the client (perhaps * after modifying it). */ @Override public PrintWriter getWriter() { return new PrintWriter(charWriter); } /** * Get a String representation of the entire buffer. *

* Be sure not to call this method multiple times on the same * wrapper. The API for CharArrayWriter does not guarantee that it * "remembers" the previous value, so the call is likely to make a new * String every time. */ @Override public String toString() { return charWriter.toString(); } /** Get the underlying character array. */ public char[] toCharArray() { return charWriter.toCharArray(); }}

转载于:https://www.cnblogs.com/hemingwang0902/archive/2012/01/13/stop-words-filter.html

你可能感兴趣的文章
未来SEO的发展方向和趋势猜测与分析
查看>>
Python面向对象——多态
查看>>
键盘事件的运用
查看>>
e b
查看>>
CSS居中
查看>>
搜索引擎点击隐藏文字
查看>>
关于YII2如何修改默认控制器的问题
查看>>
QML和JS引擎的关系以及调用c++函数的原理
查看>>
35.在PCB中删除元件
查看>>
数据库MySQL-----介绍,安装配置
查看>>
Friends (ZOJ - 3710)
查看>>
解决:Ubuntu无法进入图形化界面(报错/dev/sda2:clean)
查看>>
div(固定宽度和不固定宽度)居中显示的方法总结
查看>>
还原MySql数据库失败:max_allowed_packet 设置过小导致记录写入失败
查看>>
PhpStorm 9.03 集成 开源中国(oschina.net)的Git项目,提交SVN时注意事项
查看>>
css选择器的优先级
查看>>
学习笔记3
查看>>
jquery中的prop与attr区别
查看>>
OpenGL ES无法获取贴图数据原因
查看>>
jmeter取样器--FTP测试计划
查看>>