简体   繁体   中英

How Struts2 validation framework works

I am using struts2 for my project. Now i have a business information fill-up form for getting business details. In form i have some basic items such as email, username , password , confirm password & Facebook twitter links(FB & tweeter links are optional but if user enters i want to check whether they are real) for basic items i am using xml file validation as:

<validators>
    <field name="companyname">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message>Company name is required.</message>
        </field-validator>
    </field>        
    <field name="fblink">
        <field-validator type="url">
        <message>Please enter a valid url</message>
        </field-validator>
    </field>
    <field name="tweetlink">
        <field-validator type="url">
        <message>Please enter a valid url</message>
        </field-validator>
    </field>
</validators>

& if user enters values for Facebook or twitter url i am writing validation in Action class's Validate() method to check whether these are real(means HTTP_STATUS_CODE=200) as :

    public void validate()
    {
if(getFblink()!=null && !getFblink().isEmpty())
        {
            if(URLValidation.validate(getFblink())== false)
            {
                addFieldError("fblink", getText("Enter valid facebook page link"));
            }
        }       
        if(getTweetlink()!=null && !getTweetlink().isEmpty())
        {
            if(URLValidation.validate(getTweetlink())== false)
            {
                addFieldError("tweetlink", getText("Enter valid tweeter link"));
            }
        }
    }

Here URLValidation is my class & it contains static method validate which takes URL & using Httpclient libraries i am hitting & checking its status code. Depending on its return value ie boolean value i am setting error message.

Its working. But i want to know is my approach is correct? Also i want to use shor-circcuit validation so how can i communicate in xml & validate() validation code??

You want to validate links and want to use your code (from validation xml). This will be possible by writing custom validators. Write a custom validator and use it through XML file for your fields.

For example you can see this tutorial for an idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM