首页 > 技术文章 > java中的拦截器和过滤器

gdutcaleb 2017-03-06 21:24 原文

拦截器与过滤器的区别 : 
1. 拦截器是基于java的反射机制的,而过滤器是基于函数回调。
2. 拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
3. 拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
4. 拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
5. 在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次

拦截器的代码实现(以struts2为例):
1、在xml文件中如何定义拦截器
<interceptors>
<interceptor name="filterIPInterceptor"
class="com.xxxx.web.FilterIPActionInterceptor" />
<interceptor-stack name="filterIPStack">
<interceptor-ref name="defaultStack" />

<interceptor-ref name="filterIPInterceptor" />
</interceptor-stack>
</interceptors>

2、怎么遍别写自定义拦截器

public class FilterIPActionInterceptor extends AbstractInterceptor
{
/** 日志控制. */
private final Log log = LogFactory.getLog(getClass());

/**
* @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
@Override
@SuppressWarnings("unchecked")
public String intercept(ActionInvocation invocation) throws Exception
{
String result = null;
// 获得当前方法名.
String methodName = invocation.getInvocationContext().getName();
String currIp = null;
try
{
if (invocation.getAction() instanceof PortletAction)
{
PortletAction action = (PortletAction) invocation.getAction();
currIp = action.getRequest().getRemoteAddr();
}
String ip = ApplicationResource.getHotValue("ALLOW_CACHE_IP");

if (StringUtils.isBlank(ip) || StringUtils.isBlank(currIp))
{
log.error("允许刷新的IP不存在或当前请求的IP非法.");
throw new NoAllowIPException();
}
else
{
String[] ips = ip.split(",");
boolean errorIp = true;
for (String s : ips)
{
if (s.equals(currIp))
errorIp = false;
}
// 判断IP
if (errorIp)
throw new NoAllowIPException();
}
result = invocation.invoke();//调用被拦截的方法
}
catch (Exception e)
{
log.error("异常类名:" + invocation.getAction().getClass());
log.error("异常方法:" + methodName, e);
throw e;
}

return result;
}

}

3、怎么编写过滤器

1、在web.xml里面配置自定义的拦截器
<filter>
<filter-name>Redirect Filter</filter-name>
<filter-class>com.xx.filter.RedirectFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>Redirect Filter</filter-name>
<url-pattern>/xx/xx/*</url-pattern>

</filter-mapping>

2、如何编写自定义的拦截器
public class RedirectFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// 获取URL
Long startTime = null;
if (log.isDebugEnabled())
{
startTime = System.currentTimeMillis();
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String url = httpRequest.getRequestURL().toString();
if (url == null || url.trim().length() == 0) {
return;
}
if (url.indexOf(luceneCreateMapping) != -1
|| url.indexOf(luceneSearchMapping) != -1) {
doFilterForxxx(request, response, url);
} else {
doxxxx(request, response, url);
}
if (log.isDebugEnabled())
{
long endTime = System.currentTimeMillis();
Thread currentThread = Thread.currentThread();
String threadName = currentThread.getName();
log.debug("[" + threadName + "]" + "< "
+ this.getClass().getName() + " " + url + " "
+ (endTime - startTime) + " ms");
}
// 激活下一个Filter
filterChain.doFilter(request, response);

}
}

推荐阅读