一、前言
1.1、什么是輸入驗(yàn)證?為什么需要輸入驗(yàn)證?
在上一篇文章中,我們學(xué)習(xí)了數(shù)據(jù)類型轉(zhuǎn)換,我們提到了表示層數(shù)據(jù)處理的兩個(gè)方法,也提到了用戶輸入數(shù)據(jù)需要進(jìn)行類型轉(zhuǎn)換才能得到我們想要的數(shù)據(jù),那么,我們?cè)趺创_定類型轉(zhuǎn)換后的數(shù)據(jù),是我們想要的數(shù)據(jù)呢?這里有點(diǎn)繞。你可以這樣想:一個(gè)成年男子年齡是18歲,你現(xiàn)在想要得到18這個(gè)數(shù)據(jù),但是,用戶輸入32,經(jīng)過類型轉(zhuǎn)換也是對(duì)的,但是數(shù)據(jù)不是你想要的。這時(shí)候,我們要怎么辦?所以輸入驗(yàn)證在這里就有用處了。
類型轉(zhuǎn)換和輸入驗(yàn)證的關(guān)系是:類型轉(zhuǎn)換是輸入驗(yàn)證的前提,如果類型轉(zhuǎn)換都出錯(cuò)了,那就不用再進(jìn)行輸入驗(yàn)證了。但是很多時(shí)候類型轉(zhuǎn)換和輸入驗(yàn)證是同時(shí)完成的。
輸入驗(yàn)證有兩種:
1、客戶端驗(yàn)證;
2、服務(wù)端驗(yàn)證。這里主要講解的是服務(wù)端驗(yàn)證(重寫ValidateXxx方法和xml配置文件驗(yàn)證)
1.2、重寫ValidateXxx方法的驗(yàn)證流程
1、類型轉(zhuǎn)換器負(fù)責(zé)對(duì)字符串的請(qǐng)求參數(shù)進(jìn)行類型轉(zhuǎn)換,并將這些值設(shè)置成Action的屬性值
2、在執(zhí)行類型轉(zhuǎn)換過程中可能出現(xiàn)異常,如果出現(xiàn)異常,異常信息會(huì)自動(dòng)保存到ActionContext中,conversionError攔截器負(fù)責(zé)將其封裝到fieldError中
3、通過反射調(diào)用ValidateXxx()方法,其中Xxx是即將處理用戶請(qǐng)求的處理邏輯所對(duì)應(yīng)的方法名
4、調(diào)用Action類的Validate方法
5、如果上面的步驟沒有出現(xiàn)fieldError,將調(diào)用Action里處理用戶請(qǐng)求的處理方法,如果出現(xiàn)fieldError,系統(tǒng)將轉(zhuǎn)入input邏輯視圖所指定的視圖。
二、輸入驗(yàn)證
2.1、輸入驗(yàn)證這里講解的有兩種方式:
1、重寫Validate方法或者自定義ValidateXxx方法(其中的Xxx是自己定義的名字,會(huì)先執(zhí)行該方法,在執(zhí)行Validate方法)
2、新建xml進(jìn)行驗(yàn)證
2.2、重寫Validate方法
在MVC框架,都會(huì)提供規(guī)范的數(shù)據(jù)驗(yàn)證部分,Struts2在這里提供的是一個(gè)Validate方法,我們重寫Validate方法就可以進(jìn)行輸入驗(yàn)證,但是,重寫Validate方法有兩個(gè)點(diǎn)需要知道:1、Validate方法會(huì)在execute方法之前被執(zhí)行;2、Validate方法對(duì)所有的Action都會(huì)執(zhí)行校驗(yàn)規(guī)則,為了區(qū)別某一個(gè)Action,我們可以使用ValidateXxx方法。
注意:以下的例子是局部類型轉(zhuǎn)換和輸入驗(yàn)證一起使用的例子。
簡(jiǎn)單的注冊(cè)驗(yàn)證例子:
新建實(shí)體類User:
User
新建視圖:Register.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <%@ taglib uri= "/struts-tags" prefix= "s" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>注冊(cè)用戶</title> </head> <body> <h2>使用validateXXX()方法驗(yàn)證</h2> <form action= "register_test" > 用戶:<input type= "text" name= "user" ><br/> 密碼:<input type= "password" name= "user" ><br/> 密碼:<input type= "password" name= "user" ><br/> <input type= "submit" value= "提交" > </form> </body> </html> |
新建RegisterAction類繼承ActionSupport
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
38
39
|
package com.validatexxx; import com.opensymphony.xwork2.ActionSupport; //重寫validate()和validateXXX指定方法進(jìn)行驗(yàn)證 /* * 在struts.xml配置method方法為test(),會(huì)先調(diào)用ValidateTest()方法, * 然后在調(diào)用validate方法 * 之后test方法被調(diào)用 * */ public class RegisterAction extends ActionSupport { private User user; public User getUser() { return user; } public void setUser(User user) { this .user = user; } //2 @Override public void validate(){ System.out.println( "重寫Validate方法" ); if ( null == user.getPassword() || "" .equals(user.getPassword()) || null == user.getRepassword() || "" .equals(user.getRepassword())) { this .addFieldError( "repassword" , "repassword should be same password" ); return ; } if (!user.getPassword().equals(user.getRepassword())) { //當(dāng)FieldError中存在數(shù)據(jù)時(shí),服務(wù)器會(huì)自動(dòng)幫我們跳轉(zhuǎn)到input的邏輯視圖 this .addFieldError( "repassword" , "repassword should be same password" ); } } //1 public void validateTest(){ System.out.println( "自定義校驗(yàn)方法:ValidateTest" ); } //3 public String test(){ System.out.println( "test:方法" ); return SUCCESS; } } |
注意:這里的屬性是User,所以你jsp頁面參數(shù)的名字要寫實(shí)例的名字user,然后你還需要去創(chuàng)建一個(gè)類型轉(zhuǎn)換器,返回一個(gè)填充好數(shù)據(jù)的類
新建struts.xml,存放在WEB-INF/classes/struts.xml
注意:這里的method必須是你ValudateXxx()方法后面你自己定義的,筆者這里是test。使用*的話,struts2還必須配置 strict-method-invocation="false",據(jù)說是因?yàn)榘姹咎吡耍陌踩栽黾恿耍斜仨毤硬拍軌蚴褂?
新建Usertypeconverter類繼承StrutsTypeConverter(創(chuàng)建一個(gè)類型轉(zhuǎn)換器)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.validatexxx; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; //類型轉(zhuǎn)換的類 public class Usertypeconverter extends StrutsTypeConverter { @Override public Object convertFromString(Map arg0, String[] arg1, Class arg2) { System.out.println( "Usertypeconverter:類型轉(zhuǎn)換!" ); User user = new User(); user.setUsername(arg1[ 0 ]); user.setPassword(arg1[ 1 ]); user.setRepassword(arg1[ 2 ]); return user; } @Override public String convertToString(Map arg0, Object arg1) { User u = (User)arg1; return u.getUsername()+ "!" ; } } |
注意:該類型轉(zhuǎn)換器創(chuàng)建好之后還需新建一個(gè)RegisterAction-conversion.properties,放在同級(jí)目錄下
該文件的內(nèi)容有:
前面是你在RegisterAction的屬性名,后面是類型轉(zhuǎn)換器的具體路徑。
新建成功視圖:success.jsp
success.jsp
新建錯(cuò)誤視圖:input.jsp
input.jsp
代碼執(zhí)行成功的效果如下:
Register.jsp頁面
成功跳轉(zhuǎn)的頁面為:success.jsp
控制臺(tái)測(cè)試結(jié)果為:
數(shù)據(jù)跳轉(zhuǎn)到Usertypeconverter進(jìn)行類型轉(zhuǎn)換,之后跳轉(zhuǎn)到RegisterAction,執(zhí)行ValidateTest方法(),Validate,test之后返回SUCCESS,然后執(zhí)行result的視圖。
我們看代碼執(zhí)行失敗的順序:
Register.jsp頁面
input.jsp頁面
控制臺(tái)測(cè)試效果:
在Validate方法里面,筆者代碼為:this.addFieldError(),在前面有說過,如果添加錯(cuò)誤的話,那么服務(wù)器會(huì)自動(dòng)幫我們跳轉(zhuǎn)到錯(cuò)誤的界面。它會(huì)返回input,而input在struts.xml中就有配置,會(huì)返回到input.jsp界面。
2.3、新建xml進(jìn)行輸入驗(yàn)證
新建視圖界面:Test.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" %> <%@ taglib uri= "/struts-tags" prefix= "s" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <title>使用XML校驗(yàn)</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> |
新建Employee類繼承ActionSupport
該類有使用重寫Validate方法和Xml配置,我們可以選擇其中一種進(jìn)行驗(yàn)證就可以
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
38
39
40
|
package com.validatexxx; import com.opensymphony.xwork2.ActionSupport; //使用validate()方法驗(yàn)證,這是服務(wù)端驗(yàn)證! public class Employee extends ActionSupport { private String name; private int age; public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } //第二步再執(zhí)行該方法 public String execute(){ System.out.println( "execute:" + this .age); return SUCCESS; } /* 使用服務(wù)端的校驗(yàn):重寫validate方法(); //第一步先執(zhí)行該方法 //重寫validate方法有缺陷:每次都會(huì)使用validate方法驗(yàn)證,造成極大的資源浪費(fèi)。 public void validate(){ System.out.println("validate"); if (name == null || name.trim().equals("")) { //當(dāng)往該方法添加數(shù)據(jù)的時(shí)候,服務(wù)器會(huì)返回input,之后跳轉(zhuǎn)到input.jsp頁面中。 addFieldError("name","The name is required"); } if (age < 28 || age > 65) { addFieldError("age","Age must be in between 28 and 65"); } } */ } |
在Struts.xml中進(jìn)行配置:
這里的success.jsp和input.jsp還是使用上面的。
之后我們需要新建Employee-validation.xml,路徑放在與Employee同級(jí)目錄下,注意:-validation.xml是固定不變的
內(nèi)容為:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?xml version= "1.0" encoding= "UTF-8" ?> <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd" > <validators> <field name= "name" > <field-validator type= "required" > <message> The name is required. </message> </field-validator> </field> <field name= "age" > <field-validator type= "int" > <param name= "min" > 29 </param> <param name= "max" > 64 </param> <message> Age must be in between 28 and 65 </message> </field-validator> </field> </validators> |
重點(diǎn):該文件的dtd限制必須有,不然回報(bào)錯(cuò)誤:
ERROR DefaultDispatcherErrorHandler Exception occurred during processing request: [Connection timed out: connect - [unknown location], null]
接下來我們使用http://localhost:8080/LearStruts2/ValidateJSP/Test.jsp進(jìn)行訪問。
測(cè)試成功:
Test.jsp界面:
success.jsp
測(cè)試失敗例子:
input.jsp界面:
說明例子是正確的。
其實(shí)在Struts2中有多個(gè)內(nèi)置驗(yàn)證器:必填驗(yàn)證器,必填字符串驗(yàn)證器,整數(shù)驗(yàn)證器,日期驗(yàn)證器,表達(dá)式驗(yàn)證器,字符長(zhǎng)度驗(yàn)證器,正則表達(dá)式驗(yàn)證器...等等,這個(gè)有需要的話,筆者在一一述說。
以上所述是小編給大家介紹的Struts2數(shù)據(jù)輸入驗(yàn)證教程詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/yingzi1028/p/5976774.html