Saturday, 5 October 2013

Struts 2 Simple manual validation Example


Struts 2 validation is configured via XML or annotations. Manual validation in the action is also possible, and may be combined with XML and annotation-driven validation, see more about Struts 2 Validation.

In this example we will see one simple user name manual validation in action class.

1. Create a web project.

Create a dynamic web project and all struts 2 related jars in to lib folder. Here is the final structure of this example.


2. Create an Action class (

The validate method is taking care validating and throwing error messages.

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) { = name;
    public String execute() {
        setName("Hello " + name + " Welcome to Struts 2");
        return SUCCESS;
    public void validate() {
        if (getName().length() == 0) {
            addFieldError("name", "Name should not be blank");
        } else if (!getName().equals("pretech")) {
            this.addActionError(getText("Invalid user"));

3. Create a JSP page (index.jsp)

This jsp file contains input field for user name and submit button

<%@ taglib prefix="s" uri="/struts-tags" %>
<h4>Welcome to Struts 2</h4>
<s:form action="userAction">
    <s:textfield name="name" label="Enter your nme" /><br>
    <s:submit value="submit" align="center" />

4. Create a success page

<%@ taglib prefix="s" uri="/struts-tags" %>
    <s:property value="name" />

5. Struts.xml

<?xml version="1.0" encoding="UTF-8"?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <include file="struts-default.xml"/>
    <package name="a" extends="struts-default">
        <action name="userAction" class="com.pretech.UserAction">
            <result name="success">/success.jsp</result>
            <result name="input">/index.jsp</result>

6. Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">

7. Test Validation

Run this application and click on submit button without any username , we will see below validation error messages



Download this example: Struts 2 Simple Validation