Struts page Flow Form Verification

Source: Internet
Author: User

Verifying user input in HTML forms is the most common problem during web application creation. User input data must be verified to ensure that the data is correct before business processing. The input form data may be used to create or update database entries, call Web Services, or as input to the business process. Based on the form verification framework provided by struts, page stream provides a simple and easy-to-use server-side verification method.
Page flow verification provides the following functions:
· Server verification for user form input
· Encapsulate the verification logic with the form bean to be verified
· Automatically navigate to the input page when verification fails
· Built-in message package support for internationalization
This document assumes that the reader is familiar with the page stream and JSP. This article describes the basic steps for creating a form bean and verifying the page. If a verification error occurs, the user will be notified to correct them. When the action method is called, the data can be considered correct.

Request lifecycle and Verification
Form Verification targets the content in the submitted Form bean. The bean is indirectly selected through the action attribute of the <netui: Form> tag on the JSP page. The form bean is associated with the specified action. Form bean inherits from Com. Bea. wlw. netui. pageflow. formdata. To verify form beans, developers need to reload the validate () method and provide verification logic.
Figure 1 demonstrates the request lifecycle and how verification occurs. When the strut controller receives the request, it passes the request to the page stream requestprocessor. The processpopulate method of the request processor first constructs a new form bean containing all data entries from the request. In this step, formdata is created. Request the processor to check whether form verification is activated for the action. If the verification is activated, the validate () method is called for the form bean. In the event of a verification error, the control will be handed over to an input page, along with the user-input data and error information. If no error is found, the control is passed to the target action to continue processing the request.
The verification can be performed in the page stream in five simple steps. Each step is described in detail below.
Step 1 -- Verification Method
The first step to verify user input is to create the validate () method on the form bean. This method checks the bean attributes of the form to see if user input is incorrect. The following simple form bean defines two attributes: name and type. The Validate () method provides validation of these attributes.
Public static class namebean extends formdata
{
Private string name;
Private string type;
Public void settype (string type)
{
This. type = type;
}
Public String GetType ()
{
Return this. type;
}
Public void setname (string name)
{
This. Name = Name;
}
Public String getname ()
{
Return this. Name;
}
Public actionerrors validate (actionmapping mapping, httpservletrequest request)
{
Actionerrorserrors = new actionerrors ();
If (name = NULL | Name. Equals ("")){
Errors. Add ("nameerror ",
New actionerror ("nullnameerror "));
} Else {
If (! Character. isuppercase (name. charat (0 ))){
Errors. Add ("nameerror ",
New actionerror ("uppercasenameerror", name ));
}
}
If (type = NULL | (! Type. Equals ("bar ")&&! Type. Equals ("foo "))){
Errors. Add ("typeerror ",
New actionerror ("typeerror", type ));
}
If (! Errors. Empty ()){
Request. setattribute ("errornotset", new Boolean (false ));
}
Return errors;
}
The Validate () method returns the struts actionerrors object, which contains any possible error information. When this method is called, it receives the struts actionmapping structure and httpservletrequest. If an internal method error occurs, the struts actionerror class will capture the error message.

The first thing the validate () method does is to create an actionerrors object to return verification errors.
Actionerrors errors = new actionerrors ();
If a non-empty actionerrors object is returned, this method notifies the request processor of the error. If no actionerror is added, actionerrors is empty. This method may return NULL actionerrors or null to indicate that no error occurs.
In this example, if an error occurs, a new actionerror object will be created and added to actionerrors:
Errors. Add ("typeerror", new actionerror ("typeerror", type ));
In this example, we will create a new error containing the attribute "typeerror. <Netui: Error> the label uses a name to determine which error should be reported. The newly created actionerror contains a primary key "typeerror ". The primary key is the ID used to find the error display information in the message package. In addition, we will also pass the variable type to replace the text when the information is created.
Step 2 -- enable verification in action
The Validate () method can be called only when the verification function is enabled for the action. You can enable the verification function by adding a validation-error-page attribute to @ JFP: Action annotation:
/**
* @ Jpf: Action Validation-error-page = "index. jsp"
* @ Jpf: Forward name = "success" Path = "results. jsp"
*/
Protected forward processnamebean (namebean form)
{
Httpservletrequest Req = getrequest ();
Req. setattribute ("form", form );
Return new forward ("success ");}
Annotations can be defined manually or in the attribute editing window of the source code view of the action.

Step 3 -- create error message text
The error message text is found from the message package. The message package is placed under the WEB-INF/classes subdirectory. In this example, we create the validation. properties file and place it in the WEB-INF/classes/message directory
Validation. properties contains the text that will be displayed in the <netui: Error> or <netui: errors> label. This property file contains the following entries:
Rrors. header = <ul>
Errors. footer = </u>
Errors. prefix = <li>
Errors. suffix </LI>
Nullnameerror = The Name field must not be null.
Uppercasenameerror = the name <B> '{0}' </B> must begin
With an upper case letter.
Typeerror = the type <B> '{0}' </B> must be the value 'foo' or 'bar'

In the example, we create an actionerror using the following statement:
Actionerror ("typeerror", type ));
The string "typeerror" is used for message search:
Typeerror = the type <B> '{0}' </B> must be the value 'foo' or 'bar'
At runtime, replace type with '{0}' to generate the complete text of the Report to the user.
 
