詳解Java的Struts框架中注釋的用法
要開始在你的項目中使用注釋,確保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 將被捕獲的姓名和年齡使用一個簡單的頁面,我們將會把兩個驗證,以確保使用總是進(jìn)入一個名字和年齡應(yīng)該是在28和65之間。所以,讓我們先從主JSP頁面的例子。
創(chuàng)建主頁:
讓我們寫主JSP頁面文件index.jsp,這將被用來收集上述員工的相關(guān)信息。
<%@ 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的標(biāo)簽,我們還沒有覆蓋,但我們將研究這些標(biāo)簽相關(guān)的章節(jié)。但現(xiàn)在,假設(shè)s:textfield 標(biāo)簽打印一個輸入字段 s:submit 打印一個提交按鈕。我們已經(jīng)使用label屬性標(biāo)簽,每個標(biāo)簽每個標(biāo)簽創(chuàng)建。
創(chuàng)建視圖:
我們將使用JSP文件的success.jsp將調(diào)用的情況下定義的動作返回SUCCESS。
<%@ 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文件。請確保操作類擴(kuò)展ActionSupport類,否則validate方法將不會被執(zhí)行。
package com.yiibai.struts2;
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;
}
}
在這個例子中,我們已經(jīng)使用了一些注解。讓我逐個說明:
首先,我們已經(jīng)Result注解。結(jié)果注解的結(jié)果是一個集合。結(jié)果注解下,我們有兩個結(jié)果注釋。結(jié)果注釋的名稱對應(yīng)的執(zhí)行方法的結(jié)果。它們還含有一個視圖應(yīng)擔(dān)任相應(yīng)的execute() 返回值的位置。
下一個注解是行動注解。這是用來修飾 execute()方法。操作方法也需要一個值,該URL上調(diào)用操作。
最后,使用兩個驗證的注解。已經(jīng)配置了所需的字段驗證的年齡字段"name“字段和整數(shù)范圍驗證。也指定了自定義驗證消息。
配置文件:
我們不需要struts.xml 配置文件,讓我們刪除該文件,并讓我們檢查web.xml文件中的內(nèi)容:
<?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服務(wù)器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給出以下畫面:

現(xiàn)在不輸入任何所需信息,只需點擊“Submit ”按鈕。將看到以下結(jié)果:

輸入所需的信息,但輸入了錯誤的“From ”字段,讓我們說“test”和年齡為30名,最后點擊“Submit ”按鈕。將看到以下結(jié)果:

