Form validation in Struts 2

Last Updated: February 9, 2018

There are several ways to do server-side validation of your form with Struts 2. We will see how we can use validate() inside your action class to validate form inputs

First you can create web project with Struts support

I have the user.jsp which is having the HTML form to enter first name and the last name fields

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

        JSP Page

Login Form

Next I will create the bean class which has first name and last name fields with getters and setters

package example;

public class User {
    private String firstName;
    private String lastName;

    public User(){
    public String toString() {
        return "hello";
    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastname() {
        return lastName;

    public void setLastName(String lastname) {
        this.lastName = lastname;

Next, we will create the action class . In this class we have refernce to the User bean class

package example;

import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport  {
    private User userBean;

    public User getUserBean() {
        return userBean;

    public void setUserBean(User userBean) {
        this.userBean = userBean;
    public String execute() throws Exception{
       return SUCCESS;

In this class you have to create the validate() to do the validation. You can add the following method to above class

public void validate(){
       if (userBean.getFirstName().length() == 0) {
         addFieldError("userBean.firstName", "First name is required.");

This will check the length of the first name field and error message is added using addFieldError() method

Now you can update the struts.xml file with following entry


If there is a error in vaidation process browser will load the user.jsp file again with error message

Now you can run the project and open the page in http://localhost:8080/validate/user.jsp
login form

When you leave the first name blank and submit thr form you will get following screen with the error message
login form error