Step 4: bind the message file to the page stream
The message File validation. properties needs to be bound to the page stream so that the message can be searched before the message is reported to the user. You can bind a page stream annotation.
/* @ Jpf: Controller
* @ Jpf: Message-resources Resources = "messages. validation"
*/
Public class controller extends pageflowcontroller
{
@ Jpf: the message-resources annotation declares that the page stream uses the messages. Validation attribute file. You can set this annotation directly in the source code or in the message resource list area under the stream attribute editing window in the source code view page.
The message Resource Name Is the classpath entry used to find a message package. In this example, messages. validation can be found because the WEB-INF/classes is in classpath. Its actual file name is WEB-INF/classes/message/validation. properties.

Note: Java caches the accessed message packets. If the. properties file is modified during development, you can clear the cache by modifying the page stream file, restarting the test browser, or stopping and restarting the service.
 
Step 5 -- report errors on the JSP page

There are two page flow labels used to report errors during verification. <Netui: Error> the label reports Errors Based on the value attribute. It is usually used after an input field to directly report the error of this field. The <netui: errors> label reports all errors on the page. The following JSP code snippet demonstrates a <netui: Form> example, which submits the namebean form bean. It uses the <netui: Error> label to report errors after a field is entered by the user. In addition, other errors are reported at the bottom of the document using the <netui: errors> label.
<H4> name input form </H4>
<Netui: Form Action = "processnamebean" Focus = "">
<Table>
<Tr>
<TD> <netui: Label value = "name:">
</Netui: Label> </TD>
<TD> <netui: textbox datasource = "{actionform. name}">
</Netui: textbox> </TD>
<TD> <span style = "color: # cc0000;">
<Netui: error value = "nameerror"/> </span> </TD>
</Tr>
<Tr>
<TD> <netui: Label value = "type:"/> </TD>
<TD> <netui: textbox datasource = "{actionform. Type}"/> </TD>
<TD> <span style = "color: # cc0000;">
<Netui: error value = "typeerror"/> </span> </TD>
</Tr>
</Table>
<Netui: button value = "Submit Form"> </netui: button>
</Netui: Form>
<Netui-template: visible visibility = "{request. errornotset }"
Negate = "true">
<HR/>
<Span style = "color: # cc0000;">
<Netui: errors> <br/> </netui: errors>
</Span>
</Netui-template: visible>
<Netui: errors> the tag has four special attributes that can be defined in the message package: errors. header, errors. footer, errors. prefix, errors. suffi, which can be used to set the format around the displayed message. In this example, errors are displayed in an unordered list. In addition, the <netui: Error> label allows error. prefix and error. suffix to define tags for memory. This function is not demonstrated in this example.

Result
If the user inputs invalid data in the form, the verification error is returned, and the request processor directs to the index. jsp page. The error information is displayed after the field and below the form. All the content of the error form is returned, so that you can modify only the error fields.

Conclusion
 
It takes five steps to verify the user input on the server. First, create a validate () method in form bean. This method verifies user input and reports an error. Step 2: You must set the validation-error-page symbol on the form receiving action to activate form verification. Step 3: add the error text to the Message package. Step 4: Use the message resource annotation to bind the message package to the page stream. Finally, add the <netui: Error> or <netui: errors> labels in JSP to display the error text. The page Flow Framework manages all verification calls and routes control to the input page when an error occurs. Otherwise, the system routes the control to the target action.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.