Filter
-
Filter:过滤器,用来过滤网站的数据
-
用来处理 中文乱码
-
登录验证等等
-
Filter开发步骤:
- 导包
import javax.servlet.*;
- 重写对应方法
public class CharacterEncodingFilter implements Filter {
/**
* web服务器启动执行该方法
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
/**
* 1. 过滤中的所有代码,在过滤特定请求的时候都会执行
* 2. 必须要让过滤器继续同行
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
@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销毁");
}
}
在web.xml中配置Filter映射
<filter>
<filter-name>CharecterFilter</filter-name>
<filter-class>com.saxon.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharecterFilter</filter-name>
<!-- 只要是/servlet/的请求,都会经过这个过滤器 -->
<!-- <url-pattern>/servlet/*</url-pattern>-->
<!-- 都会经过这个过滤器 -->
<url-pattern>/*</url-pattern>
</filter-mapping>