先貼個本帖的地址,以免被爬:struts2教程 官方系列六:表單驗證? 即?http://www.cnblogs.com/linghaoxinpian/p/6906720.html?
下載本章節代碼
?
介紹
在本教程中,我們將探索使用Struts2來驗證用戶在表單上的輸入。有兩種方法可以來進行表單驗證。本教程將介紹更基本的方法,在Struts2 Action類中包含驗證。
為了使Struts2 Action類在Struts2 表單中驗證用戶的輸入,您必須在Action類中定義一個validate方法。假設我們有這些業務規則:
1.用戶必須提供第一個名稱用戶
2.必須提供一個電子郵件地址用戶
3.未到18歲不能注冊
?
添加如下代碼到/src/action/RegisterAction.java中
validate method
public void validate(){if (personBean.getFirstName().length() == 0) {addFieldError("personBean.firstName", "First name is required.");}if (personBean.getEmail().length() == 0) {addFieldError("personBean.email", "Email is required.");}if (personBean.getAge() < 18) {addFieldError("personBean.age", "Age is required and must be 18 or older");} }
當用戶在register表單上按下提交按鈕時,Struts2將把用戶的輸入傳遞給personBean的實例字段。然后Struts 2將自動執行validate?方法。如果if判斷條件為true,那么Struts2將調用它的addFieldError方法(繼承自ActionSupport類)。
如果驗證失敗,那么Struts2就不會繼續調用execute方法了。相反,Struts2 將返回“input”作為該操作的結果。(常用結果的還有success、error)
?
處理 "Input" 結果
那么,如果Struts2返回“input”表示用戶的表單輸入無效,那么接下來該怎么辦呢?在大多數情況下,我們將希望重新顯示具有表單的web頁面,并將錯誤消息包含在表單中,以告知用戶。
為了處理"input" 結果,我們需要在struts.xml添加配置:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN""http://struts.apache.org/dtds/struts-2.5.dtd"><struts><constant name="struts.devMode" value="true" /><package name="basicstruts2" extends="struts-default"><action name="index"><result>/index.jsp</result></action><!--hello-><action name="hello" class="action.HelloWorldAction" method="execute"><result name="success">/HelloWorld.jsp</result></action><!-- register --><action name="register" class="action.RegisterAction" method="execute"><result name="success">/thankyou.jsp</result><result name="input">/register.jsp</result></action></package></struts>
?因此,當驗證失敗,Struts2 返回"input"結果時,Struts2 將重新顯示register.jsp。由于我們使用了Struts2 的表單標簽,因此Struts2將自動的添加錯誤消息。這些錯誤消息是我們在addFieldError方法調用中指定的。addFieldError方法有兩個參數。第一個是錯誤字段的表單字段名,第二個是在表單字段上方顯示的錯誤消息 ?
addFieldError("personBean.firstName", "First name is required.")
將會在表單上的firstName字段上面顯示"First name is required."
?
運行
?
添加css
Struts2 的<s:head/>標簽可用于對錯誤消息添加CSS,這個標簽要放在HTML的<head>標簽中,重新運行:
?
總結
本教程通過向Action類添加驗證方法來驗證用戶的表單輸入。還有一種更復雜的方法可以使用XML驗證用戶輸入。如果您想了解關于在Struts 2中使用XML進行驗證的更多信息,請參閱驗證Validation
在我們的下一個教程中,我們將使用消息資源文件將文本從視圖頁面中分離出來。