1、导包,filter代码
import javax.servlet.*;
import java.io.IOException;
public class filter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse.setCharacterEncoding("UTF-8"); //通过过滤器设置响应得字符格式
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;Charset=utf-8");
System.out.println("filter执行之前");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("filter执行之后");
}
public void destroy() {
}
}
2、在web.xml中配置filter
<filter>
<filter-name>filter_1</filter-name>
<filter-class>com.cling.filter.filter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter_1</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
下面得代码中/s1没有经过filter,而/servlet/s1经过了filter。
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet/s1</url-pattern>
</servlet-mapping>