要開始在你的項目中使用注釋,確保WebContent/WEB-INF/lib文件夾中的jar文件包括以下:
- struts2-convention-plugin-x.y.z.jar
- asm-x.y.jar
- antlr-x.y.z.jar
- commons-fileupload-x.y.z.jar
- commons-io-x.y.z.jar
- commons-lang-x.y.jar
- commons-logging-x.y.z.jar
- commons-logging-api-x.y.jar
- freemarker-x.y.z.jar
- javassist-.xy.z.GA
- ognl-x.y.z.jar
- struts2-core-x.y.z.jar
- xwork-core.x.y.z.jar
現(xiàn)在,讓我們看看你如何能做到配置在struts.xml文件,取而代之的是注解。
Struts2注釋的概念的解釋,我們需要重新考慮我們的驗證為例說明在 Struts2的驗證 一章中。
在這里,我們將采取一個例子,雇員Employee 將被捕獲的姓名和年齡使用一個簡單的頁面,我們將會把兩個驗證,以確保使用總是進入一個名字和年齡應該是在28和65之間。所以,讓我們先從主JSP頁面的例子。
創(chuàng)建主頁:
讓我們寫主JSP頁面文件index.jsp,這將被用來收集上述員工的相關信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>Employee Form</title> </head> <body> <s:form action= "empinfo" method= "post" > <s:textfield name= "name" label= "Name" size= "20" /> <s:textfield name= "age" label= "Age" size= "20" /> <s:submit name= "submit" label= "Submit" align= "center" /> </s:form> </body> </html> |
在index.jsp使用Struts的標簽,我們還沒有覆蓋,但我們將研究這些標簽相關的章節(jié)。但現(xiàn)在,假設s:textfield 標簽打印一個輸入字段 s:submit 打印一個提交按鈕。我們已經使用label屬性標簽,每個標簽每個標簽創(chuàng)建。
創(chuàng)建視圖:
我們將使用JSP文件的success.jsp將調用的情況下定義的動作返回SUCCESS。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>Success</title> </head> <body> Employee Information is captured successfully. </body> </html> |
創(chuàng)建動作:
這是將用于注釋的地方。讓我們重新定義行動Employee類的注釋,然后添加一個方法稱為validate() ,如下所示在Employee.java文件。請確保操作類擴展ActionSupport類,否則validate方法將不會被執(zhí)行。
package com.yiibai.struts2;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import com.opensymphony.xwork2.validator.annotations.*; @Results ({ @Result (name= "success" , location= "/success.jsp" ), @Result (name= "input" , location= "/index.jsp" ) }) public class Employee extends ActionSupport{ private String name; private int age; @Action (value= "/empinfo" ) public String execute() { return SUCCESS; } @RequiredFieldValidator ( message = "The name is required" ) public String getName() { return name; } public void setName(String name) { this .name = name; } @IntRangeFieldValidator (message = "Age must be in between 28 and 65" , min = "29" , max = "65" ) public int getAge() { return age; } public void setAge( int age) { this .age = age; } } |
在這個例子中,我們已經使用了一些注解。讓我逐個說明:
首先,我們已經Result注解。結果注解的結果是一個集合。結果注解下,我們有兩個結果注釋。結果注釋的名稱對應的執(zhí)行方法的結果。它們還含有一個視圖應擔任相應的execute() 返回值的位置。
下一個注解是行動注解。這是用來修飾 execute()方法。操作方法也需要一個值,該URL上調用操作。
最后,使用兩個驗證的注解。已經配置了所需的字段驗證的年齡字段"name“字段和整數(shù)范圍驗證。也指定了自定義驗證消息。
配置文件:
我們不需要struts.xml 配置文件,讓我們刪除該文件,并讓我們檢查web.xml文件中的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display-name >Struts 2</ display-name > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > < filter > < filter-name >struts2</ filter-name > < filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class > < init-param > < param-name >struts.devMode</ param-name > < param-value >true</ param-value > </ init-param > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > </ web-app > |
現(xiàn)在,右鍵點擊項目名稱,并單擊 Export > WAR File創(chuàng)建一個WAR文件。然后部署此WAR在Tomcat的webapps目錄下。最后,啟動Tomcat服務器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給出以下畫面:
現(xiàn)在不輸入任何所需信息,只需點擊“Submit ”按鈕。將看到以下結果:
輸入所需的信息,但輸入了錯誤的“From ”字段,讓我們說“test”和年齡為30名,最后點擊“Submit ”按鈕。將看到以下結果:
Struts 2的注釋類型
Struts 2 應用程序可以使用Java5注釋作為替代XML和Java屬性配置。可以檢查最重要的注解涉及不同類別的列表:
Struts 2 應用程序可以使用Java5注釋作為替代XML和Java屬性配置。這里是清單的不同的類別有關的最重要的注解:
命名空間注釋(動作注釋):
@ Namespace注釋允許在Action類中,而不是基于零配置的約定動作的命名空間的定義。
1
2
3
4
|
@Namespace ( "/content" ) public class Employee extends ActionSupport{ ... } |
結果注釋 - (動作譯注):
@ Result注解允許在Action類中,而不是一個XML文件中定義的動作結果。
1
2
3
4
|
@Result (name= "success" , value= "/success.jsp" ) public class Employee extends ActionSupport{ ... } |
結果注釋 - (動作譯注):
@ Results注解定義了一套動作的結果。
1
2
3
4
5
6
7
|
@Results ({ @Result (name= "success" , value= "/success.jsp" ), @Result (name= "error" , value= "/error.jsp" ) }) public class Employee extends ActionSupport{ ... } |
注釋后(攔截注釋):
@After注解標志著一個需要調用后的主要操作方法和執(zhí)行結果的操作方法。返回值將被忽略。
1
2
3
4
5
6
7
8
9
10
|
public class Employee extends ActionSupport{ @After public void isValid() throws ValidationException { // validate model object, throw exception if failed } public String execute() { // perform secure action return SUCCESS; } } |
注釋之前(攔截注釋):
@ Before注釋標記需要一個操作方法的主要操作方法之前被調用執(zhí)行結果。返回值將被忽略。
1
2
3
4
5
6
7
8
9
10
|
public class Employee extends ActionSupport{ @Before public void isAuthorized() throws AuthenticationException { // authorize request, throw exception if failed } public String execute() { // perform secure action return SUCCESS; } } |
BeforeResult注釋 - (攔截注釋):
@ BeforeResult注解標志著一個結果之前需要執(zhí)行的操作方法。返回值將被忽略。
1
2
3
4
5
6
7
8
9
10
11
|
public class Employee extends ActionSupport{ @BeforeResult public void isValid() throws ValidationException { // validate model object, throw exception if failed } public String execute() { // perform action return SUCCESS; } } |
ConversionErrorFieldValidator注釋 - (驗證譯注):
此驗證注解如果有任何轉換錯誤進行了實地檢查,并適用于他們,如果他們存在。
1
2
3
4
5
6
7
|
public class Employee extends ActionSupport{ @ConversionErrorFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true ) public String getName() { return name; } } |
DateRangeFieldValidator注釋 - (驗證譯注):
這驗證注解檢查日期字段的值在指定范圍內。
1
2
3
4
5
6
7
8
|
public class Employee extends ActionSupport{ @DateRangeFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true , min = "2005/01/01" , max = "2005/12/31" ) public String getDOB() { return dob; } } |
DoubleRangeFieldValidator注釋 - (驗證譯注):
此驗證注解檢查雙字段有一個值,該值在指定范圍內。如果既不最小或最大,什么都不會做的。
1
2
3
4
5
6
7
8
9
|
public class Employee extends ActionSupport{ @DoubleRangeFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true , minInclusive = "0.123" , maxInclusive = "99.987" ) public String getIncome() { return income; } } |
EmailValidator注釋 - (驗證譯注):
這驗證注解檢查一個字段是一個有效的E-mail地址,如果它包含一個非空的字符串。
1
2
3
4
5
6
7
8
|
public class Employee extends ActionSupport{ @EmailValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true ) public String getEmail() { return email; } } |
ExpressionValidator注釋 - (驗證譯注):
這種非字段級驗證驗證所提供的正則表達式。
@ExpressionValidator(message = "Default message", key = "i18n.key",
shortCircuit = true, expression = "an OGNL expression" )
IntRangeFieldValidator注釋 - (驗證譯注):
這驗證注解檢查一個數(shù)字字段的值在指定的范圍內。如果既不最小或最大,什么都不會做的。
1
2
3
4
5
6
7
8
9
|
public class Employee extends ActionSupport{ @IntRangeFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true , min = "0" , max = "42" ) public String getAge() { return age; } } |
RegexFieldValidator 注釋 - (驗證譯注):
這個注解驗證一個字符串字段,使用正則表達式。
@RegexFieldValidator( key = "regex.field", expression = "yourregexp")
RequiredFieldValidator 注釋 - (驗證譯注):
這驗證注解檢查一個字段不為空。標注必須被應用在方法層面。
1
2
3
4
5
6
7
8
|
public class Employee extends ActionSupport{ @RequiredFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true ) public String getAge() { return age; } } |
RequiredStringValidator注釋 - (驗證譯注):
這驗證注解檢查一個字符串字段不為空(即非空,長度> 0)。
1
2
3
4
5
6
7
8
|
public class Employee extends ActionSupport{ @RequiredStringValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true , trim = true ) public String getName() { return name; } } |
StringLengthFieldValidator注釋 - (驗證譯注):
這個驗證檢查字符串字段是合適的長度。假定該字段是一個字符串。如果設置既不是minLength 也不是最大長度,什么都不會做。
1
2
3
4
5
6
7
8
9
|
public class Employee extends ActionSupport{ @StringLengthFieldValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true , trim = true , minLength = "5" , maxLength = "12" ) public String getName() { return name; } } |
UrlValidator注釋 - (驗證譯注):
這個驗證檢查一個字段是一個有效的URL。
1
2
3
4
5
6
7
8
|
public class Employee extends ActionSupport{ @UrlValidator (message = "Default message" , key = "i18n.key" , shortCircuit = true ) public String getURL() { return url; } } |
驗證注釋 - (驗證譯注):
如果想使用多個相同類型的注釋,這些注釋必須嵌套在@Validations() 注釋。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class Employee extends ActionSupport{ @Validations ( requiredFields = { @RequiredFieldValidator (type = ValidatorType.SIMPLE, fieldName = "customfield" , message = "You must enter a value for field." )}, requiredStrings = { @RequiredStringValidator (type = ValidatorType.SIMPLE, fieldName = "stringisrequired" , message = "You must enter a value for string." )} ) public String getName() { return name; } } |
CustomValidator注釋 - (驗證譯注):
這個注解可以用于自定義驗證。使用ValidationParameter的注釋,以提供額外的 params.
1
|
@CustomValidator (type = "customValidatorName" , fieldName = "myField" ) |
轉換注釋 - (類型轉換注釋):
這是一個標記注釋類型轉換類型級別。轉換注釋必須應用在類型級別。
1
2
3
|
@Conversion () public class ConversionAction implements Action { } |
CreateIfNull注釋 - (類型轉換注釋):
這個注解設置類型轉換CreateIfNull。必須應用在域或方法級CreateIfNull注解。
1
2
|
@CreateIfNull ( value = true ) private List<User> users; |
元素注釋 - (類型轉換注釋):
這個注解設置元素進行類型轉換。必須應用在字段域或方法級元素的注解。
1
2
|
@Element ( value = com.acme.User ) private List<User> userList; |
關鍵注釋 - (類型轉換注釋):
這個注解設置進行類型轉換的關鍵。必須應用在域或方法級的關鍵注解。
1
2
|
@Key ( value = java.lang.Long. class ) private Map<Long, User> userMap; |
KeyProperty注釋 - (類型轉換注釋):
這個注解設置類型轉換KeyProperty。必須應用在域或方法級KeyProperty注解。
1
2
|
@KeyProperty ( value = "userName" ) protected List<User> users = null ; |
TypeConversion注釋 - (類型轉換注釋):
這個注解的注解是用于類和應用程序的轉換規(guī)則。注解可以應用于TypeConversion在屬性和方法的級別。
1
2
3
4
5
|
@TypeConversion (rule = ConversionRule.COLLECTION, converter = "java.util.String" ) public void setUsers( List users ) { this .users = users; } |