FieldError in Struts 2 Example
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.
** UPDATE: Struts 2 Complete tutorial now available here.
Folder Structure
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 & ActionMessage Example</h3> <s:actionmessage /> </body> </html>
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
When Username or password is empty, display error message set by <s:fielderror/>
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.
Reference
FieldError Apache
How to Override Default Theme in Struts 2 ?
Struts 2 have theme generation functionality due to which it automatically generates Table based HTML code for its tags. This is due the default theme (x_html)
** UPDATE: Struts 2 Complete tutorial now available here.
Other themes are
- simple
- css_xhtml
- ajax
You can change this theme setting to any other theme on tag level, page level or application level as shown below.
1. Tag Level
<s:submit name="clear" action="ClearFormAction" value="Clear" theme="simple" />
2. Page Level
a) Static value
<s:set name="theme" value="'simple'" scope="page"/>
b) Dynamic property
<s:set name="theme" value="%{myTheme}" scope="page"/>
3. Application Level
<constant name="struts.ui.theme" value="simple"/>
Popular Post in Struts 2 :
Read More
Changing default style of s:actionerror / s:actionmessage tag
In struts 2 when you use <s:actionerror /> tag, it displays the errors with bullets, On viewing the page source of the jsp page, we can see that error message is displayed using
<ul> <li>error 1</li> <li>error 2</li> </ul>
But suppose if our requirement is to display the error message without bullet in the action errors or action messages
** UPDATE: Struts 2 Complete tutorial now available here.
There are 2 ways to solve this problem
1. Customized the code in jsp, such that you can specify your own css for displaying the message
<s:if test="hasActionErrors()"> <s:iterator value="actionErrors"> <span class="msg"><s:property escape="false" /> </span> </s:iterator> </s:if>
2. Change the file in the “/template/simple/actionerror.ftl” and put it in the /web-directory/struts/simple if you are using simple theme
Similar kind of approach is followed for <s:actionmessage /> tag.
How to get checkbox values from struts2 checkbox in displaytag to action class
Consider a scenario, such that we have a list of items and each item can be selected by checking its checkbox. If a submit button is clicked after selecting all necessary checkboxes. So now, in our Action class, we could get the values of checkboxes which had been selected, by which we can implement delete functionality.
** UPDATE: Struts 2 Complete tutorial now available here.
The following snippet of code is used to retrieve the value from a checkbox used inside displaytag.
<display:table name="productList" pagesize="10" requestURI="productAction" id="row"> <display:column title="Delete"> <s:checkbox name="productList[%{#attr.row_rowNum - 1}].chkBox" id="check%{#attr.row_rowNum - 1}" value="%{#attr.row.chkBox}"/> </display:column> <display:column property="product" title="Product Name"/> <display:column property="price" title="Price"/> </display:table> <s:submit action="removeProduct" value="Delete" onClick="return confirm('Do you want to delete these items?');"/>
In our Action class, we can get the values of checkbox by creating getter & setter for the field “chkBox”.
Struts 2 tag not working in Display tag – Solution
Consider a scenario, such that you want to display a value of a column based on certain condition.
For example:
if a student’s marks is greater than 50 display as ‘pass’, if its less than 50 then display as ‘fail’. For this scenario, in a display tag, most of us result in the following code snippet.
<display:table name="ranklist" id="row" pagesize="10" requestURI="rankAction" > <s:if test="%{mark > 50}"> <display:column title="Status">Pass</display:column> </s:if> <s:elseif test="%{mark < 50}"> <display:column title="Status">Fail</display:column> </s:elseif> </display:table>
But here unfortunately this code does not works, because the variable “mark”is not reachable inside the display tag, since it is not associated with current display table.
** UPDATE: Struts 2 Complete tutorial now available here.
Solution :
So the correct way of coding is:
<display:table name="ranklist" id="row" pagesize="10" requestURI="rankAction" > <display:column property="userName" title="User Name" /> <s:if test="%{#attr.row.mark > 50}"> <display:column title="Status">Pass</display:column> </s:if> <s:elseif test="%{#attr.row.mark < 50}"> <display:column title="Status">Fail</display:column> </s:elseif> </display:table>
Generalized way to access the struts 2 tag via display tag is :- #attr.tableIdName.tableField. So the only way to access a struts 2 tag inside displaytag, is to follow the above syntax.
Example : To access a property tag inside display tag :
<s:property name="userId" value="#attr.row.userId" />
Related Questions:
How to get checkbox values from displaytag using struts2
Displaytag export option is not working?
Concept of Servlets Vs Concept of Struts 2
In our previous article we have created a hello world program in struts2, in which I have passed parameter from request and setted in action class via a member variable, which may led you in some confusion, since in case of servlets the member variable in it are shared between all request and only those variable inside doget and dopost methods remains unique. So inorder to know why a member variable in struts 2 remains unique per request, we have look into the conceptual difference between Servlets and Struts 2. This article deals with the same.
** UPDATE: Struts 2 Complete tutorial now available here.
In case of Servlet when we have N number of request then only one object is created out of which N number of Threads are created , in which a request object is created. So the objects inside the thread are safe and not shared with other thread objects.
But suppose if the Servlet has Member variable, then those variable are not thread safe, as they are shared between all the threads created for each request.
The above concept is depicted pictographically below.
Note: Servlet & Struts 1 follows same concept.
In case of struts 2 for N number of request N number of object is created. So in this case, even the member variable for these objects are not shared between objects of other request, that the reason Struts 2 is said to be thread safe.
The concept of Struts 2 is depicted pictographically as below.
In our next article we shall learn about the roles of Action class in struts 2.