Validation under struts

Source: Internet
Author: User
Use validator for server-side verification in struts

Author: Unknown Article Source: Reprinted clicks: 183 updated on:

This example uses the built-in struts1.2.4 to help you learn. The directory structure of the example and all the files used can be downloaded from this site.
1. Form bean and JSP page
First look at the form on the JSP page. The content includes the name, address, Province (city), county, zip code, phone number, and email.
Below is form bean, which is named registrationform in the struts-config.xml. Be sure to inherit validatorform. Pay attention to the citystatezip attribute, which is used to store the three items: province (city), county, and zip code.
Package org. Apache. Struts. webapp. validator;
Import java. Io. serializable;
Import javax. servlet. http. httpservletrequest;
Import org. Apache. Struts. Action. actionmapping;
Import org. Apache. Struts. validator. validatorform;

Public final class registrationform extends validatorform implements serializable {
Private string action = NULL;

Private string sfirstname = NULL;
Private string slastname = NULL;
Private string saddr = NULL;
Private citystatezip CSZ = new citystatezip ();
Private string sphone = NULL;
Private string semail = NULL;
Public String getaction (){
Return Action;
}
Public void setaction (string action ){
This. Action = action;
}

Public String getfirstname (){
Return sfirstname;
}

Public void setfirstname (string sfirstname ){
This. sfirstname = sfirstname;
}

Public String getlastname (){
Return slastname;
}

Public void setlastname (string slastname ){
This. slastname = slastname;
}

Public String getaddr (){
Return saddr;
}

Public void setaddr (string saddr ){
This. saddr = saddr;
}

Public citystatezip getcitystatezip (){
Return CSZ;
}

Public void setcitystatezip (citystatezip CSZ ){
This. csz = CSZ;
}

Public String getphone (){
Return sphone;
}

Public void setphone (string sphone ){
This. sphone = sphone;
}

Public String getemail (){
Return semail;
}

Public void setemail (string semail ){
This. semail = semail;
}


Public void reset (actionmapping mapping, httpservletrequest request ){
Action = NULL;
Sfirstname = NULL;
Slastname = NULL;
Saddr = NULL;
CSZ = new citystatezip ();
Sphone = NULL;
Semail = NULL;
}

}

This is the source code of citystatezip. It corresponds to the province (city), county, and zip code. You can see the following JSP page: the zip code is stored in the second item of the string array szippostal, the other two items are null.

Package org. Apache. Struts. webapp. validator;

Public class citystatezip implements java. Io. serializable {

Private string scity = NULL;
Private string sstateprov = NULL;
Private string [] szippostal = new string [3];

Public String getcity (){
Return scity;
}

Public void setcity (string scity ){
This. scity = scity;
}

Public String getstateprov (){
Return sstateprov;
}

Public void setstateprov (string sstateprov ){
This. sstateprov = sstateprov;
}

Public String getzippostal (INT index ){
Return szippostal [Index];
}

Public void setzippostal (INT index, string value ){
This. szippostal [Index] = value;
}

}

This is the form-included registration. jsp,

<% @ Page contenttype = "text/html; charset = GBK" %>
<% @ Taglib uri = "/tags/Struts-bean" prefix = "Bean" %>
<% @ Taglib uri = "/tags/Struts-html" prefix = "html" %>
<% @ Taglib uri = "/tags/Struts-logic" prefix = "logic" %>

<HTML: HTML>
<Head>
<Title> <Bean: Message key = "registrationform. Title"/> </title>
<HTML: base/>
</Head>
<Body bgcolor = "white">

<Logic: messagespresent>
<Bean: Message key = "errors. Header"/>
<Ul>
<HTML: messages id = "error">
<Li> <Bean: write name = "error"/> </LI>
</Html: messages>
</Ul> <HR/>
</Logic: messagespresent>

<HTML: Form Action = "registration-submit">
<HTML: hidden property = "action"/>

<Table border = "0" width = "100%">
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. firstname. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "firstname" size = "30" maxlength = "30"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. lastname. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "lastname" size = "60" maxlength = "60"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. ADDR. displayname"/>
</Th>
<TD align = "Left">
<HTML: textarea property = "ADDR" Cols = "40" rows = "5"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. City. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "citystatezip. City" size = "60" maxlength = "60"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. stateprov. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "citystatezip. stateprov" size = "60" maxlength = "60"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform.zip postal. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "citystatezip.zip postal [1]" size = "25" maxlength = "25"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. Phone. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "phone" size = "20" maxlength = "20"/>
</TD>
</Tr>
<Tr>
<TH align = "Left">
<Bean: Message key = "registrationform. Email. displayname"/>
</Th>
<TD align = "Left">
<HTML: Text property = "email" size = "60" maxlength = "60"/>
</TD>
</Tr>
<Tr>
<TD>
<HTML: Submit property = "Submit">
<Bean: Message key = "button. Save"/>
</Html: Submit>