Struts 2的注釋類型
Struts 2 應(yīng)用程序可以使用Java5注釋作為替代XML和Java屬性配置??梢詸z查最重要的注解涉及不同類別的列表:
Struts 2 應(yīng)用程序可以使用Java5注釋作為替代XML和Java屬性配置。這里是清單的不同的類別有關(guān)的最重要的注解:
命名空間注釋(動作注釋):
@ Namespace注釋允許在Action類中,而不是基于零配置的約定動作的命名空間的定義。
@Namespace("/content")
public class Employee extends ActionSupport{
...
}
結(jié)果注釋 - (動作譯注):
@ Result注解允許在Action類中,而不是一個XML文件中定義的動作結(jié)果。
@Result(name="success", value="/success.jsp")
public class Employee extends ActionSupport{
...
}
結(jié)果注釋 - (動作譯注):
@ Results注解定義了一套動作的結(jié)果。
@Results({
@Result(name="success", value="/success.jsp"),
@Result(name="error", value="/error.jsp")
})
public class Employee extends ActionSupport{
...
}
注釋后(攔截注釋):
@After注解標(biāo)志著一個需要調(diào)用后的主要操作方法和執(zhí)行結(jié)果的操作方法。返回值將被忽略。
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注釋標(biāo)記需要一個操作方法的主要操作方法之前被調(diào)用執(zhí)行結(jié)果。返回值將被忽略。
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注解標(biāo)志著一個結(jié)果之前需要執(zhí)行的操作方法。返回值將被忽略。
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注釋 - (驗證譯注):
此驗證注解如果有任何轉(zhuǎn)換錯誤進(jìn)行了實地檢查,并適用于他們,如果他們存在。
public class Employee extends ActionSupport{
@ConversionErrorFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getName() {
return name;
}
}
DateRangeFieldValidator注釋 - (驗證譯注):
這驗證注解檢查日期字段的值在指定范圍內(nèi)。
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注釋 - (驗證譯注):
此驗證注解檢查雙字段有一個值,該值在指定范圍內(nèi)。如果既不最小或最大,什么都不會做的。
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地址,如果它包含一個非空的字符串。
public class Employee extends ActionSupport{
@EmailValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getEmail() {
return email;
}
}
ExpressionValidator注釋 - (驗證譯注):
這種非字段級驗證驗證所提供的正則表達(dá)式。
@ExpressionValidator(message = "Default message", key = "i18n.key",
shortCircuit = true, expression = "an OGNL expression" )
IntRangeFieldValidator注釋 - (驗證譯注):
這驗證注解檢查一個數(shù)字字段的值在指定的范圍內(nèi)。如果既不最小或最大,什么都不會做的。
public class Employee extends ActionSupport{
@IntRangeFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true,
min = "0", max = "42")
public String getAge() {
return age;
}
}
RegexFieldValidator 注釋 - (驗證譯注):
這個注解驗證一個字符串字段,使用正則表達(dá)式。
@RegexFieldValidator( key = "regex.field", expression = "yourregexp")
RequiredFieldValidator 注釋 - (驗證譯注):
這驗證注解檢查一個字段不為空。標(biāo)注必須被應(yīng)用在方法層面。
public class Employee extends ActionSupport{
@RequiredFieldValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getAge() {
return age;
}
}
RequiredStringValidator注釋 - (驗證譯注):
這驗證注解檢查一個字符串字段不為空(即非空,長度> 0)。
public class Employee extends ActionSupport{
@RequiredStringValidator(message = "Default message",
key = "i18n.key", shortCircuit = true, trim = true)
public String getName() {
return name;
}
}
StringLengthFieldValidator注釋 - (驗證譯注):
這個驗證檢查字符串字段是合適的長度。假定該字段是一個字符串。如果設(shè)置既不是minLength 也不是最大長度,什么都不會做。
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。
public class Employee extends ActionSupport{
@UrlValidator(message = "Default message",
key = "i18n.key", shortCircuit = true)
public String getURL() {
return url;
}
}
驗證注釋 - (驗證譯注):
如果想使用多個相同類型的注釋,這些注釋必須嵌套在@Validations() 注釋。
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.
@CustomValidator(type ="customValidatorName", fieldName = "myField")
轉(zhuǎn)換注釋 - (類型轉(zhuǎn)換注釋):
這是一個標(biāo)記注釋類型轉(zhuǎn)換類型級別。轉(zhuǎn)換注釋必須應(yīng)用在類型級別。
@Conversion()
public class ConversionAction implements Action {
}
CreateIfNull注釋 - (類型轉(zhuǎn)換注釋):
這個注解設(shè)置類型轉(zhuǎn)換CreateIfNull。必須應(yīng)用在域或方法級CreateIfNull注解。
@CreateIfNull( value = true ) private List<User> users;
元素注釋 - (類型轉(zhuǎn)換注釋):
這個注解設(shè)置元素進(jìn)行類型轉(zhuǎn)換。必須應(yīng)用在字段域或方法級元素的注解。
@Element( value = com.acme.User ) private List<User> userList;
關(guān)鍵注釋 - (類型轉(zhuǎn)換注釋):
這個注解設(shè)置進(jìn)行類型轉(zhuǎn)換的關(guān)鍵。必須應(yīng)用在域或方法級的關(guān)鍵注解。
@Key( value = java.lang.Long.class ) private Map<Long, User> userMap;
KeyProperty注釋 - (類型轉(zhuǎn)換注釋):
這個注解設(shè)置類型轉(zhuǎn)換KeyProperty。必須應(yīng)用在域或方法級KeyProperty注解。
@KeyProperty( value = "userName" ) protected List<User> users = null;
TypeConversion注釋 - (類型轉(zhuǎn)換注釋):
這個注解的注解是用于類和應(yīng)用程序的轉(zhuǎn)換規(guī)則。注解可以應(yīng)用于TypeConversion在屬性和方法的級別。
@TypeConversion(rule = ConversionRule.COLLECTION,
converter = "java.util.String")
public void setUsers( List users ) {
this.users = users;
}
- Java的Struts框架中配置國際化的資源存儲的要點解析
- 深入解析Java的Struts框架中的控制器DispatchAction
- 詳解Java的Struts框架以及相關(guān)的MVC設(shè)計理念
- Java的Struts框架中登陸功能的實現(xiàn)和表單處理器的使用
- Java的Struts框架中append標(biāo)簽與generator標(biāo)簽的使用
- 簡單說明Java的Struts框架中merge標(biāo)簽的使用方法
- 總結(jié)Java的Struts框架的異常處理方法
- Java的Struts框架中Action的編寫與攔截器的使用方法
- Java下Struts框架中的ActionForm類詳解
相關(guān)文章
SpringBoot使用JdbcTemplate操作數(shù)據(jù)庫
這篇文章主要介紹了SpringBoot使用JdbcTemplate操作數(shù)據(jù)庫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Spring中@PropertySource和@Value注解詳解
這篇文章主要介紹了Spring中@PropertySource和@Value注解詳解,@PropertySource注解可以方便和靈活的向Spring的環(huán)境容器(org.springframework.core.env.Environment Environment)中注入一些屬性,這些屬性可以在Bean中使用,需要的朋友可以參考下2023-11-11
生成PDF全攻略之在已有PDF上添加內(nèi)容的實現(xiàn)方法
下面小編就為大家?guī)硪黄蒔DF全攻略之在已有PDF上添加內(nèi)容的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
java的arraylist排序示例(arraylist用法)
這篇文章主要介紹了java的arraylist排序示例,學(xué)習(xí)一下arraylist的用法,需要的朋友可以參考下2014-03-03
springboot(thymeleaf)中th:field和th:value的區(qū)別及說明
這篇文章主要介紹了springboot(thymeleaf)中th:field和th:value的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

