一、拦截器与过滤器的区别:
1、filter基于回调函数,而interceptor则基于java本身的反射机制,这是两者最本质的区别。
2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器
3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求 起作用 。
4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能
5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次 。
二、举例
1、filter实现获取某个指定文件的图片失败时,返回一个默认的图片,用于提示用户。
<!--errorImgFilter过滤器 --> <filter> <filter-name>errorImgFilter</filter-name> <filter-class>com.yingjun.sharing.web.ErrorImgFilter</filter-class> </filter> <filter-mapping> <filter-name>errorImgFilter</filter-name> <url-pattern>/filelibs/*</url-pattern> </filter-mapping>
package com.yingjun.sharing.web;
import java.io.File;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* 获取指定文件下的文件失败时,返回一个默认的图片,用于提示用户
*
*/
public class ErrorImgFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化ErrorImgFilter");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("执行ErrorImgFilter");
HttpServletRequest req = (HttpServletRequest) request;
String realPath = req.getSession().getServletContext().getRealPath("/");
String contextPath = req.getContextPath();
String requestURI = req.getRequestURI();
String fileUrl = realPath + requestURI.substring(contextPath.length());
File f = new File(fileUrl);
if (!f.exists()) {
request.getRequestDispatcher("/images/front/errorImg.png").forward(request, response);
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("销毁ErrorImgFilter");
}
}
效果图:
2、interceptor来检测用户是否登录以及分页的实现。
<interceptors> <!-- struts2拦截器 --> <interceptor name="sessionInterceptor" class="com.yingjun.sharing.web.SessionInterceptor" /> <interceptor name="pagerInterceptor" class="com.yingjun.sharing.web.PagerInterceptor" /> <interceptor-stack name="myStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="sessionInterceptor"> <!-- 以下方法sessionInterceptor拦截器不拦截--> <param name="excludeMethods">login*,checkUserExistWithName,register</param> </interceptor-ref> <interceptor-ref name="pagerInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 全局拦截器栈 --> <default-interceptor-ref name="myStack"></default-interceptor-ref> <global-results> <result name="error">/WEB-INF/error/error.jsp</result> </global-results>
package com.yingjun.sharing.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.yingjun.sharing.dto.SessionInfo;
/**
* session拦截器
*
*/
public class SessionInterceptor extends MethodFilterInterceptor {
private static final long serialVersionUID = 1L;
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
HttpServletRequest request=ServletActionContext.getRequest();
SessionInfo sessionInfo = (SessionInfo)request.getSession().getAttribute("SessionInfo");
System.out.println("#######SessionInterceptor:"+request.getRequestURI());
if (sessionInfo == null) {
request.setAttribute("msg", "您还没有登录或登录已超时,请退出重新登录,然后再刷新本功能!");
return "error";
}
return actionInvocation.invoke();
}
}
package com.yingjun.sharing.web;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.yingjun.sharing.pager.SystemContext;
public class PagerInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation arg) throws Exception {
System.out.println("#######PagerInterceptor:"+arg.getAction().toString());
Integer offset = 0;//起始值
Integer page = 1;//第几页
Integer rows=15;//每页显示个数
try {
offset = Integer.parseInt(ServletActionContext.getRequest().getParameter("offset"));
} catch (NumberFormatException e) {}
try {
page = Integer.parseInt(ServletActionContext.getRequest().getParameter("page"));
} catch (NumberFormatException e) {}
try {
rows = Integer.parseInt(ServletActionContext.getRequest().getParameter("rows"));
} catch (NumberFormatException e) {}
try {
SystemContext.setOrder(ServletActionContext.getRequest().getParameter("order"));
SystemContext.setSort(ServletActionContext.getRequest().getParameter("sort"));
SystemContext.setOffset(offset);
SystemContext.setRows(rows);
SystemContext.setPage(page);
return arg.invoke();
} finally {
SystemContext.removeOrder();
SystemContext.removeSort();
SystemContext.removeOffset();
SystemContext.removeRows();
SystemContext.removePage();
}
}
}