除了使用配置文件配置之外,還能夠使用注解來配置
以下是一些經常使用的注解
介紹:
@Action/@Actions:
@Action指定一個類為action,相應配置文件里的<action>....</action>標簽,當中能夠配置例如以下屬性
- results:配置返回的結果集屬性,相當於struts2中的<result>列表,能夠在{}中配置屬性,詳細例如以下
- value:配置action的名字,相當於<action>中的name屬性
- interceptorRefs:配置攔截器
@Action能夠定義在類上,也能夠定義在方法上
例如以下(@Result的作用后面講,也能夠和后面的配合着看)
@Action(value = "testAction",results = {@Result(name="success",location="/success.jsp")}) public class testAction extends ActionSupport { @Override public String execute() throws Exception { return SUCCESS; } }這就相當於例如以下的xml配置
<action name="testAction" class="struts2.action.testAction"> <result name="success">/success.jsp</result> </action>在xml配置中假設name不寫,那么默認就是success,在注解中也是,假設results中的name不寫。那么默認就是success
也能夠使用@Actions來指定多個action映射,這樣能夠做到一個類相應多個地址映射。例如以下
@Actions({ @Action(value = "testAction",results = {@Result(location="/success.jsp")}), @Action(value = "testAction2",results = {@Result(location="/success.jsp")}) }) public class testAction extends ActionSupport { @Override public String execute() throws Exception { return SUCCESS; } }這是使用/testAction或者/testAction2都能夠跳轉到success.jsp上。由於配置了兩個action映射
在xml配置中,我們有例如以下的配置方法
<action name="*" class="struts2.action.testAction" method={1}> <result name="{1}">/{1}.jsp</result> </action>這是xml配置中的通配符方式,即當我們以add來訪問action時。將會進到action的add方法進行處理。當返回add時會跳轉到add.jsp頁面
在注解中沒有通配符能夠使用,可是也能夠實現類似的效果,這時@Action就要寫在方法上了,就像以下這樣
public class testAction extends ActionSupport { @Action(value = "add",results = {@Result(name="add",location="/add.jsp")}) public String add() throws Exception { return "add"; } @Action(value = "delete",results = {@Result(name="delete",location="/delete.jsp")}) public String delete() throws Exception { return "delete"; } }這樣便實現了上面的效果。這說明@Action也是能夠在方法上聲明的(@Actions也能夠在方法上聲明)
@Result/@Results:
@Result配置詳細返回結果。在results中使用,也能夠單獨在類上使用,有例如以下屬性
- name:相應<result>中的name屬性
- location:相應<result></result>間的地址
- type:相應<result>的type屬性
@Result能夠在類上聲明。也能夠和Action配置聲明,假設在類上聲明,那么就是全局的結果,例如以下
@Result(name="delete",location = "/delete.jsp") public class testAction extends ActionSupport { @Action(value = "add", results = { @Result(name = "add", location = "/add.jsp") }) public String add() throws Exception { return "add"; } @Action(value = "delete") public String delete() throws Exception { return "delete"; } }盡管delete方法沒有指定返回delete時要跳轉到哪個頁面頁面。可是在類上用@Result聲明了,那么就會找到類上面的這個@Result,然后跳轉到delete.jsp頁面
@Results是用來聲明多個結果集。使用方法和@Actions類似,這里就不再詳述