javaWeb 使用 filter 处理 html 标签问题

1.web.xml代码

    <filter>
        <filter-name>HtmlFilter</filter-name>
        <filter-class>de.bvb.web.filter.HtmlFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HtmlFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping> 

2.de.bvb.web.filter.HtmlFilter.java 代码

package de.bvb.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;

public class HtmlFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        chain.doFilter(new HtmlHttpServletRequestWrapper(request), response);
    }

    class HtmlHttpServletRequestWrapper extends HttpServletRequestWrapper {

        private HttpServletRequest request;

        public HtmlHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        @Override
        public String getParameter(String name) {
            return filter(request.getParameter(name));
        }

        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("&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());
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

}

 

posted @ 2016-12-13 17:12  MarcoReus  阅读(1353)  评论(0编辑  收藏  举报