拦截器(Interceptor)与过滤器(Filter)

 一、拦截器与过滤器的区别:
1filter基于回调函数,而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();
		}
	}

}
 
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值