专栏首页Java技术分享圈分享JavaWeb中filter过滤器的案例妙用 - 脏话过滤/编码过滤/代码过滤

分享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 条评论
登录 后参与评论

相关文章

  • 杨校老师课堂之Servlet的重构为BaseServlet的步骤

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.n...

    杨校
  • 杨校老师课堂之基于Servlet整合JQuery中的Ajax进行表单提交[基于IDEA]

    杨校
  • 基于Servlet的3.1以上注解方式完成上传功能。

    注意:这里采用的是servlet的注解方式,即要求在Servlet3.1版本以上。另,Tomcat7.0版本以上

    杨校
  • 子域名枚举的艺术深度剖析

    子域名枚举是信息收集中关键的一步,细节很大程度决定战果。本文参考The Art of Subdomain Enumeration,加上实践运用进行总结。

    FB客服
  • 部署ssl证书需要注意什么呢?

    随着社会经济的快速发展,人们的日常生活已经离不开互联网的作用了。互联网的存在使得人们的信息交互变得更加快捷方便,同时也让我们的生活多了许多乐趣。但...

    合信ssl证书
  • 云数据库MySQL入门机型重磅上线

    数据库MySQL入门机型是腾讯云数据库团队打造的一款适用于广大用户入门、学习、培训,生产前测试、小规模业务系统的产品。同时也具备管理和扩展,主从实时热备,自动容...

    云服务器教程
  • 统计PG数据库的库和表大小

    转载地址: https://blog.csdn.net/rocklee/article/details/51251174

    二狗不要跑
  • day16_ajax学习笔记

    JavaScript 中 XMLHttpRequest对象是整个Ajax技术的核心,它提供了异步发送请求的能力。

    黑泽君
  • 使用JavaScript的FormData向SAP ABAP系统发起登录请求

    Jerry Wang
  • P3381 【模板】最小费用最大流

    题目描述 如题,给出一个网络图,以及其源点和汇点,每条边已知其最大流量和单位流量费用,求出其网络最大流和在最大流情况下的最小费用。 输入输出格式 输入格式: 第...

    attack

扫码关注云+社区

领取腾讯云代金券