Filter过滤器用来设置整个应用的字符编码是一个不错的选择。Filter的生命周期同servlet的生命周期是一样的。它们都提供了init(FilterConfig arg0)destroy()方法来控制。当web容器启动的时候,就会自动调用init(FilterConfig arg0)来对filter进行初始化,当关闭web容器,关机,或者reload整个应用时,都会调用destroy()来关闭filter。也就是说,当web容器启动时,filter就被加载到内存,并在destroy()调用之前都常驻内存。

   1.创建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;

 

public class ShopFilter implements Filter {

 

    public void destroy() {

       System.out.println("filter关闭........");

       

    }

 

    public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain fChain) throws IOException, ServletException {

            request.setCharacterEncoding("utf-8");

            response.setCharacterEncoding("utf-8");

            fChain.doFilter(request, response);

 

    }

 

    public void init(FilterConfig arg0) throws ServletException {

       //filter的生命周期

       System.out.println("初始化........");

 

    }

 

}

2.xml中配置:

    <filter>

       <filter-name>Filter</filter-name>

       <filter-class>com.xie.shop.filter.ShopFilter</filter-class>

    </filter>

    <filter-mapping>

       <filter-name>Filter</filter-name>

       <url-pattern>/*</url-pattern>

</filter-mapping>(/*表示对于任意请求)

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