Searching...
Sunday, 6 October 2013

Struts 2 Validation using properties file Example

09:52

in this example we will see how to use validation messages using properties file. Here i am using this Struts 2 Validation example to add properties file.

1. Create a Struts Application

Please download this Struts 2 Validation example to create web application

2. Create Properties file

Create below properties file and placed in to web-inf/classess folder

1. validation.properties

uname.blank = User Name should not be blank.
uname.invalid = Invalid User.


2. struts.properties

struts.custom.i18n.resources=validation


Final project structure


image

2. Create an action class (UserAction.java)

 
package com.pretech;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String execute() {
        setName("Hello " + name + " Welcome to Struts 2");
        return SUCCESS;
    }

    public void validate() {
        System.out.println("validation started");
        if (getName().length() == 0) {
            this.addFieldError("name", getText("uname.blank"));
        } else if (!getName().equals("pretech")) {
            this.addActionError(getText("uname.invalid"));
        }
    }
}

 

3. Test Application

Compile and run application in tomcat server, we will see below validations upon clicking submit button

1. If user name is blank


image 

2. If user name is less then 4 letters


image

0 comments: