Servlet 3.0过滤器Filter

原创
2016/06/07 00:25
阅读数 1.4K

Servlet: 

    其中:

  • filterName:即以前web.xml中的filter-name。
  • urlPatterns:访问路径,即web.xml中的filter-mapping->url-pattern
  • initParams :初始化参数,等价于web.xml的init-param节点。name=>param-name>,value=>param-value
/**
 * 字符过滤
 */
@WebFilter(filterName = "/WordFilter", urlPatterns = "/*", initParams = {
		@WebInitParam(name = "encoding", value = "UTF-8"), @WebInitParam(name = "words", value = "日,次奥,靠,艹,尼玛,呵呵") })
public class WordFilter implements Filter {

	private String Encoding;
	private String[] words;

	/**
	 * Default constructor.
	 */
	public WordFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (null != this.Encoding && this.Encoding != "") {
			request.setCharacterEncoding(Encoding);
			request = new MyWordsRequest((HttpServletRequest) request);
			response.setContentType("text/html;" + Encoding);
		}
		chain.doFilter(request, response);
	}

	/**
	 * 文字过滤
	 * 
	 * @param value
	 *            原始文字
	 * @return 返回过滤后的文字
	 */
	private String filter(String value) {
		try {
			if (null != this.words && this.words.length > 0) {
				for (int i = 0; i < words.length; i++) {
					if (value.contains(this.words[i])) {
						value = value.replaceAll(this.words[i], "**");
					}
				}
			}

		} catch (Exception err) {
			err.printStackTrace();
		}
		return value;
	}

	/**
	 * 初始化
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("WordFilter..");
		Encoding = fConfig.getInitParameter("encoding");
		String wordStr = fConfig.getInitParameter("words");
		if (null != wordStr && wordStr != "") {
			this.words = wordStr.split(",");
		}
		System.out.println(this.Encoding + "--" + this.words);
	}

	class MyWordsRequest extends HttpServletRequestWrapper {

		public MyWordsRequest(HttpServletRequest request) {
			super(request);
		}

		@Override
		public String getParameter(String name) {
			return filter(super.getRequest().getParameter(name));
		}

		@Override
		public String[] getParameterValues(String name) {
			String[] values = super.getRequest().getParameterValues(name);
			if (null != values && values.length > 0) {
				for (int i = 0; i < values.length; i++) {
					values[i] = filter(values[i]);
				}
			}
			return values;
		}

	}

}

JSP:

<form action="MessageServlet" method="post">
            <table border="0" width="500" align="center">
                <tr>
                    <td align="right">内 容:</td>
                    <td><textarea rows="5" cols="40" name="content"></textarea></td>
                </tr>
                <tr>
                    <td align="center" colspan="2"><input type="submit"
                        value="提 交"></td>
                </tr>
            </table>
   </form>

MessageServlet:


@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MessageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");
		String content =request.getParameter("content");
		request.setAttribute("title", title);
		request.setAttribute("content", content);
		request.getRequestDispatcher("zuoye1.jsp").forward(request, response);
	}

}

 

效果:

结果:

展开阅读全文
打赏
0
4 收藏
分享
加载中
更多评论
打赏
0 评论
4 收藏
0
分享
返回顶部
顶部