用过滤器让全站html标签转义输出

package cn.lfd.web.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;
/*
 * 用过滤器让全站html标签转义输出
 */
public class HtmlFilter implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;//对ServletResponse进行强转
		HttpServletResponse response = (HttpServletResponse) resp;
		
		MyHtmlRequest MyRequest = new MyHtmlRequest(request);//new 出一个增强后的request
		chain.doFilter(MyRequest, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}
//增强HttpServletRequest方法的getParameter方法
class MyHtmlRequest extends HttpServletRequestWrapper {

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

	@Override
	public String getParameter(String name) {//对getParameter方法进行增强
		String value = super.getParameter(name);
		if(value==null) {
			return null;
		}
		return filter(value);//调用filter方法对数据进行html转义
	}
	
	 public String filter(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("<");
	                break;
	            case '>':
	                result.append(">");
	                break;
	            case '&':
	                result.append("&");
	                break;
	            case '"':
	                result.append(""");
	                break;
	            default:
	                result.append(content[i]);
	            }
	        }
	        return (result.toString());

	    }
}

注意:

1.filter方法可以在tomcat安装目录下的\webapps\examples\WEB-INF\classes\util的HTMLFilter.java中复制过来

你可能感兴趣的:(java,filter,javaweb,过滤器,html转义)