过滤器filter过滤input里面输入的标签

package edu.sanyang.hr.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;


@WebFilter("/*")
public class HTMLFilter implements Filter {
     
	private String coding = "utf-8";
   
    public HTMLFilter() {
     
    }

	
	public void destroy() {
     
	}
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
     
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		HTMLHttpServletRequest htmlRequest = new HTMLHttpServletRequest(request);
		
		
		chain.doFilter(htmlRequest, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
     
	}

}

/**
 * 
 * @author ASUS
 *	��֤html��ǩ
 */
class HTMLHttpServletRequest extends HttpServletRequestWrapper {
     

	public HTMLHttpServletRequest(HttpServletRequest request) {
     
		super(request);
	}
	
	@Override
	public String getParameter(String name) {
     
		 String value = super.getParameter(name);
		 if (value == null) {
     
			return value;
		}
		 value = htmlName(value);
		 return value;
	}

	private String htmlName(String message) {
     
		//E:\\apache-tomcat-8.0.50\\webapps\\examples\\WEB-INF\\classes\\util\\HTMLFilter.java
		 char content[] = new char[message.length()];
	        message.getChars(0, message.length(), content, 0);
	        StringBuilder result = new StringBuilder(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());
	}
}

例如你在前端页面的里面输入一个存入数据库,然后查询出来显示在页面时显示的是一个按钮,而不是,
这个过滤器就解决这个问题

你可能感兴趣的:(java)