Monday, 25 January 2016

Struts2: ActionError & ActionMessage Example

Struts2 ActionSupport class provides addActionError, addActionMessage methods used to send feedback (or) error messages to user. In this post, I am going to explain an example, which uses addActionError, addActionMessage methods to send messages to user.

Class (or) Jsp
Description
LoginAction.java
If user log in successfully, then page is redirected to success.jsp, else page stays in index.jsp and shows validation (or) verification errors.
index.jsp
Contains login form
success.jsp
Displays success message, if user login successfully.



Following snippet displays all action error messages.
<s:if test="hasActionErrors()">
   <div class="errors">
      <s:actionerror/>
   </div>
</s:if>


Following snippet displays all action messages.
<s:if test="hasActionMessages()">
   <div class="welcome">
      <s:actionmessage/>
   </div>
</s:if>


Following is the stpe-by-step procedure to develop complete working application in Eclipse.

Step 1: Create new dynamic web project ‘struts_action_messages’ in Eclipse.
File -> New -> Dynamic Web Project.

Step 2: Mavenize the project, Right click on the project -> Configure -> Convert To Maven Project.

Update pom.xml for struts dependencies, following are the maven dependencies, I am going to use.

pom.xml
<dependency>
 <groupId>org.apache.struts</groupId>
 <artifactId>struts2-core</artifactId>
 <version>2.3.20</version>
</dependency>
<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <version>1.16.6</version>
 <scope>provided</scope>
</dependency>


Step 3: Update index.jsp like below.
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.errors {
 background-color: #FFCCCC;
 border: 1px solid #CC0000;
 width: 400px;
 margin-bottom: 8px;
}

.errors li {
 list-style: none;
}

.welcome {
 background-color: #DDFFDD;
 border: 1px solid #009900;
 width: 200px;
}

.welcome li {
 list-style: none;
}
</style>
</head>
<body>
 <s:if test="hasActionErrors()">
  <div class="errors">
   <s:actionerror />
  </div>
 </s:if>

 <s:if test="hasActionMessages()">
  <div class="welcome">
   <s:actionmessage />
  </div>
 </s:if>

 <table>

  <tr>
   <td>
    <form action="loginCheck" name="playerLogin" method="post">
     <table align="left" width="40%">
      <tr>
       <th>My Account</th>
      </tr>
      <tr>
       <td>Username *</td>
      </tr>
      <tr>
       <td><input type=text name="userName" value="" /></td>
      </tr>
      <tr>
       <td>Password *</td>
      </tr>
      <tr>
       <td><input type=password name="password" value="" /></td>
      </tr>
      <tr>
       <td><input type=submit name="submitButton" value="LogIn" />
      </tr>
     </table>
    </form>
   </td>
  </tr>

 </table>

</body>
</html>


Step 4:  Define success.jsp like below.
success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.errors {
 background-color: #FFCCCC;
 border: 1px solid #CC0000;
 width: 400px;
 margin-bottom: 8px;
}

.errors li {
 list-style: none;
}

.welcome {
 background-color: #DDFFDD;
 border: 1px solid #009900;
 width: 200px;
}

.welcome li {
 list-style: none;
}
</style>
</head>
<body>
 <s:if test="hasActionErrors()">
  <div class="errors">
   <s:actionerror />
  </div>
 </s:if>

 <s:if test="hasActionMessages()">
  <div class="welcome">
   <s:actionmessage />
  </div>
 </s:if>

 <h1>Login successfull</h1>
</body>
</html>


Step 5: Create package com.sample.actions, Define class LoginAction.java.

LoginAction.java

package com.sample.actions;

import lombok.Getter;
import lombok.Setter;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
 @Getter @Setter private String userName;
 @Getter @Setter private String password;

 public String execute() {
  if (!isValidRequestParams()) {
   return "input";
  }
  return "success";
 }

 public boolean isValidRequestParams() {
  if (userName == null) {
   addActionError("userName shouldn't be empty");
  }

  if (password == null) {
   addActionError("userName shouldn't be empty");
  }

  if (userName != null && userName.length() < 5) {
   addActionError("userName must has atleast 5 characters");
  }

  if (password != null && password.length() < 5) {
   addActionError("password must has atleast 5 characters");
  }

  if (userName != null && !userName.equals("admin")) {
   addActionError("userName is not correct");
  }

  if (password != null && !password.equals("admin")) {
   addActionError("password is not correct");
  }

  if (this.hasActionErrors()) {
   return false;
  }

  addActionMessage("Welcome Admin");
  return true;
 }
}


hasActionErrors() method returns true, if any addActionError are added, else false.
hasActionMessages() method returns true, if any addActionMessage are added, else false.

Step 6: Update web.xml like below.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>struts_action_messages</display-name>
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <display-name>struts action messages example</display-name>
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <session-config>
  <session-timeout>1</session-timeout>
 </session-config>

</web-app>


Step 7: It is time to create struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. Create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder. Create struts.xml file inside classes.

struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="default" extends="struts-default">
  <action name="loginCheck" class="com.sample.actions.LoginAction">
   <result name="input">/index.jsp</result>
   <result name="success">/success.jsp</result>
  </action>
 </package>

</struts>


Complete project structure looks like below.
Run project on application server, submit login form, without entering any values, you will get following kind of screen.
Enter username as admin, password as admin and submit the login form, you will get following kind of screen.


Previous                                                 Next                                                 Home

No comments:

Post a Comment