Upul Udukala
How to validate a form in action class and forward errors to the jsp in struts?
2 Answer(s)      5 years and 10 months ago
Posted in : Struts

How to validate a form in action class and forward errors to the jsp in struts?


View Answers

April 1, 2011 at 4:11 PM


<meta http-equiv="refresh" content="0;URL='formAction'" >


package net.roseindia.action;

import net.roseindia.model.UserModel;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ValidationAction extends ActionSupport implements ModelDriven {
    UserModel obUserModel;

    public String execute() throws Exception {

        return SUCCESS;


    public void validate() {
        if (obUserModel.getName().length() == 0) {
            addFieldError("name", "Name is required.");
        if (obUserModel.getAge().length() == 0) {
            addFieldError("age", "Age is required.");
        if (obUserModel.getAddress().length() == 0) {
            addFieldError("address", "Address is required.");

    public Object getModel() {
        // TODO Auto-generated method stub
        obUserModel = new UserModel();
        return obUserModel;



package net.roseindia.model;

import java.io.Serializable;

public class UserModel implements Serializable {
    private String name;
    private String age;
    private String address;
    private int phone;

    public String getName() {
        return name;

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

    public String getAge() {
        return age;

    public void setAge(String age) {
        this.age = age;

    public String getAddress() {
        return address;

    public void setAddress(String address) {
        this.address = address;

    public int getPhone() {
        return phone;

    public void setPhone(int phone) {
        this.phone = phone;

April 1, 2011 at 4:14 PM


<[email protected] prefix="s" uri="/struts-tags" %>
<title>User form</title>
<h1>User information form...</h1><hr/>
<s:form action="formvalidation">
    <s:textfield key="name" label="Name" />
    <s:textfield key="age" label="Age" />
    <s:textfield key="address" label="Address" />
    <s:submit />


<?xml version="1.0" encoding="UTF-8"?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    <constant name="struts.devMode" value="false" />
    <package name="roseindia" extends="struts-default">
        <action name="formAction" >
            <result name="success">/userform.jsp</result>
        <action name="formvalidation" class="net.roseindia.action.ValidationAction">
            <result name="input">/userform.jsp</result>

Related Tutorials/Questions & Answers: