拦截器(Interceptor)与过滤器(Filter)的区别与使用


Filter:过滤器Interceptor:拦截器
过滤从客户端向服务器发送的请求。(既可拦截Action,也可拦截静态资源,如:html、css、js、图片等)拦截是客户端对Action的访问。更细粒度化的拦截。(拦截Action中的具体的方法)

使用方法:

拦截器:Interceptor

作用:主要是拦截Action

用法:

1、定义一个拦截器类
  • a、实现Interceptor接口
  • b、继承AbstractInterceptor(推荐)
2、在intercept(ActionInvocation invocation)方法中编写代码
  • 拦截:
    设置错误消息
	//传递错误消息到页面
	ActionSupport action = (ActionSupport) invocation.getAction();	
	action.addActionError("你没有权限访问!");
	//跳转页面
	return "input";
	...
	//放行:
	return invocation.invoke();
3、配置拦截器 struts.xml
  • 声明拦截器:
	<package name="customerModel" extends="struts-default">
		<interceptors>
			<interceptor name="拦截器1" class="拦截器1的全路径"/>
			<interceptor name="拦截器2" class="拦截器2的全路径"/>
			<interceptor name="拦截器3" class="拦截器3的全路径"/>
		</interceptors>
	<package>
  • 使用拦截器:
	<!-- 在action标签中使用拦截器 -->
	<action name="cust_*" class="com.qs.web.CustomerAction" method="{1}">
		<result name="result">/jsp/customer/list.jsp</result>
		<result name="addUI">/jsp/customer/add.jsp</result>
		<result name="input" type="redirect">/login.jsp</result>
					
		<!-- 引入系统的拦截器栈 -->
		<interceptor-ref name="defaultStack"/>
		<interceptor-ref name="拦截器1"/>
		<interceptor-ref name="拦截器2"/>
		<interceptor-ref name="拦截器3"/>
	</action>

过滤器:Filter

作用:拦截Action、jsp等静态资源

用法:

1、定义一个过滤器类
  • a、实现Filter接口
  • b、继承Filter的子类
2、在filter中重写doFilter(ServletRequest request, ServletResponse response, FilterChain chain)方法
  • 拦截:
    在request对象中,封装了http请求头的所有信息;所以可以根据request得到这个请求需要的资源是什么,如果不允许访问,就可以根据资源路径来拦截
	HttpServletResponse resp = (HttpServletResponse) response;
	resp.sendRedirect("/login.jsp");
	//放行:
	chain.doFilter(request, response);
3、filter的配置,在web.xml中配置
	<filter>
		<filter-name>sessionFilter</filter-name>
		<filter-class>com.qs.web.filter.JspFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>sessionFilter</filter-name>
		<!--拦截所有的jsp-->
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值