Struts2 examples of built-in validators

Source: Internet
Author: User

First, the configuration of the validator style

1. Field Validator:

<field name= "verified field" >

<field-validator type= "Validator Name" >

<!--Here you need to specify a different number of check rules for each validator--

<param name= "parameter name" > Value of Parameters </param>

....................

<!--the prompt after the failure of the checksum, where key specifies the key--> of the internationalized information

<message> Check for information after failure </message>

<!--check after the failure of the prompt message: Recommended with GetText ("I18nkey"), or may appear freemarker template error-->

</field-vallidator>

<!--if the check field satisfies more than one rule, you can configure multiple validators--

</field>

2. Non-field validator (used in this example):

<validator type= "Validator Name" >

<param name= "FieldName" > Fields to be validated </param>

<!--Here you need to specify a different number of check rules for each validator--
<param name= "parameter name" > Value of Parameters </param>

<message> Check for information after failure </message>

</validator>

The two configurations differ only in style, without essential differences.

Second, examples

4 built-in validators are used in this registration project. The project has only one registration page (register2.jsp), corresponding to the business controller (Register2action.java). If the input data is validated successfully by the built-in validator, jump to success1.jsp.

The example steps are as follows:

Attention:

Register2action.java and Register2action-validation.xml within the same package validatoraction

Register2.jsp and success1.jsp under WebContent (I'm using Eclipse) in the same folder validate

1. Web. XML Configuration Filterdispatcher

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.4"xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "><filter> <!--configuration Struts2 core Filter Name---<filter-name>struts2</filter-name> <!--configuration Struts2 core Filter implementation Class--<filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class> </filter> <!--Configuring the URL of filter blocker-<filter-mapping> <!--configuring STRUTS2 core filt Erdispatcher Intercept all user requests-<filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

2. Writing the View component (JSP page)

(1) registration page (register2.jsp)

<%@ page language= "Java"Import= "java.util.*" contenttype= "text/html; Charset=utf-8 "pageencoding= "Utf-8"%><%@ taglib prefix= "s" uri= "/struts-tags"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Please enter information:

(2) Verification Success page (SUCCESS1.JSP)

<%@ page language= "Java"Import= "java.util.*" contenttype= "text/html; Charset=utf-8 "pageencoding= "Utf-8"%><%@ taglib prefix= "s" uri= "/struts-tags"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >The verification pass, the user information is as follows:Name:<s:property value= "UserName"/> <br>Password:<s:property value= "UserPassword"/> <br>Age:<s:property value= "Userage"/> <br>Tel:<s:property value= "Usertelephone"/> <br>Email:<s:property value= "UserEmail"/></body>

3. Write business controller (Register2action.java)

 Packagevalidatoraction;ImportCom.opensymphony.xwork2.ActionSupport; Public classRegister2actionextendsactionsupport{PrivateString UserName; PrivateString UserPassword; PrivateString Ruserpassword; Private intUsertelephone; Private intUserage; PrivateString UserEmail;  PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     PublicString Getuserpassword () {returnUserPassword; }     Public voidSetUserPassword (String userpassword) { This. UserPassword =UserPassword; }     PublicString Getruserpassword () {returnRuserpassword; }     Public voidSetruserpassword (String ruserpassword) { This. Ruserpassword =Ruserpassword; }     Public intGetusertelephone () {returnUsertelephone; }     Public voidSetusertelephone (intUsertelephone) {         This. Usertelephone =Usertelephone; }     Public intGetuserage () {returnUserage; }     Public voidSetuserage (intuserage) {         This. Userage =Userage; }     PublicString getUserEmail () {returnUserEmail; }     Public voidSetuseremail (String useremail) { This. UserEmail =UserEmail; }             PublicString Execute () {return"Success"; }        }

4, Configuration Struts.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts     Public " -//apache software foundation//dtd Struts Configuration 2.3//en "     http://struts.apache.org/dtds/struts-2.3.dtd" ><struts>            <packageextends= "Struts-default" >        class= " Validatoraction.register2action ">            <result name=" input ">/validate/register2.jsp</result>            <result name= "Success" >/validate/success1.jsp</result>        </action>    </Package ></struts>

5. Verification file with built-in validator

<?xml version= "1.0" encoding= "UTF-8"?> <!doctype validators public  "-//apache struts//xwork Validator 1.0.3//en" "Http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd" > &lt ;validators> <!--string length checker, verifying username properties--<validator type= "Stringlength" > <param name = "FieldName" >userName</param> <param name= "maxLength" >16</param> <param name= "mi Nlength ">6</param> <message> name length ${minlength} to ${maxlength} characters! </message> </validator> <!--string length checker, verifying userpassword Properties--<validator type= "Stri Nglength "> <param name=" fieldName ">userPassword</param> <param name=" MaxLength ">16& lt;/param> <param name= "minLength" >6</param> <message> password length ${minlength} to ${maxlength } characters!          </message> </validator> <!--field Expression validator--<validator type= "Fieldexpression" > <param name= "FieldName" >userpassword</param> <param name= "expression" > <!--Verify that the password entered two times is the same-and <! [cdata[userpassword==ruserpassword]]> </param> <message> two times passwords are inconsistent! </message> </validator> <!--integer Validator--<validator type= "int" > <par Am Name= "fieldName" >userAge</param> <param name= "min" >1</param> <param name= "Max ">130</param> <message> age must be between ${min} to ${max}! </message> </validator> <!--integer Validator--<validator type= "int" > &LT;PA Ram Name= "FieldName" >userTelephone</param> <param name= "min" >22222222</param> <p Aram Name= "Max" >99999999</param> <message> phone must be eight-digit number between ${min} to ${max}! </message> </validator> <!--mail address checker--<validator type= "email" > <par Am Name= "FieldName";useremail</param> <message> Please use the correct message format! </message> </validator> </validators>

If the validation fails:

Check the case of attributes such as stringlength, and whether the field matches the previous one;

View the Struts-2.3.28.1\src\xwork-core\src\main\resources\xwork-validator-1.0.3.dtd file and copy the first 4 lines of code, depending on the version.

Struts2 examples of built-in validators

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.