利用filter 过滤掉html标签

web.xml配置文件:
HtmlFilter
com.itheima.filter.HtmlFilter
HtmlFilter
/*


java代码:
public class HtmlFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;

try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
HtmlHttpServletRequest hrequest = new HtmlHttpServletRequest(request);
chain.doFilter(hrequest, response);

}

public void destroy() {
// TODO Auto-generated method stub

}

}
class HtmlHttpServletRequest extends HttpServletRequestWrapper{

public HtmlHttpServletRequest(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
String value = super.getParameter(name);
if(value==null)
return value;
value = filter(value);
return value;
}
private 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());
}

你可能感兴趣的:(java)