Filter(过滤器/拦截器)的作用
1、filter用于拦截用户请求,在服务器作出响应前,可以在拦截后修改request和response,这样实现很多开发者想得到的功能。
2、filter实现×编写一个继承Filter接口的类
×在工程的web.xml文件描述此过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>CharsetEcodingFilter2</filter-name>
<filter-class>cn.itcast.filter.CharsetEcodingFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>CharsetEcodingFilter2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3、常见用法
×处理全站中文乱码问题
×实现自动登录
×过滤敏感词汇
×压缩网页
×选择性让浏览器缓存
这几种功能的实现采用同样的原理,那就是使用包装模式或动态代理增强request或response对象的功能。
Filter工作流程图:
范例代码:
-------------web.xml-----------:
<filter>
<filter-name>mutiDomainFilter</filter-name>
<filter-class>javacommon.filter.MutiDomainFilter</filter-class>
</filter>
------------MutiDomainFilter.java----------:
public class MutiDomainFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
// 自动编码处理
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String reqUri = request.getRequestURI();
try {
// 过滤非二级域名url
String modulePath = UrlUtil.getProdModulePath(request);
if (modulePath == null) {
<strong>filterChain.doFilter(request, response);</strong>
return;
}
// 更改url路径
String qryString = request.getQueryString();
StringBuilder sb = new StringBuilder();
sb.append(modulePath).append(reqUri == null ? "" : reqUri)
.append(qryString == null ? "" : qryString);
System.out.println("changed url:" + sb.toString());
<strong>request.getRequestDispatcher(sb.toString()).forward(request,
response);</strong>
} catch (SecurityException e) {
} finally {
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}