package com.jikexueyuan.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.annotation.WebFilter; /** * Servlet Filter implementation class EncodingFilter */ @WebFilter("/EncodingFilter") public class EncodingFilter implements Filter { private String charEncoding=null; /** * Default constructor. */ public EncodingFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { charEncoding=fConfig.getInitParameter("encoding"); // if(charEncoding==null) //{ System.out.println("EncodingFilter init函数开始"); System.out.println(fConfig.getInitParameter("encoding")); //throw new ServletException("EncodingFilter编码设置为空"); // } System.out.println("EncodingFilter init函数结束"); } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(!charEncoding.equals(request.getCharacterEncoding())){ request.setCharacterEncoding(charEncoding); } response.setCharacterEncoding(charEncoding); chain.doFilter(request, response); } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } }
控制台输出看图
init()被调用了两次
下面是web.xml部分配置信息
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.jikexueyuan.filter.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
解决方案
40
建议你回去研究下注解,为啥会有注解的出现,一开始全用的xml配置,然后两者之间的关系。再看看你的Filter上@WebFilter(“/EncodingFilter”)和你web.xml中的filter配置。你不觉得tomcat在启动的时候会创建两个filter吗?