Validation framework verification data

Source: Internet
Author: User

In struts2 tutorial 4: using the validate method to verify data submitted by the client, however, if the validate method is used, the verification code will be mixed with the normal logic code, but this is not conducive to code maintenance, and it is difficult to use some code for verification by other programs. In struts2, a validation framework is provided for us. This framework is similar to the validation framework provided by struts1.x and is also configured through XML files.

1. Server Verification

The following example shows how to use the validation framework of struts2 for server verification. We can write this program in the following four steps:

[Step 2] create an action class (newvalidateaction. Java)

Packageaction;

Importcom. opensymphony. xwork2.actionsupport;
Publicclassnewvalidateactionextendsactionsupport
{
Privatestringmsg; // required
Privateintage; // The value ranges from 13 to 20.
Publicstringgetmsg ()
{
Returnmsg;
}
Publicvoidsetmsg (stringmsg)
{
This. MSG = MSG;
}
Publicintgetage ()
{
Returnage;
}
Publicvoidsetage (intage)
{
This. Age = age;
}
}

Next we will verify the MSG and age attributes.

Step 2: configure the action class. The Struts. XML Code is as follows:

<? Xmlversion = "1.0" encoding = "UTF-8"?>
<! Doctypestrutspublic
"-// Apachesoftwarefoundation // dtdstrutsconfiguration2.0 // en"
Http://struts.apache.org/dtds/struts-2.0.dtd>
<Struts>
<Packagename = "Demo" extends = "struts-Default" namespace = "/test">
<Actionname = "new_validate" class = "Action. newvalidateaction">
<Resultname = "input">/validate_form.jsp </result>
<Resultname = "success">/validate_form.jsp </result>
</Action>
</Package>
</Struts>

[Step 2] compile the verification Rule Configuration File

This is an XML-based configuration file, similar to the validation rule configuration file of the validator framework in struts1.x. But it is usually put in the same directory as the. Class file to be verified, and the configuration file name should be named using one of the following two rules:

<Actionclassname>-validation. xml
  
<Actionclassname>-<actionaliasname>-validation. xml

<Actionaliasname> is the name attribute value of <ation> In struts. xml. In this example we use the first naming rule, so the file name is a NewValidateAction-validation.xml. The file content is as follows:

<? Xmlversion = "1.0" encoding = "UTF-8"?>
<! Doctypevalidatorspublic "-// opensymphonygroup // xworkvalidator1.0.2 // en"
Http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd>
<Validators>
<Fieldname = "MSG">
<Field-validatortype = "requiredstring">
<Message> enter the information. </message>
</Field-validator>
</Field>
<Fieldname = "Age">
<Field-validatortype = "int">
<Paramname = "min"> 13 </param>
<Paramname = "Max"> 20 </param>
<Message>
Must be between 13 and 20
</Message>
</Field-validator>
</Field>
</Validators>

This file uses two rules: requiredstring (required) and INT (to determine the Integer Range ). For more detailed verification rules, visit http://struts.apache.org/2.0.11.1/docs/validation.html.

Step 2: compile the data entry JSP page.

Create a validate_form.jsp file in the web root directory. The Code is as follows:

<% @ Pagelanguage = "Java" Import = "Java. util. *" pageencoding = "GBK" %>
<% @ Taglibprefix = "S" uri = "/Struts-tags" %>
<Linkrel = "stylesheet" type = "text/CSS" href = "<s: urlvalue ="/styles/styles.css "/>">
<HTML>
<Head>
<Title> verification data </title>
</Head>
<Body>
<S: formaction = "new_validate" namespace = "/test">
<S: textfieldname = "MSG" label = "name"/>
<S: textfieldname = "Age" label = "Age"/>
<S: Submit/>
</S: Form>
</Body>
</Html>

Note that if you specify the namespace attribute in the <package> tag of Struts. XML, you must separate the namespace and action in <s: Form>, as shown in the code above. Cannot be connected together. struts2 must separate the action and namespace. The following code is incorrect:

<S: Form Action = "/test/new_validate">
  
......
  
</S: Form>

Styles.css is also used in other programs to customize the style of error messages. The Code is as follows:

. Label {font-style: italic ;}
  
. Errorlabel {font-style: italic; color: red ;}
  
. Errormessage {font-weight: bold; color: red ;}

