在webwork中通过validation校验框架可以轻松完成相关的表单校验,下面是相关的应用:
一、login.jsp
<ww:form method="post">
<ww:textfield label="Name" name="name"/>
<ww:textfield label="Password" name="password"/>
<ww:submit/>
</ww:form> |
二、LoginAction.java
1package org.register;
2
3import com.opensymphony.xwork.Action;
4public class LoginAction extends Action {
5 String name;
6 int password;
7
8
9 public String getName() {
10 return name;
11 }
12
13 public void setName(String name) {
14 this.name = name;
15 }
16
17 public int getPassword() {
18 return password;
19 }
20
21 public void setPassword(int password) {
22 this.password = password;
23 }
24 public String execute() throws Exception {
25 if(user.getName().equals("apple0668")&&user.getPassword().equals("apple0668"))
26 {
27 return SUCCESS;
28 }
29 else
30 {
31 return ERROR;
32 }
33
34 }
35
36
37} |
三、填写要使用的校验器.validation.xml的格式是 <ActionClassName>-validation.xml
LoginAction-validation.xml
1<validators>
2 <field name="name">
3 <field-validator type="requiredstring">
4 <message>You must enter a name</message>
5 </field-validator>
6 </field>
7 <field name="password">
8 <field-validator type="stringlength">
9 <param name="trim">true</param>
10 <param name="min">5</param>
11 <param name="max">10</param>
12 <message>trim-min5-max10</message>
13 </field-validator>
14 </field>
15</validators>
16 |
其他xwork.xml,web.xml webwork.properties配置省略。通过几步就可以顺利完成对表单输入校验。
还有其他校验:
1、日期校验:
1 <validators>
2 <!-- Plain Validator syntax -->
3 <validator type="date">
4 <param name="fieldName">birthday</param>
5 <param name="min">01/01/1990</param>
6 <param name="max">01/01/2000</param>
7 <message>Birthday must be within ${min} and ${max}</message>
8 </validator>
9
10 <!-- Field Validator Syntax -->
11 <field name="birthday">
12 <field-validator type="date">
13 <param name="min">01/01/1990</param>
14 <param name="max">01/01/2000</param>
15 <message>Birthday must be within ${min} and ${max}</message>
16 </field>
17 </field>
18
19</validators> |
2、邮件格式校验:
1 <validators>
2 <validator type="email">
3 <param name="fieldName">myEmail</param>
4 <message>Must provide a valid email</message>
5 </validator>
6 </validators>
7
8<!-- Field Validator Syntax -->
9<field name="myEmail">
10 <field-validator type="email">
11 <message>Must provide a valid email</message>
12 </field-validator>
13</field> |