过滤器(Filter)
Filter:用来过滤网站的数据
filter的用法和servlet基本一样
作用:
- 处理中文乱码
- 登录验证等等
- 有了过滤器,我们就不需要在每个servlet中设置字符集编码,这个就提高了开发效率
思路如图:
开发步骤:
- 导包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
- 编写过滤器(实现Filter接口,重写对应的方法)
public class CharacterEncodingFilter implements Filter {
//初始化
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化了");
}
/*
1.过滤中的所有代码,再过滤特定请求的时候都会执行
2.必须要让过滤器继续前进
filterChain.doFilter(servletRequest,servletResponse);
*/
@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执行后");
}
//销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter初始化了");
}
}
重点:一定要写filterChain.doFilter(servletRequest,servletResponse);这样才可以让过滤器继续前进
- 在web.xml中配置
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--要过滤什么,路径包含什么就可以了-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
这样改过滤的servlet就得到了过滤。
注意:这里的