什麼是攔截器
攔截器,在AOP(Aspect-Oriented Programming)中用於在某個方法或字段被訪問之前,進行攔截然後在之前或之後加入某些操作。攔截是AOP的一種實現策略。
在 Webwork的中文文檔的解釋爲——攔截器是動態攔截Action調用的對象。它提供了一種機制可以使開發者可以定義在一個action執行的前後執行的代碼,也可以在一個action執行前阻止其執行。同時也是提供了一種可以提取action中可重用的部分的方式。
攔截器的定義和使用
1.定義攔截器
所 有的Struts 2的攔截器都直接或間接實現接口com.opensymphony.xwork2.interceptor.Interceptor。除此之外,大家可能 更喜歡繼承類com.opensymphony.xwork2.interceptor.AbstractInterceptor。
- package test;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- public class TestInterceptor extends AbstractInterceptor {
- @Override
- public String intercept(ActionInvocation arg0) throws Exception {
- System.out.println( "begin intercept" );
- return arg0.invoke();
- }
- }
TestInterceptor.java
arg0.invoke()表示不做任務操作,返回被攔截的action
2.定義action
- package test;
- import com.opensymphony.xwork2.ActionSupport;
- public class Test extends ActionSupport {
- @Override
- public String execute(){
- return SUCCESS;
- }
- }
Test.java
3.配置攔截器
- <? xml version = "1.0" encoding = "UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- < struts >
- < constant name = "struts.action.extension" value = "do" />
- < include file = "struts-default.xml" />
- < package name = "struts" extends = "struts-default" >
- < interceptors >
- < interceptor name = "test" class = "test.TestInterceptor" />
- </ interceptors >
- < action name = "Test" class = "test.Test" >
- < interceptor-ref name = "test" />
- < result name = "error" > /error.jsp </ result >
- < result name = "success" > /success.jsp </ result >
- </ action >
- </ package >
- </ struts >
struts.xml
4.新建jsp,併發布。
訪問http://localhost:8080/Interceptor/Test.do則可看到後到攔截器的運行過程
begin intercept
以上是一個簡單的攔截器的實現。但一般的都要從jsp往傳一些參數,那麼,怎麼辦呢。
在攔截器中我們可以得到session,parameter,application等,我們可以利用這些來傳參數
我現把 TestInterceptor.java 改成
TestInterceptor.java通過parameter傳參數
訪問http://localhost:8080/Interceptor/Test.do同樣可看到後到攔截器的運行過程
但跑的結果就是error,進入error.jsp
訪問http://localhost:8080/Interceptor/Test.do?str=123
結果就是seccuss,進入seccuss.jsp