Filter中文字符过滤器工具类和xml配置方法

    技术2022-07-10  94

    代码如下:

    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; public class CharacterFilter implements Filter { String encoding = null; @Override public void destroy() { encoding = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding != null) { request.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); } /* * 在过滤器对象的doFilter()方法中,业务逻辑处理完成之后, * 需要通过FilterChain对象的doFilter()方法将请求传递到下一过滤器或目标资源,否则将出现错误。 */ chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter("encoding"); } }

    xml的配置:

    <filter> <filter-name>CharacterFilter</filter-name> <filter-class>filter.CharacterFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
    Processed: 0.019, SQL: 14