过滤器
1. 过滤中的所有代码,在过滤特定请求的时候都会执行
2. 必须要让过滤器继续执行
public class FilterEncoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("已经初始化了");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
System.out.println("过滤前");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("过滤后");
}
@Override
public void destroy() {
System.out.println("销毁");
}
}
映射过滤器:
<servlet>
<servlet-name>showFilter</servlet-name>
<servlet-class>com.xia.Filter.Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showFilter</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showFilter</servlet-name>
<url-pattern>/Filter/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f</filter-name>
<filter-class>com.xia.Filter.FilterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>f</filter-name>
<url-pattern>/Filter/show</url-pattern>
</filter-mapping>