<HTML: reset>
<Bean: Message key = "button. Reset"/>
</Html: reset>

<HTML: Cancel>
<Bean: Message key = "button. Cancel"/>
</Html: Cancel>
</TD>
</Tr>
</Table>

</Html: Form>

</Body>
</Html: HTML>

Note that the following three attributes are written. Their values will be saved to the citystatezip attribute of form Bean (registrationform:
<HTML: Text property = "citystatezip. City" size = "60" maxlength = "60"/>
<HTML: Text property = "citystatezip. stateprov" size = "60" maxlength = "60"/>
<HTML: Text property = "citystatezip.zip postal [1]" size = "25" maxlength = "25"/>

2. struts-config.xml Configuration

<? XML version = "1.0" encoding = "iso-8859-1"?>
<! Doctype Struts-config public
"-// Apache Software Foundation // DTD struts configuration 1.2 // en"
Http://struts.apache.org/dtds/struts-config_1_2.dtd>

<Struts-config>
<Form-beans>
<Form-bean name = "registrationform" type = "org. Apache. Struts. webapp. validator. registrationform"/>
</Form-beans>
<Action-mappings>
<Action Path = "/registration-submit"
Type = "org. Apache. Struts. webapp. validator. registrationaction"
Name = "registrationform"
Scope = "request"
Validate = "true"
Input = "/validator/registration. jsp">
<Forward name = "success" Path = "/index. jsp"/>
</Action>

</Action-mappings>

<Message-resources parameter = "org. Apache. Struts. webapp. validator. applicationresources"/>

<Plug-in classname = "org. Apache. Struts. validator. validatorplugin">
<Set-Property
Property = "pathnames"
Value = "/WEB-INF/validator-rules.xml,/WEB-INF/validation. xml"/>
</Plug-in>

</Struts-config>

1. Add the verification component validator in the struts-config.xml. It involves four important files. One is the registrationaction. Java that processes the form. Here, only the information is output in the log, and there is no database storage. If there is no error, go to the "success" page.

Package org. Apache. Struts. webapp. validator;

Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet. http. httpsession;

Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;
Import org. Apache. Struts. action. Action;
Import org. Apache. Struts. Action. actionform;
Import org. Apache. Struts. Action. actionforward;
Import org. Apache. Struts. Action. actionmapping;

Public final class registrationaction extends action {

/**
* Commons logging log.
*/
Private log = logfactory. getfactory (). getinstance (this. getclass (). getname ());


Public actionforward execute (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {


Registrationform info = (registrationform) form;
Citystatezip city = info. getcitystatezip ();
String action = request. getparameter ("action ");
If (log. isinfoenabled ()){
Log.info ("1: =" + city. getcity ());
Log.info ("2: =" + city. getstateprov ());
Log.info ("3: =" + city. getzippostal (1 ));
}
// Was this transaction canceled?
If (iscancelled (request )){
If (log. isinfoenabled ()){
Log.info (
""
+ Mapping. getattribute ()
+ "-Registration transaction was canceled ");
}

Removeformbean (mapping, request );

Return (mapping. findforward ("success "));
}

Return Mapping. findforward ("success ");
}

Protected void removeformbean (
Actionmapping mapping,
Httpservletrequest request ){

// Remove the obsolete form Bean
If (mapping. getattribute ()! = NULL ){
If ("request". Equals (mapping. getscope ())){
Request. removeattribute (mapping. getattribute ());
} Else {
Httpsession session = request. getsession ();
Session. removeattribute (mapping. getattribute ());
}
}
}
}

2. The other is the resource attribute file: applicationresources1_zh_cn.properties. use native2ascii.exe with JDK to convert it to applicationresources_zh_cn.properties and put it together with the class file.

D:/Java/> native2ascii-encoding gbk d:/Java/applicationresources1_zh_cn.properties> D:/Java/applicationresources_zh_cn.properties

It must include content in # errors (because this information is used in the validator-rules.xml)

Applicationresources1_zh_cn.properties
Button. Cancel = Cancel
Button. Confirm = Configuration
Button. Reset = Reset
Button. Save = submit

# Errors
Errors. footer =
Errors. header = Errors. ioexception = I/O exception rendering error messages: {0}
Error. database. Missing = <li> User Database is missing, cannot validate logon credentials </LI>
Errors. Required = {0} is required.
Errors. minlength = {0} cannot be less than {1} characters.
Errors. maxlength = {0} cannot exceed {1} characters.
Errors. Invalid = {0} is invalid.

Errors. byte = {0} must be an byte.
Errors. Short = {0} must be an short.
Errors. Integer = {0} must be an integer.
Errors. Long = {0} must be an long.
Errors. Float = {0} must be an float.
Errors. Double = {0} must be an double.

Errors. Date = {0} is not a date.

Errors. range = {0} is not in the range {1} through {2 }.

Errors. creditcard = {0} is not a valid credit card number.

Errors. Email = {0} is an invalid e-mail address.

# Registration Form
Registrationform. Title = server-side Verification
Registrationform. Title. Create = create user
Registrationform. Title. Edit = edit user information
Registrationform. firstname. displayname = Your Name:
Registrationform. lastname. displayname = your surname:
Registrationform. ADDR. displayname = your address:
Registrationform. City. displayname = province and city:
Registrationform. stateprov. displayname = state:
Registrationform.zip postal. displayname = zip code:
Registrationform. Phone. displayname = phone:
Registrationform. Email. displayname = E-mail:
Registrationform. lastname. maskmsg = The Last name can only be a character and cannot contain spaces.
3. The other two files are mentioned below.
Iii. validator Configuration
Copy the Validator-rules.xml, validation. XML to the path of the current application, such as WEB-INF/(which can be obtained after extraction from the struts-examples.war ).
1. What is defined in the Validator-rules.xml is the validator, which is stored in the form of <validator>. By default, the contained rules can already meet the needs of our program, and generally do not need to be modified.
2. Configure the validation. xml file, which defines the content of the validation rules unique to the application, and provides specific validation rules for form attributes using regular expressions.

<? XML version = "1.0" encoding = "iso-8859-1"?>
<! Doctype form-validation public
"-// Apache Software Foundation // DTD commons validator rules configuration 1.1.3 // en"
Http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd>
<Form-validation>
<Global>
<Constant>
<Constant-Name> phone </Constant-Name>
<Constant-value> ^ /(? (/D {3 })/)? [-|]? (/D {3}) [-|]? (/D {4}) $ </Constant-

</Constant>
<Constant>
<Constant-Name> zip </Constant-Name>
<Constant-value> ^/d {5}/D * $ </Constant-value>
</Constant>
</Global>
<FormSet>
<Constant>
<Constant-Name> zip </Constant-Name>
<Constant-value> ^/d {5} (-/d {4 })? $ </Constant-value>
</Constant>
<Form name = "registrationform">
<Field property = "firstname" depends = "required, mask, minlength">
<Arg key = "registrationform. firstname. displayname" position = "0"/>
<Arg name = "minlength" Key = "$ {var: minlength}" resource = "false" position = "1"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> ^/W + $ </var-value>
</Var>
<Var>
<Var-Name> minlength </var-Name>
<Var-value> 5 </var-value>
</Var>
</Field>
<Field property = "lastname" depends = "required, mask, maxlength">
<MSG name = "Mask" Key = "registrationform. lastname. maskmsg"/>
<Arg key = "registrationform. lastname. displayname" position = "0"/>
<Arg name = "maxlength" Key = "$ {var: maxlength}" resource = "false" position = "1"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> ^ [A-Za-Z] * $ </var-value>
</Var>
<Var>
<Var-Name> maxlength </var-Name>
<Var-value> 10 </var-value>
</Var>
</Field>
<Field property = "ADDR" depends = "required">
<Arg key = "registrationform. ADDR. displayname"/>
</Field>
<Field property = "citystatezip. City" depends = "required, mask">
<Arg key = "registrationform. City. displayname"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> ^ [A-Za-Z] * $ </var-value>
</Var>
</Field>
<Field property = "citystatezip. stateprov" depends = "required, mask">
<Arg key = "registrationform. stateprov. displayname"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> ^ [A-Za-Z] * $ </var-value>
</Var>
</Field>
<Field property = "citystatezip.zip postal [1]" depends = "required, mask">
<Arg key = "registrationform.zip postal. displayname"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> </var-value>
</Var>
</Field>
<Field property = "phone" depends = "Mask">
<Arg key = "registrationform. Phone. displayname"/>
<Var>
<Var-Name> mask </var-Name>
<Var-value> </var-value>
</Var>
</Field>
<Field property = "email" depends = "required, email">
<Arg key = "registrationform. Email. displayname"/>
</Field>
</Form>

</FormSet>
</Form-validation>

4. Test: Download the directory structure teststruts of the webmaster, put it under Tomcat's webapps, and enter in the browser:
Http: // 127.0.0.1: 8080/teststruts/validator/registration. jsp

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.