JavaWeb使用Filter进行字符编码过滤 预防web服务中文乱码

JavaWeb使用Filter进行字符编码过滤 预防web服务中文乱码

准备条件:一个创建好的 JavaWeb 项目

步骤:

1、创建一个类并实现 Filter 接口

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 对网站指定页面进行字符编码过滤,过滤条件在web.xml中配置
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //访问请求调用链上的下一个资源,可以简单理解为对请求或响应处理之后放行
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}

2、在web.xml中配置拦截条件

<!--对web应用下所有由用户直接访问的页面进行字符编码过滤-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.realzs.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

必须注意的一点是:即便 filter-mapping 标签中的 url-pattern 被设置为 /* ,也并不意味着此web应用下的所有资源被调用时都会被拦截, filter-mapping 标签下有一个子标签叫做
dispatcher ,当未被显式定义时, dispatcher 默认属性为REQUEST,此时当用户直接访问 url-pattern 指定的页面时,Web容器将会调用过滤器。如果目标资源是通过RequestDispatcher的include()或forward()方法访问时,那么该过滤器就不会被调用。

想要设置 Filter 在用户直接访问之外的其它资源调用方式下生效,必须显式地声明 dispatcher 标签, filter-mapping 标签下可以设置多个 dispatcher 标签。

参考资料:

[1] 遇见狂神说.JavaWeb入门到实战.bilibili,https://www.bilibili.com/video/BV12J411M7Sj?p=24

[2] 张嫣然.Servlet过滤器----Filter.博客园,https://www.cnblogs.com/zhangyanran/p/10082187.html

posted @ 2021-09-01 17:40  realzhangsan  阅读(232)  评论(0编辑  收藏  举报