过滤器Filter
Filter
Filter:过滤器,用来过滤网站数据;
- 处理乱码
- 登录验证...
Filter编写步骤:
-
导包不要导错(javax.servlet)
-
编写过滤器,实现Filter接口,重写对应的方法即可
-
在web.xml中配置Filter
import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { //初始化:web服务器启动就开始初始化了,随时等待过滤对象出现 @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化"); } /* chain: 1. 过滤器中的所有代码,再过滤特定请求时都会执行 2. 必须要让过滤器继续同行 */ @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("CharacterEncodingFilter执行前..."); filterChain.doFilter(servletRequest,servletResponse);//让我们的请求继续走,如果不写程序在这里被拦截停止 System.out.println("CharacterEncodingFilter执行后..."); } //销毁:web服务器关闭时,过滤器会销毁 @Override public void destroy() { System.out.println("销毁"); } }
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.company.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!-- 只要是/servlet的任何请求都要经过过滤器 --> <url-pattern>/servlet/*</url-pattern> </filter-mapping>