分享JavaWeb中filter过滤器的案例妙用 - 脏话过滤/编码过滤/代码过滤

案例1. 利用Servlet的过滤器Filter进行完成脏话过滤

package cn.javabs.filter;

import java.io.IOException;

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.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class DirtyWordsFilterDemo implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request;
		HttpServletResponse response;
		try{
			request = (HttpServletRequest)req;
			response = (HttpServletResponse)resp;
		}catch(Exception e){
			throw new RuntimeException("non-http request");
		}
		DirtyWordHttpServletRequest dwrequest = new DirtyWordHttpServletRequest(request);
		chain.doFilter(dwrequest, response);
		

	}

	public void destroy() {

	}

}
class DirtyWordHttpServletRequest extends HttpServletRequestWrapper{
	private String strs[] = {"傻逼","畜生","我去年买了个包"};
	private HttpServletRequest request;
	public DirtyWordHttpServletRequest(HttpServletRequest request){
		super(request);
		this.request = request;
	}
	@Override
	public String getParameter(String name) {
		String value = request.getParameter(name);
		if(value==null)
			return null;
		for(String s:strs){
			if(value.contains(s)){
				value = value.replace(s, "**");
			}
		}
		return value;
	}
	
}

案例2. 利用Servlet的过滤器Filter进行完成Html编码过滤

package cn.javabs.filter;

import java.io.IOException;

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.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class HtmlFilterDemo implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request;
		HttpServletResponse response;
		try{
			request = (HttpServletRequest)req;
			response = (HttpServletResponse)resp;
		}catch(Exception e){
			throw new RuntimeException("non-http request");
		}
		
		HtmlHttpServletRequest hrequest = new HtmlHttpServletRequest(request);
		chain.doFilter(hrequest, response);

	}

	public void destroy() {

	}

}
class HtmlHttpServletRequest extends HttpServletRequestWrapper{
	private HttpServletRequest request;
	public HtmlHttpServletRequest(HttpServletRequest request){
		super(request);
		this.request = request;
	}
	@Override
	public String getParameter(String name) {
		String value = request.getParameter(name);
		if(value==null)
			return null;
		value = htmlFilter(value);
		return value;
	}
	private String htmlFilter(String message) {
		if (message == null)
            return (null);

        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
	}
	
}

案例3. 利用Servlet的过滤器Filter进行完成字符编码过滤(Get及Post方式)

	package cn.javabs.filter;

	import java.io.IOException;
	import java.io.UnsupportedEncodingException;

	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.HttpServletRequest;
	import javax.servlet.http.HttpServletRequestWrapper;
	import javax.servlet.http.HttpServletResponse;
	/**
       * 同时解决GET及POST请求参数和响应输出的编码过滤器
       */
	public class SetAllEncodingFilterDemo implements Filter {
		private FilterConfig filterConfig;
		public void init(FilterConfig filterConfig) throws ServletException {
			this.filterConfig = filterConfig;
		}

		public void doFilter(ServletRequest req, ServletResponse resp,
				FilterChain chain) throws IOException, ServletException {
			HttpServletRequest request;
			HttpServletResponse response;
			try{
				request = (HttpServletRequest)req;
				response = (HttpServletResponse)resp;
			}catch(Exception e){
				throw new RuntimeException("non-http request");
			}
			String encoding = "UTF-8";
			String value = filterConfig.getInitParameter("encoding");
			if(value!=null){
				encoding = value;
			}
			
			request.setCharacterEncoding(encoding);//POST请求方式
			response.setContentType("text/html;charset="+encoding);
			MyHttpServletRequest mrequest = new MyHttpServletRequest(request);
			chain.doFilter(mrequest, response);
		}

		public void destroy() {

		}

	}
	class MyHttpServletRequest extends HttpServletRequestWrapper{
		private HttpServletRequest request;
		public MyHttpServletRequest(HttpServletRequest request){
			super(request);
			this.request = request;
		}
		public String getParameter(String name) {
			String value = request.getParameter(name);
			if(value==null)
				return value;
			try {
				if("get".equalsIgnoreCase(request.getMethod()))
					value = new String(value.getBytes("ISO-8859-1"),request.getCharacterEncoding());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return value;
		}
		
	}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏吴伟祥

Apache POI总结 原

Apache POI  是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格...

1281
来自专栏菩提树下的杨过

JSP中的Servlet及Filter

asp.net中,如果开发人员想自己处理http请求响应,可以利用HttpHandler来满足这一要求;类似的,如果要拦截所有http请求,可以使用HttpMo...

2325
来自专栏积累沉淀

适配器模式

思想: 写一个抽象类继承HttpServlet,在这个类中加入通用功能。 以后所有的servlet类都继承自这个 类。 以达到扩展Servlet...

1975
来自专栏闻道于事

JavaWeb项目之电话本,两个版本,以及总结反思

使用技术: Oracle 数据库 前端后台: Servlet + jsp + JDBC + html + css + js 前端界面自定, 但一定实现需要的功能...

5455
来自专栏IT可乐

Servlet 与 Ajax 交互一直报status=parsererror

原因:servlet 返回的数据不是 Json 格式 1、JS代码为: 1 var jsonStr = {'clusterNum':2,'iterationN...

2346
来自专栏拂晓风起

enctype="multipart/form-data"的表单无法获取表单中除了type=file以外的其他参数 commons-fileupload 获取除file外其他参数

1745
来自专栏GIS讲堂

servlet解决浏览器的跨域

在做一些web请求时,会涉及到很麻烦的浏览器跨域问题,因此,一般都会通过后台处理再给前台。本文讲述通过servlet解决浏览器的跨域问题。

3593
来自专栏lgp20151222

生成验证码并校验

1511
来自专栏XAI

POI -纯java代码实现导出excel表格

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 HSSF ...

3947
来自专栏ml

Servlet的尾(yi)巴---filter ( 过滤器 )的小应用

        该,该,该.......,继之前说到的 Filter 现在用这个来做一个小小的应用----------》  铛,铛,铛,铛.....  ->_-...

3499

扫码关注云+社区

领取腾讯云代金券