Pages Navigation Menu

Coding is much easier than you think

FieldError in Struts 2 Example

 
Field error in Struts 2
 
In our previous tutorial we learnt about actionError and actionMessage in struts 2, in this tutorial, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exist.
 

download

 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Folder Structure

 
Struts 2 Field Error
 

Action Class

 
Develop an action class using addFieldError(String fieldName, String errorMessage)method. This method adds an error message for a given field to the corresponding jsp page.

Here the error messages is added to each field individually using the addFieldError() method. The error messages can either be specified in a separate property file or can be added directly in the Action class itself.
 

package com.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 6677091252031583948L;

	private String userName;
	private String password;

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String execute() {
		return SUCCESS;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void validate() {

		if (userName.isEmpty()) {
			addFieldError("userName", "Username can't be blank");
		}
		if (password.isEmpty()) {
			addFieldError("password", "Password Can't be blank");
		}
		else {
		addActionMessage("Welcome " + userName + ", You have been Successfully Logged in");
		}
	}
}

 
Here when either of userName or password is empty then fieldError is added this action via addFiedError method, so the execute method does not get invoked, and interceptors take case altering the flow of response by sending “error” string.
 
If userName and password are valid then a success message is added to actionMessage, the execute method get invoked, the jsp page get displayed based on execute methods returned value.
 
Recommended Article

 

JSP

 
File: Login.jsp
 
Create a jsp page that will display your field error messages (when fails to logged-in) using <s:fielderror/> tag as shown:
 

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>FieldError in Struts 2</h3>
<s:form action="loginUser">
	<s:textfield name="userName" placeholder="Username" label="Username" />
	<s:password name="password" placeholder="Password" label="Password" />
	<s:submit value="Submit" />
</s:form>
</body>
</html>

 
File : Success.jsp
 

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h3>ActionError &amp; ActionMessage Example</h3>
	<s:actionmessage />
</body>
</html>

 

Note :

We have done the coding such that If the username or password is empty , then the user will be forwarded to login.jsp where the field error added using addFieldError will get displayed.


 
You might be interested to read:

 

struts.xml

 
Make sure that the struts.xml has the following mapping

<struts>
 <package name="default" extends="struts-default">
     <action name="loginUser" class="com.action.LoginAction">
	<result name="success">success.jsp</result>
	<result name="input">login.jsp</result>
     </action>
 </package>
</struts>

 
The web.xml configuration is same as given in hello world programe.
 

Demo

 
On running the application
 
FieldError in Struts 2
 
When Username or password is empty, display error message set by <s:fielderror/>
 
FieldError in Struts 2 Error
 
When Username and password is non empty, then application executes successfully and redirects to success.jsp and displays the ActionMessage setted in Validate method via <s:actionmessage/> tag.
 
FieldError in Struts 2 Action Message
 

Reference

 
FieldError Apache
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • steve

    Doesn’t your login.jsp need to have s:fielderror tags in it to indicate where the field-specific errors should be displayed?

    • http://www.simplecodestuffs.com Mohaideen Jamil

      No it is not needed when you add field error message for field in UI, because interceptors takes care of it. But suppose if you are trying to add fielderror for the fields not in ui, for example [code]addFieldError("dummyField", "dummy message");[/code].. now inorder to display this field error in ui, you need to use [code][/code] in jsp page

  • Hemant

    I want error messages show on the textfields.

    • Jamil

      Hi Hemant ,
      Can you please post the source code in comment once again using  <pre class=”prettyprint lang-java”> source code </pre> . As the struts xml you uploaded is missing.

      Thanks:)

    • Jamil

      Hi Hemant, I could not able to receive your xml file.
      Please post your source code using  <pre class=”prettyprint lang-java”> source code </pre> .
      or mail to simplecodestuffs@gmail.com
      Thanks:)

  • Hemant

    Hi, I am new to Struts2. I have a Login Jsp page, after validating by the Validations annotation, error messages are not visible. Plz help me.

    Login.jsp

    Username :

    Password :

    LoginAction.xml

    public class LoginAction extends ActionSupport{

    private String userName;
    private String userPassword;
    public String getUserName() {
    return userName;
    }

    @Validations(requiredStrings={@RequiredStringValidator(type=ValidatorType.FIELD, message=”User Name can ot be empty.”, fieldName=”userName”)})
    public void setUserName(String userName) {
    this.userName = userName;
    }
    public String getUserPassword() {
    return userPassword;
    }

    @Validations(requiredStrings={@RequiredStringValidator(type=ValidatorType.FIELD, message=”Password can ot be empty.”, fieldName=”userPassword”)})
    public void setUserPassword(String userPassword) {
    this.userPassword = userPassword;
    }

    public String execute()
    {
    return SUCCESS;
    }

    }

    struts.xml

    /success.jsp
    /Login.jsp