Struts2 官方教程之Form Validation(十二)

来源:互联网 发布:电脑怎么选看淘宝直播 编辑:程序博客网 时间:2024/06/05 14:21
This tutorial assumes you've completed the Processing Forms tutorial and have a working Form_Processing_Struts2_Ant (or Form_Processing_Struts2_Mvn) project. The example code for this tutorial, Form_Validation_Struts2_Ant or Form_Validation_Struts2_Mvn, is available on Google Code - http://code.google.com/p/struts2-examples/downloads/list. After downloading and unzipping the file, you'll have a folder named Form_Validation_Struts2_Ant (or Form_Validation_Struts2_Mvn). In that folder will be a README.txt file with instructions on now to build and run the example application.

Introduction

In this tutorial we'll explore using Struts 2 to validate the user's input on a form. There are two ways you can use Struts 2 to do form validation. This tutorial will cover the more basic method, where the validation is included in the Struts 2 Action class.

在这个示例中,我们将会使用表单验证,有两种方式进行验证。

The code provided in this tutorial may be added to the Processing Forms example or you can download this complete example from Google Code -http://code.google.com/p/struts2-examples/downloads/list.

示例请从上面链接下载

The Struts 2 user mailing list is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.

Add validate Method

To enable the Struts 2 Action class to validate a user's input on a Struts 2 form, you must define a validate method in your Action class. Using the example fromProcessing Forms tutorial, let's say that we have these business rules:

为了使在action类进行表单验证,你必须在action类中定义验证方法,使用下面的步骤。

1. User must provide a first name
2. User must provide an email address
3. User younger then 18 cannot register

用户必须提供名字,邮件地址,18岁以下不能注册。

If you recall from the Processing Forms tutorial the user's input into the form fields is placed by Struts 2 into the Java model class personBean. So a user's input into the firstName field would end up as the value for personBean's firstName instance field (via the personBean.setFirstName method).

In the validate method we can refer to get the values of personBean's instance fields by using the appropriate get methods. Once we have the values we can employ logic to enforce our business rules.

Add the following validate method to Register.java (the Action class).

Actionsupport这个工具类在实现了Action接口的基础上还定义了一个validate()方法,重写该方法,它会在execute()方法之前执行,如校验失败,会转入input处,必须在配置该Action时配置input属性。重写validate方法,该方法会在执行系统的execute方法之前执行,如果执行该方法之后,Action类的fieldErrors中已经包含了数据校验错误,请求将被转发到input逻辑视图处。

validate methodpublic 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" );}}


 

When the user presses the submit button on the register form, Struts 2 will transfer the user's input to the personBean's instance fields. Then Struts 2 will automatically execute the validate method. If any of the if statements are true, Struts 2 will call its addFieldError method (which our Action class inherited by extending ActionSupport).

If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return "input" as the result of calling the action.

当用户点击提交,struts2将会把数据提交到model属性中,struts2将会自动执行验证方法。

Handle Input Being Returned

So what should we do if Struts 2 returns "input" indicating that the user's input in the form is not valid? In most cases we will want to redisplay the web page that has the form and include in the form error messages to inform the user what is wrong.

如果struts2返回"input"我们应该做什么,这表示用户的无效?在大多数例子中,我们将把错误信息显示在表单的页面上。

To handle the return value of "input" we need to add the following result to our action node in struts.xml.

<result name="input">/register.jsp</result>

 

The above result node goes just after the success result node for the register action and before the closing of the action node.

Error Messages

So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp. Since we used Struts 2 form tags, automatically Struts 2 will add the error messages. These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first is the form field name to which the error applies and the second is the error message to display above that form field.

当验证失败,struts2返回input,struts2会再次显示register.jsp,因为我们使用的是struts2标签,会自动把我们定义的错误信息加进去。

So the following addFieldError method call:

addFieldError( "personBean.firstName", "First name is required.")


 

will cause the message "First name is required" to be displayed above the firstName field on the form.

If you have made the above changes to the Processing Forms tutorial or you have downloaded fromGoogle Code either the Form_Validation_Struts2_Ant or Form_Validation_Struts2_Mvn projects run the application (see the README.txt in the project root folder). Click on the Please register link. On the registration form, just click the submit button and you should see:

 

Struts 2 called the validate method, validation failed, the register.jsp was displayed with the error messages.

Styling The Error Messages

The Struts 2 s:head tag can be used to provide CSS that includes a style for the error message. Add<s:head /> to register.jsp before the closing HTML</head> tag. Go through the same steps as above and you should see:

看到这里也许读者觉得非常神奇:我们仅仅在Action添加了数据校验错误,并未在输入页面输出这些校验错误信息,但图2.13所示的页面,却可以看到页面已经输出了这些校验信息——这是因为Struts 2的标签,上面的JSP页面中表单使用的并不是HTML表单,而是用了<s:form .../>标签,Struts 2的<s:form ... />标签已经具备了输出校验错误的能力。

 提示  Struts 2的<s:form .../>默认已经提供了输出校验错误的能力。

 

Summary

This tutorial covered validating a user's form input by adding a validate method to an Action class. There is another more sophisticated way to validate user input using XML. If you want to learn more about using XML for validation in Struts 2 seeValidation.

Up Next

In our next tutorial we'll cover how to use message resource files to separate out the text from the view page.