拦截器(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>

猜你喜欢

转载自blog.csdn.net/weixin_44142296/article/details/85106578