In this example we will see how to use Annotation based validation in Struts 2.
1. Create a Struts Application
Please download this Struts 2 Validation example to create web application
2. Create an Action class (UserAction.java)
package com.pretech;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Name Should not be blank", key = "errors.required")
@StringLengthFieldValidator(type = ValidatorType.FIELD, message = "Name should contain min of 4 characters and max 15 charcters", minLength = "4", maxLength = "15", trim = true)
public void setName(String name) {
this.name = name;
}
public String execute() {
setName("Hello " + name + " Welcome to Struts 2");
return SUCCESS;
}
}
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
@RequiredStringValidator(type = ValidatorType.FIELD, message = "Name Should not be blank", key = "errors.required")
@StringLengthFieldValidator(type = ValidatorType.FIELD, message = "Name should contain min of 4 characters and max 15 charcters", minLength = "4", maxLength = "15", trim = true)
public void setName(String name) {
this.name = name;
}
public String execute() {
setName("Hello " + name + " Welcome to Struts 2");
return SUCCESS;
}
}
3. Test validations
Compile and run application in tomcat server, we will see below validations upon clicking submit button
1. If user name is blank
2. If user name is less then 4 letters
No comments:
Post a Comment