过滤器是实现了Filter接口的一个java类,是Servlet的高级应用,可以处理request和response,该接口有下面三种方法
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
}
public void init(FilterConfig filterConfig) throws ServletException {
}
工作区间
// 注解配置(@WebFilter(filterName="FilterTest",urlPatterns="/*"))
// 但我这里用xml配置
public class FilterTest implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//需要执行的逻辑代码在这里
System.out.println("我是首个Filter");
//表示放行
chain.doFilter(request, response);
// 表示处理Response
System.out.println("处理响应的地方");
}
public void init(FilterConfig filterConfig) throws ServletException {
}
<filter>
<filter-name>FilterTest</filter-name>
<filter-class>filter.FilterTest</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterTest</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
使用了责任链模式,具体请看这里 责任链模式(使用Filter来举例)
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//ServletRequest功能不够强大,需要强转成HttpSerlvet
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//设置编码
httpServletRequest.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("text/html;charset=UTF-8");
//表示放行
chain.doFilter(request, response);
}
装饰类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
this.request = request;
}
public String getParameter(String name) {
String value = this.request.getParameter(name);
if (value == null) {
return null;
}
//如果不是get方法的,直接返回就行了
if (!this.request.getMethod().equalsIgnoreCase("get")) {
return null;
}
try {
//进来了就说明是get方法,把乱码的数据
value = new String(value.getBytes("ISO8859-1"), this.request.getCharacterEncoding());
return value ;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException("不支持该编码");
}
}
}
实现
MyRequest myRequest = new MyRequest(httpServletRequest);
//装饰增加新功能
Filter也有FilterConfig这个对象,来获取里面的初始化参数,至此我们可以知道,获取xml配置初始化参数有Config这个对象