Filter过滤器
1.过滤器要实现Filter接口 import javax.servlet.*
public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); chain.doFilter(request,response); //如果不写chain 将被阻塞在这 } @Override public void destroy() { System.out.println("销毁"); } }
2. 在web.xml中注册Filter
<filter> <filter-name>filter</filter-name> <filter-class>com.cai.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>*</url-pattern> </filter-mapping>