使用註解來配置Action的最大好處就是能夠實現零配置,可是事務都是有利有弊的,使用方便,維護起來就沒那麼方便了。java
要使用註解方式,咱們必須添加一個額外包:struts2-convention-plugin-2.x.x.jar。web
雖然說是零配置的,但struts.xml仍是少不了的,配置以下:spring
<?xml version="1.0" encoding="UTF-8" ?> apache
<!DOCTYPE struts PUBLIC 數組
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" 瀏覽器
"http://struts.apache.org/dtds/struts-2.1.7.dtd"> 緩存
<struts> app
<!-- 請求參數的編碼方式--> jsp
<constant name="struts.i18n.encoding" value="UTF-8"/> this
<!-- 指定被struts2處理的請求後綴類型。多個用逗號隔開-->
<constant name="struts.action.extension" value="action,do,htm"/>
<!-- 當struts.xml改動後,是否從新加載。默認值爲false(生產環境下使用),開發階段最好打開 -->
<constant name="struts.configuration.xml.reload" value="true"/>
<!-- 是否使用struts的開發模式。開發模式會有更多的調試信息。默認值爲false(生產環境下使用),開發階段最好打開 -->
<constant name="struts.devMode" value="false"/>
<!-- 設置瀏覽器是否緩存靜態內容。默認值爲true(生產環境下使用),開發階段最好關閉 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 指定由spring負責action對象的建立
<constant name="struts.objectFactory" value="spring" />
-->
<!-- 是否開啓動態方法調用-->
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
</struts>
action類的註解:
package com.tjcyjd.web.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
/**
* Struts2基於註解的Action配置
*
*/
@ParentPackage("struts-default")
@Namespace("/annotation_test")
@Results( { @Result(name = "success", location = "/main.jsp"),
@Result(name = "error", location = "/error.jsp") })
@ExceptionMappings( { @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") })
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 2730268055700929183L;
private String loginName;
private String password;
@Action("login") //或者寫成 @Action(value = "login")
public String login() throws Exception {
if ("yjd".equals(loginName) && "yjd".equals(password)) {
return SUCCESS;
} else {
return ERROR;
}
}
@Action(value = "add", results = { @Result(name = "success", location = "/index.jsp") })
public String add() throws Exception {
return SUCCESS;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password= password;
}
}
這樣就完成了一個基於註解的action配置。
總結經常使用的註解以下:
Namespace:指定命名空間。
ParentPackage:指定父包。
Result:提供了Action結果的映射。(一個結果的映射)
Results:「Result」註解列表
ResultPath:指定結果頁面的基路徑。
Action:指定Action的訪問URL。
Actions:「Action」註解列表。
ExceptionMapping:指定異常映射。(映射一個聲明異常)
ExceptionMappings:一級聲明異常的數組。
InterceptorRef:攔截器引用。
InterceptorRefs:攔截器引用組。