Create a styles In the webroot directory, and set styles.css

If the context path of the web project is validation, you can use the following URL to test the program:

Http: // localhost: 8080/validation/validate_form.jsp

The result 1 is displayed.

{
Get_larger (this)
} "Src =" http://img.ddvip.com/2009_01_16/1232099034_ddvip_8645.jpg "alt =" struts2 tutorial 5: Validate data using the validation framework ">

Figure 1

Ii. Client Verification

In struts2, client verification is very simple. You only need to add a validate attribute in <s: Form> and the value is true. For example, <s: Form validate = "true" ...... </form>.

Iii. Verify nested attributes

There is a special attribute, that is, the type of this attribute is another JavaBean. If there is a user class, the Code is as follows:

Packagedata;

publicclassUser
{
  privateStringname;
  privateintage;
  publicStringgetName()
  {
    returnname;
  }
  publicvoidsetName(Stringname)
  {
    this.name=name;
  }
  publicintgetAge()
  {
    returnage;
  }
  publicvoidsetAge(intage)
  {
    this.age=age;
  }
}

Add a user attribute to the newvalidateaction class. The Code is as follows:

Packageaction;

importcom.opensymphony.xwork2.ActionSupport;
importdata.User;
publicclassNewValidateActionextendsActionSupport
{
  privateStringmsg;
  privateintage;
  privateUseruser;
  publicStringgetMsg()
  {
    returnmsg;
  }
  publicvoidsetMsg(Stringmsg)
  {
    this.msg=msg;
  }
  publicintgetAge()
  {
    returnage;
  }
  publicvoidsetAge(intage)
  {
    this.age=age;
  }
  publicUsergetUser()
  {
    returnuser;
  }
  
  publicvoidsetUser(Useruser)
  {
    this.user=user;
  }
}

To verify the user attribute in newvalidateaction, you can use the visitor validator. The procedure is as follows:

First add a <field> label to the NewValidateAction-validation.xml, the Code is as follows:

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEvalidatorsPUBLIC"-//OpenSymphonyGroup//XWorkValidator1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
  ……
  
  <fieldname="user">
  <field-validatortype="visitor">
      <paramname="context">abc</param>
      <paramname="appendPrefix">true</param>
      <message>User:</message>
    </field-validator>
  </field>
</validators>

The context parameter serves as part of the file name that validates the user class property. If the user property returns a user object, the file name used to validate the user object property is the User-abc-validation.xml. This file must be in the same directory as the user. Class file. Appendprefix indicates whether to add a user to the field. If it is set to true, struts2 uses user. Name to search for the data to be verified in the data submitted by form. The default value of this attribute is true. If an error occurs, struts2 adds the information in the <message> label to the corresponding error information in the User-abc-validation.xml file.

The User-abc-validation.xml file is as follows:

<? Xmlversion = "1.0" encoding = "UTF-8"?>

<! Doctypevalidatorspublic "-// opensymphonygroup // xworkvalidator1.0.2 // en"
Http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd>
<Validators>
<Fieldname = "name">
<Field-validatortype = "requiredstring">
<Message> enter name </message>
</Field-validator>
</Field>
<Fieldname = "Age">
<Field-validatortype = "int">
<Paramname = "min"> 5 </param>
<Paramname = "Max"> 20 </param>
<Message>
Must be between 5 and 20
</Message>
</Field-validator>
</Field>
</Validators>

Modify validate_form.jsp as follows:

<S: formvalidate = "true" Action = "new_validate" namespace = "/test">
<S: textfieldname = "MSG" label = "name"/>
<S: textfieldname = "Age" label = "Age"/>
<S: textfieldname = "user. Name" label = "name 1"/>
<S: textfieldname = "user. Age" label = "age 1"/>
<S: Submit/>
</S: Form>

As you can see, the name attributes of the last two <s: textfield> are user. Name and user. Age, which are prefixed.

Access http: // localhost: 8080/validation/validate_form.jsp again, as shown in verification page 2.

{
Get_larger (this)
} "Src =" http://img.ddvip.com/2009_01_16/1232099035_ddvip_9546.jpg "alt =" struts2 tutorial 5: Validate data using the validation framework ">

Figure 2

According to the test, visitor cannot be used to verify the user attribute by the client, but other attributes in newvalidateaction can be tested by the client.

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.