filter
用来过滤网站数据
例如:处理中文乱码,登录验证
开发步骤
1 导包
2 实现fileter接口 重写相关方法
package com.kuang.jdbc;
import javax.servlet.*;
import java.io.IOException;
/**
* @author shkstart
* @date 2020-06-18-9:44
*/
public class FilterTest implements Filter {
// 初始化 :web服务器启动 就已经初始化 随时等待过滤
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化");
}
// filterChain 链
/**
* 1 过滤中的所有代码 在过滤器特定请求的时候会执行
* 2 必须要让过滤器继续同行
*
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("GBK");
servletResponse.setCharacterEncoding("GBK");
servletResponse.setContentType("text/html");
System.out.println("请求开始");
//请求放行的 如果不写 程序就不会往下走了
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("请求结束");
}
//销毁 web服务器关闭的时候,过滤器会销毁
public void destroy() {
System.out.println("销毁");
}
}
3 配置xml
<filter>
<filter-name>FilterTest</filter-name>
<filter-class>com.kuang.jdbc.FilterTest</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterTest</filter-name>
<url-pattern>/ShowServlet/*</url-pattern>
</filter-mapping>
应用
用户登录之后才能进入主页,用户注销后不能进入主页了!