实现javax.servlet.Filter接口。
实现接口中的三个方法:
init(FilterConfig filterConfig) throws ServletException
当servlet容器创建该filter实例的时候调用该方法进行初始化设置。
该方法可以读取,web.xml中的参数配置。
配置的格式如下:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.baidu.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
encoding = filterConfig.getInitParameter(“encoding”);
取出初始化参数
public void init(FilterConfig fConfig) throws ServletException {
encoding = fConfig.getInitParameter("encoding");
}
doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException
当客户端请求服务资源或是回复的时候调用该方法进行filter功能处理。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
req.setCharacterEncoding(encoding);
System.out.println("编码过滤器,执行。。。。");
chain.doFilter(req, resp);
}
destroy( )
当服务不在使用该filter功能的时候被web容器调用,此后的web请求将不在进行doFilter中的处理。
Filter的使用
package com.baidu.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CharacterEncodingFilter implements Filter {
private String encoding;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
req.setCharacterEncoding(encoding);
System.out.println("编码过滤器,执行。。。。");
chain.doFilter(req, resp);
}
public void init(FilterConfig fConfig) throws ServletException {
encoding = fConfig.getInitParameter("encoding");
}
}
Filter的几个作用
1,过滤所有网页修改编码格式;
2,对需要保护的的页面进行过滤;
3,记录来访日志,
4,防御DDS的攻击(现在很少使用了)。