Struts2 study notes checker

Source: Internet
Author: User
Tags cdata constant naming convention


Form verification can be performed in two ways.

The first is to write the relevant verification file, which is placed under the same level Directory of the class to be verified
The second is to write the verification logic in the Action, which can implement some special verification.


1. Verify with the xml configuration file

For example, my front-end has a form like this.

The code is as follows: Copy code

<S: form action = "ltlogin">
<! -- If the following sentence is not displayed, the error message is not displayed. The key to the jsp page is this sentence. -->
<S: fielderror/>
<S: textfield name = "name" label = "username"/>
<S: textfield name = "pass" label = "password"/>
<S: textfield name = "age" label = "age"/>
<S: textfield name = "birth" label = "birthday"/>
<S: submit value = "conversion"/>
<S: reset value = "Refill"/>
</S: form>

2. My struts. xml content is like this

The code is as follows: Copy code

<? Xml version = "1.0" encoding = "GBK"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<Constant name = "struts. i18n. encoding" value = "GBK"/>
<Constant name = "struts. ognl. allowStaticMethodAccess" value = "true"/>
<Package name = "default" extends = "struts-default">
<Action name = "ltlogin" class = "org. Rudiment. action. LoginAction" method = "checkSome">
<Result>/welcom. jsp </result>
<Result name = "input">/login. jsp </result>
</Action>
</Package>
</Struts>


 

3. The corresponding Action is

 

The code is as follows: Copy code

Package org. Rudiment. action;


Public class LoginAction extends ActionSupport
{
Private String name;
Private String pass;
Private int age;
Private int birth;
   
Public String getName (){
Return name;
    }

Public void setName (String name ){
This. name = name;
    }

Public String getPass (){
Return pass;
    }

Public void setPass (String pass ){
This. pass = pass;
    }

Public int getAge (){
Return age;
    }

Public void setAge (int age ){
This. age = age;
    }

Public int getBirth (){
Return birth;
    }

Public void setBirth (int birth ){
This. birth = birth;
    }

// Execute () is not overwritten. We can use the parent class method directly.
}

4. Next is our xml verification file.

This file writes the rule for verifying the Action, the file name is the LoginAction-validation.xml LoginAction is the name of the Action to be verified here the name should be consistent. Xxx-validation.xml xxx corresponds to the name of the Action you want to configure, put this configuration file in the same directory as the LoginAction class, the contents of the rule file is as follows:

The code is as follows: Copy code

<? Xml version = "1.0" encoding = "GBK"?>
<! DOCTYPE validators PUBLIC "-// Apache Struts // XWork Validator 1.0 //" http://struts.apache.org/dtds/xwork-validator-1.0.dtd ">

<Validators>
<Field name = "name">
<Field-validator type = "requiredstring">
<Param name = "trim"> true </param>
<Message key = "name. require"/>
</Field-validator>
       
<Field-validator type = "regex">
<Param name = "expression"> <! [CDATA [(w {4, 25})]> </param>
<Message> the user name you enter can only contain letters and numbers and must be 4-25 characters in length. </message>
</Field-validator>
</Field>
   
<Field name = "pass">
<Field-validator type = "requiredstring">
<Param name = "trim"> true </param>
<Message key = "pass. require"/>
</Field-validator>
       
<Field-validator type = "regex">
<Param name = "expression"> <! [CDATA [(w {4, 25})]> </param>
<Message> The password must be 4-25 characters long and contain letters and numbers. </message>
</Field-validator>
</Field>
</Validators>


I have verified two fields here. The above configuration method with the <field> label is called the field validator. Another non-field validator is replaced by <field> <validator>, which is not recorded here.
If an Action has multiple custom business processing methods similar to the execute () method, we can write a specific configuration file for specific method verification.
If we name the configuration file LoginAction-myexecute-validation.xml, this configuration file is only valid for the myexecute method.

The above is the complete configuration of the first verification method.


Now let's talk about the second method. In this method, we write the configuration file differently, just add
Public void validate ()
{// Our verification code}

This method checks all the business processing methods (for example, execute () in this Action.

If our Action has multiple business logic processing functions, there are multiple methods similar to execute. For example, this myexecute ()
If we want to manually write a custom verification method for this method, add a method validateMyexecute () in this Action according to the following rules ()
The naming convention for this method is the name of the method to be verified when validateXxxx () Xxxx

The following is an example:

The code is as follows: Copy code

Package org. Rudiment. action;

Public class LoginAction extends ActionSupport
{

Private String name;
Private String pass;
Private int age;
Private int birth;
   
// The getter and setter methods of this omitted property to save space

@ Override
Public String execute () throws Exception
    {
System. out. println ("neng12312bunengdlgdsfk133 ");
       
Return SUCCESS;
    }
   
Public String checkSome ()
    {
System. out. println ("execute checkSome ");
Return SUCCESS;
    }
   
   
@ Override
Public void validate ()
    {
// I did not write the verification logic here. The verification logic is written in this method.
System. out. println ("verification method entered ");
AddFieldError ("user", "the user name is too short ");
    }
   
Public void validateCheckSome ()
    {
// I did not write the verification logic here. The verification logic is written in this method.
System. out. println ("check checkSome ");
AddFieldError ("user", "the user name is too short for checkSOme ");
    }
   
}

You can use other files of the first method, except that you do not need to configure the xxx-validation.xml as in the first method. Then deploy the application. When the fields we entered do not comply with the verification rules, the tomcat console outputs information. I have no validation rules here, so in any case, "Enter the verification method" is always output in tomcat"

 

====================================== Extended content ============== ======================

HTTP Status 500-Method public java. util. list org. apache. struts2.components. form. getValidators (java. lang. string) threw an exception when invoked on org. apache. struts2.components. form @ 1588779-Class: freemarker. ext. beans. simpleMethodModel

If you get this prompt, you may set <s: form validate = "true"> The default value is false. When this value is true, struts2 starts client verification. I personally feel that the client Verification is too rigid. Generally, I suggest writing a customized js Test. Although The struts client is also a js Test, I personally feel that it is not easy to use.
When the above error occurs, there are two solutions:

1. Set validate = "false"
2. Move all JSPS to the WEB-INF/and then let the struts2 framework intercept the request, configure the following action in struts. xml
<Action name = "*">
<Result>/WEB-INF/{1}. jsp </result>
</Action>
That is, if you want to enable the client authentication function, you cannot directly request View resources (jsp). You must send a request to The struts framework, and then struts provides the view (jsp) for you ), this is more in line with the MVC design philosophy.

Note:/WEB-INF/all the files below, the client is not accessible directly.

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.