1. 程式人生 > >攔截器(Interceptor)與過濾器(Filter)的區別與使用

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