Sunteți pe pagina 1din 302

Struts 2 Tutorial for beginners

Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial, Struts-2 | 25 comments


Introduction to Struts 2 Framework

In this course we will learn how to use Struts 2 to create an MVC based Java web application.
Struts 2 is a framework for developing MVC based web applications in Java. When building a
complex web application it is often difficult to keep business and view logic separate from each
other. In this course we will learn how to create a Java based web application using the Struts
2 MVC framework to cleanly separate our views from business logic.
We will cover important features of Struts 2 like creating Actions and mapping them to Results.
We will also learn how to use OGNL to access data from Java objects inside of our Views and
even see how to create AJAX style views. If you are interesting in learning Struts 2, this course
is a great start point to get you started by building your first Struts 2 application.

Struts 2 Complete Tutorial
Model 1 and Model 2 (MVC) Architecture

Introduction to Struts 2 Framework
Struts 2 Environment Setup

Struts 2 Quick Start
Hello world in struts 2 Getting Started
Concept of Servlets Vs Concept of Struts 2
Roles of Actions class in Struts 2
Struts2 Configuration file and its roles
Architecture overview of Struts 2
DispatchAction Functionality in struts2
Dynamic Method Invocation using Action Wildcards

Non Form UI Tags
Struts 2 ActionError & ActionMessage Example
Struts 2 FieldError Example

Struts 2 Configurations
Understanding Namespace configuration example and explanation
Multiple Struts configuration files example
Struts2 Custom extension example
Struts 2 Development mode

Struts 2 Model driven
JavaBean class as a property in struts 2 action class.

Struts 2 ModelDriven example

Struts 2 File Manipulation Tutorial
Struts 2 File Upload example
How to override struts 2.x file upload error messages?
Struts 2 File Download Example

Struts 2 UI Tags

TextBox example
Password example
Hidden value example
Textarea example
<S:token/>
head example
Datetimepicker example
Datetimepicker using Jquery
Struts 2 Autocompleter Textbox & dropdown example

Struts 2 Control Tags
Struts 2 If, Else, ElseIf Tag example
Struts 2 iterator tag example

Struts 2 Data Tags
bean tag example
push tag example
debug Tag Example
Url tag example

Interceptors in Struts 2
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Struts 2 + Display tag
Struts 2 Pagination example
Struts 2 tag not working inside a Display tag Solution
How to get checkbox values from displaytag using struts2
Displaytag export option is not working- Solution

Struts 2 Theme
Tips to Override Default Theme in Struts 2 ?


Ajax implementation in Struts 2
Ajax implementation in Struts 2 without jQuery
AJAX implementation in Struts 2 using JQuery and JSON
Autocomplete in Struts 2 using Jquery and JSON via Ajax
Integrating jQuery DataTable with Struts2 using Ajax to implement Gridview

Struts 2 + jTable Plugin
Integrating jQuery jTable plugin with Struts 2 framework
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Pagination in Struts 2 using jQuery jTable plugin

Struts 2 Integrate with Other Frameworks
Struts 2 + Spring integration example
Struts 2 + Log4j integration example
Struts2-Jfreechart integration
Struts 2 and Tiles Framework Integration
Integrating Quartz Scheduler in Struts 2 Web Application

Struts 2 FAQ
Difference Between Struts 2 FilterDispatcher And StrutsPrepareAndExecuteFilter
How to exclude action methods from validation in struts2
How To Get The ServletContext In Struts 2
Action Chaining and Action redirect
Difference between # , $ and % signs in Struts2
Handling Exception in Struts 2
Example to Call Struts2 action from java script
Dynamically add, remove list of objects from jsp Using Struts2
Changing default style of s:actionerror / s:actionmessage tag
Common Support class for Action classes in Struts 2

Struts 2 Errors
There is no Action mapped for namespace / and action name yourActionName

Struts 2 Reference
Struts 2 Official Documentation


Model 1 and Model 2 (MVC) Architecture
Posted by Mohaideen Jamil on Jan 14, 2014 in Java, Servlet, Struts 1, Struts-2 | 1 comment


Misconceptions

Student: Master, what is the difference between MVC 1 and MVC 2 ?
Master: Grasshopper, there is no such thing as MVC 1 and MVC 2, theres just MVC. if you
meant to ask about the difference between Model 1 and Model 2 with respect to web
applications, then this article will help you out.

In Java there are two types of programming models
1. Model 1 Architecture
2. Model 2 (MVC) Architecture

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

Model 1 Architecture



Flow of the Model 1 architecture.
1. Browser sends request for the JSP page
2. JSP accesses Business service Bean class and invokes business logic
3. Business service Bean class connects to the database to store/retrieve data
4. Response generated by JSP is sent to the browser

Disadvantage
Navigation control is decentralized

Model 2 (MVC) Architecture



Model 2 is based on the MVC (Model View Controller) design pattern.
Model Represents the data and business logic of the application.
View Represents the presentation.
Controller The controller module acts as an interface between view and model.
It intercepts all the requests i.e. receives input and commands to Model / View
to change accordingly.

Advantage of Model 2 (MVC) Architecture
Navigation control is centralized (Controller only has the control to determine the next page)
Easy to maintain, extend and test.
Disadvantage of Model 2 (MVC) Architecture
If we change the controller code, we need to recompile the class and redeploy the application.

Introduction to Struts 2 Framework
Posted by Mohaideen Jamil on Mar 20, 2014 in Struts-2 | 0 comments

In our last article we have learned about the difference between Model 1 and Model 2 (MVC)
Architecture. In this article we will learn about Struts 2 framework and about
the Architecture which it follows.

In general if you are about to build a standard application using JSP and Servlets, then you will
end up in a following MVCpattern.



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

Why web Framework ?

Web framework is a basic ready made underlying of MVC structure, where you have to just
add components related to your business. It forces the team to implement their code in a
standard way. (helps debugging, fewer bugs etc).

Step involved in building a framework.

Step 1: Router to route the request to the correct MODEL and correct View layer
Step 2: Handle the request parameters
Step 3: Create a interface class(Model) for business service class
Step 4: View part(Jsp) to render the result

The above steps are depicted photographically below.



Struts 2 developers have identified all these modules and had builded the same. Below is how
a struts 2 design will look like.



Here Interceptor is the gate way through which a request is passed. It takes care of getting
user request parameters,

Struts 2 framework get all the request parameters from interceptor and makes it available
for Action class and we dont need to fetch it in the action class via any request or session
objects like we do in Servlets, because struts 2 makes it available.

Here Struts.xml acts as controller which Controls the execution flow of the request, Action
class represents Model and JSP represent View layer.

Note:

In struts 2 the data can be displayed in jsp with tab library,

In our next tutorial, we will learn to set up struts 2 environment in eclipse.
Struts 2 Environment Setup
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments


In our previous tutorial we got introduced to what a framework is, and why we go for struts 2. In
this tutorial you will learn how to setup development environment for Struts 2 Framework.

Environment Used

JDK 7 (Java SE 7)
Eclipse JUNO IDE
Apache Tomcat 7.x
Struts 2 jars

Setting up development environment

To install Eclipse IDE and to configure Apache Tomcat read this page

Struts 2 Framework library download:
Downloading Struts 2 Framework: It is available for downloading straight from its official site.
The latest version of this framework for this day is 2.3.8
Simply go to http://struts.apache.org/.
Choose Struts-2.3.8 Download option as shown on the picture below:



Extracting Struts 2 download: Now extract the downloaded file (struts-2.3.8-all.zip) into
your favourite. Say, D:\\Struts 2.3.8-all\
And download latest version eclipse from http://www.eclipse.org/, once installed

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


Create a Dynamic Web Project:
Now create a new Dynamic web project using the following option:
File > New > Dynamic Web Project and enter project name as LoginStruts2 and set rest of
the options as given in the following screen:



Now copy following files from struts 2 lib folder D:\struts-2.3.8-all\lib to our projects WEB-
INF\lib folder.

Now restart your tomcat server or build and clean it.

Thats all on how to create a Struts 2 project in eclipse, in our next article we shall learn to
implement a basic hello world program in struts 2

Hello world in Struts 2 Getting started
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 1 comment
In our previous article we learnt that there are 4 basic component in struts 2 framework.

They are
1. struts.xml
2. Interceptors
3. Action class
4. JSP



Since interceptor module is available in struts 2 by default, so for simplicity lets us ignore this
module as of now and we shall explore then latter.

Now ignoring interceptors the flow diagram of struts 2 looks as below.



Now create a Dynamic web project with the following folder structure.

Include the below list of commonly used JAR files required by Struts 2 framework to your
projects WEB-INF/lib folder.



commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
ognl-3.0.6.jar
struts2-core-2.3.8.jar
xwork-core-2.3.8.jar



Now the role of struts.xml here is to Controls the execution flow of the request
1. It maps the input URL to the action classes
2. It maps the input URL to the Jsp



Now consider a scenario where i receive the input request as http://localhost/login, in this case
I need this request to be mapped to a Action class, let assume that action class to be
LoginAction.


Which Method ?

In case of Servlets when a servlet got invoked, then by either doget() or dopost() method will
get invoked. But in case of struts 2, when an action class gets invoked then by default execute
method will executed, provided the signature of this execute method should be as below
public String execute()



We can have other method configured in Action class, we will learn about that in our upcoming
tutorials

Configuring request in struts.xml

The struts.xml file needs to be configured with these basic tags, and this file should always
present in src folder.

<?xml version="1.0" encoding="UTF-8" ?>
<!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="login" class="com.action.LoginAction">

</action>
</package>
</struts>

When a clients request matches the action name, the framework uses the mapping
from struts.xml file to process the request. The mapping to an action is usually generated by a
Struts Tag. The action tag ( struts.xml file) specifies the action class to be executed.

Here the configuration in struts.xml is incomplete, I have just mapped the request to Action
class and we need to map the response from our action class to jsp, once after creating action
class we shall come back to configuring struts.xml again.

Note
In struts.xml we declare a package and wrap the action classes inside.
package name= default? Just give any valid unique name.
struts-default? By default, this package extends from struts-default base package, and it is
nothing but an xml file present in struts2-core-2.x.x.jar
This xml is responsible for invoking series of interceptors which is configured in it. We shall
explore about what is role of this struts-default? and what is interceptors? in our latter part of
our tutorial series. As of now forget about it :P :)

Action class

package com.action;

public class LoginAction {

private String userName;

public String execute() {
if (userName.isEmpty()) {
return "error";
} else {
return "success";
}
}

public String getUserName() {
return userName;
}

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

Now note that the Action Class returns a string, which can be either success or error. In
struts 2, the controller maps the response from action class to a jsp using this string.

Lets assume if Action class return success then we need to map the response to success
page. If Action class returns error then we need to map its response to error.jsp.



Note:
The Action class in struts 2 is not required to implement any interface or extend any class i.e,
can be simple POJO, and there are four different ways to create an Action class which we shall
explore in our upcoming tutorials.
In case of struts 1 Action class used will be extending several classes in turn in order to
process request and response.

Configuring Response struts.xml

Earlier we have configured request flow in struts.xml now we have to configure the response
via result tag in it as shown below.

<?xml version="1.0" encoding="UTF-8" ?>
<!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="login" class="com.action.LoginAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
</package>
</struts>

Jsp pages

Now lets go a head and create jsp pages to receive request and send response back.
Create a new JSP file login.jsp inside the WebContent folder and type in the below code in this
JSP file.

File : login.jsp use the Struts 2 tags to display username input fields and submit button.

File: login.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>Struts 2 Hello World</h3>
<s:form action="login">
<s:textfield name="userName" label="Username" />
<s:submit value="Submit" />
</s:form>
</body>
</html>
In Struts 2, the userName will map to the JavaBean property of Action class automatically. In
this case, on form submit, the textbox value with name=userName will call the corresponding
Actions setUserName(String xx) to set the value
We shall explore different types of tags used in struts 2 in our tutorials.
Also Note that I have referred taglib at the beginning of jsp, By defenision the Struts Taglib
component provides a set of JSP custom tag libraries that help developers create interactive
form-based applications. There are several different tags to help with everything from
displaying error messages to dealing with nested ActionForm beans.

file : success.jsp : A JSP view page to display a welcome message to user.
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
Hello <s:property value="userName" />
</body>
</html>

file :error.jsp : A JSP view page to display error message when a wrong user id and password
is entered.
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h3>Login failed</h3>
</body>
</html>

Configuring web.xml

web.xml is the entry point for any request sent, hence in order to indicate web.xml that this is a
struts2 project, and to indicate that the request and response are handled in struts.xml, we
have to provide any filter entry in web.xml file as shown below.

<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Struts2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecu
teFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

That all on building a struts 2 project, now lets go a head and run this application in TomCat
Server

Demo

Since I have given welcome file to be login.jsp in my web.xml, so on running the application in
tomcat the login.jsp gets rendered as shown below.
Url: http://localhost:8089/HelloWorldStruts2/



When you give a non empty value in userName then success page appears


If you have not entered any value for userName then error page appears as shown below.


In our next article we will learn about the conceptional difference between struts 2 and servlets

Concept of Servlets Vs Concept of Struts 2
Posted by Mohaideen Jamil on Dec 22, 2013 in Java, Servlet, Struts 2 Tutorial, Struts-2 | 2
comments

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.



Recommended Article
Interceptors in Struts 2
Creating Custom Interceptors in Struts2

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.

Roles of Actions class in Struts 2
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments



The functionality of the action class is to retrieve resource bundle, hold the data, provide
validation, perform business logic and select the view result page that should be sent back to
the user.



There are four different ways to write struts 2 action class , which are as follows

1. Action

For Struts 2 actions, it is not mandatory to implement any interface or extend any class. It is
only required to implementexecute() method that returns a string which is to be used
in struts.xml, to indicate the result page that has to be rendered(return)

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

package com.action;
public class LoginAction
{
public String execute()
{
return "success";
}
}

In the struts.xml, configure the action class with action tag and class attribute. Define which
result page should be returned to the user with result tag and the name of the action you can
use to access this action class with name attribute.

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


Now you can access the action via

http://localhost:8089/StrutsLogin/login
Note : To change the extension to any value that suits your need, view Struts2 Custom
extension example.


2. Action interface

The second way of creating Action class on Struts 2 is to implement an optional action
interface (com.opensymphony.xwork2.Action).

This interface , comes with 5 common used constant values : success, error, none, input
and logic. By implements this interface, the action class can use the constant value directly.

The Source code for Action interface :
package com.opensymphony.xwork2;
public interface Action
{
public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public String execute() throws Exception;
}

Example: Struts 2 Action class implementing Action interface

package com.action;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action
{
public String execute()
{
return SUCCESS;
}
}

3. ActionSupport

The third way of creating Action class on Struts 2 is to extend the ActionSupport class
(com.opensymphony.xwork2.ActionSupport). The ActionSupport class is a very powerful
and convenient class that provides default implementation of few of the important interfaces :

public class ActionSupport implements Action, Validateable,
ValidationAware, TextProvider, LocaleProvider, Serializable
{
...
}

Note:
Instead of implementing Action interface, it is better to extend the ActionSupport, Since the
ActionSupport class implements Action interface along with other useful interfaces.


The ActionSupport class give you the ability to do :
1. Validation Declare a validate() method and put the validation code inside.
2. Text localization Use GetText() method to get the message from resource bundle.

LoginAction.properties, (The resource bundle name must be same as Action class name with
the extension .properties), and should be in the same folder where the action class lies

Note :
We will get to know about what is property file and the use of addFiendError , and use of other
functionality like addActionError and addActionMessage in our upcoming tutorials.


Example: Struts 2 Action class extending ActionSupport class

package com.action;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport
{
private static final long serialVersionUID = 6677091252031583948L;
private String userName;

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", getText("username.required"));
}
}
}

** UPDATE: Android Complete tutorial now available here.

4. Action annotation

Struts 2 has very good support for annotations, you can get rid of the XML file and replace
with @action in your action class.

package com.simplecode.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@ResultPath(value="/")
public class LoginAction extends ActionSupport
{
@Action(value="login", results={@Result(name="success",
location="success.jsp")})
public String execute()
{
return SUCCESS;
}
}

Struts2 Configuration file and its roles
Posted by Mohaideen Jamil on Mar 15, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments

Struts 2 application is mainly dependent on two configuration files.
1. web.xml
2. struts.xml




1. web.xml
web.xml is common for all J2EE application and in case of Struts 2, it is used in the
configuration ofStrutsPrepareAndExecuteFilter, TilesListener etc.

When any request comes for struts web application, that request is first handled by web.xml
file, where we do an entry forStrutsPrepareAndExecuteFilter, which dispatch a request object
to appropriate action name.

StrutsPrepareAndExecuteFilter is having following responsibility :
1. Executing struts actions name
2. Cleaning up the ActionContext
3. Serving static content
4. Invoking interceptor chain for the request life-cycle

We are defining StrutsPrepareAndExecuteFilter entry in web.xml as:
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepare
AndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Note : We dont have to do an entry for taglib of struts in web.xml file because its already
included into struts-core.jar file, so container automatically discover it .


Do read :
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2


2. struts.xml
The struts.xml file contains information about all the Action classes of application,
configured interceptors for each Action class, Result for each Action execution. This file also
describes the package structure of the application in which different modules are defined.
Application specific constant like resource file, devMode, custom extension, theme
settings also configured in this file. Below is the sample struts.xml file. All terms will be
explained in their respective article.

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

<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="welcome" class="com.action.LoginAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
</package>
</struts>

Architecture overview of Struts 2 and how it
works
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 6 comments


Struts Execution Flow Diagram



The article Concept of Servlets Vs Concept of Struts 2 helps you in understanding the
concepts of struts 2 better.

Execution flow of struts2

The flow starts with the web browser placing a request for a particular resource. This request is
received by the web container. The container loads web.xml and checks if the url patterns
match. If it matches, the web container transfers the request to Filter Dispatcher.
The Filter Dispatcher decides the suitable action , by calling the ActionMapper , which in turn
calls the ActionProxy. ActionProxy reads the configuration file such as struts.xml, and finds the
suitable action for the request. ActionProxy creates an instance of ActionInvocation class. The
ActionInvocation class invokes the Interceptors one by one (if required).

Do Read
Concept of Interceptors in Struts 2

The Interceptors use the required functions and after that, the Action method executes all the
functions like storing and retrieving data from a database. ActionInvocation receives the final
result produced by an action class.
Once the Action returns, the ActionInvocation is responsible for looking up the proper result
associated with the Action result code mapped in struts.xml. The Interceptors are executed
again in reverse order and the response is returned from ActionProxy to the Filter (In most
cases to FilterDispatcher). FilterDispatcher selects an appropriate view, basing on the result.
The result is then sent to the servlet container which in turn sends it back to the client. Then
the result can be seen on the output of the browser in HTML, PDF, images or any other format.
The other important features of Struts 2 are ValueStack & OGNL. Object-Graph Navigation
Language (OGNL) is a powerful expression language that is used to reference and manipulate
data on the ValueStack. OGNL expression language provides simplified syntax to reference
java objects. It helps in data transfer and type conversion by binding the java-side data
properties to the string-based view layer.




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

In Struts 2 the action resides on the ValueStack which is a part of the ActionContext.
ActionContext is a global storage area that holds all the data associated with the processing of
a request.
When a request comes the param interceptor helps in moving the request data to the
ValueStack. Now the OGNL does the job of converting the string based form data to their
corresponding java types. OGNL does this by using the set of availablebuilt-in type
converters.
Again when the results are generated the OGNL converts the java types of the property on the
ValueStack to the string-based HTML output.Here for N number of request N number of object
is created, this makes the Struts 2 actions thread safe.

The article Servlets Vs Concept of Struts 2 helps you in understanding the concepts of struts 2
better.

DispatchAction Functionality in Struts 2
Posted by Mohaideen Jamil on Sep 12, 2013 in Struts 2 Tutorial, Struts-2 | 10 comments

In Struts 1 DispatchAction helps us in grouping a set of related functions into a single action. In
Struts 2 all the Actions by default provide this functionality. To use this functionality we need to
create different methods with the similar signature of the execute() method.



In our example the CalculatorAction class has all the methods related to a Calculator like add(),
multiply(), division() and subtract() which are used for performing mathematical operation on
two numbers and it displays the result in a single jsp based on the action button clicked in jsp.

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

Action Class

package com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class CalculatorAction implements Action
{
private float number1;
private float number2;
private float result;
private String methodName;

public String execute()
{
number1 = 0;
number2 = 0;
result = 0;
setMethodName("execute Method");
return SUCCESS;
}

public String add()
{
result=number1+number2;
setMethodName("add Method");
return SUCCESS;
}

public String subtract()
{
result = number1 - number2;
setMethodName("subtract Method");
return SUCCESS;
}

public String multiply()
{
result = number1 * number2;
setMethodName("multiply Method");
return SUCCESS;
}

public String divide()
{
if(number2!=0)
result = number1/number2;
else if(number1!=0)
result = number2/number1;
else
result=0;

setMethodName("divide Method");
return SUCCESS;
}

public float getNumber1() {
return number1;
}

public void setNumber1(float number1) {
this.number1 = number1;
}

public float getNumber2() {
return number2;
}

public void setNumber2(float number2) {
this.number2 = number2;
}

public float getResult() {
return result;
}

public void setResult(float result) {
this.result = result;
}

public String getMethodName() {
return methodName;
}

public void setMethodName(String methodName) {
this.methodName = methodName;
}
}

Recommended Article
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Struts 2 using Jquery via Ajax
Tab Style Login and Signup example using jQuery in Java web application

Struts.xml

Here in order to do a DispatchAction functionality we need to create separate action mapping
for each method in the action class, which is done in the struts.xml as shown below.

<?xml version="1.0" encoding="UTF-8" ?>
<!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="Number"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="addNumber" method="add"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="multiplytNumber" method="multiply"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="subtractNumber" method="subtract"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="divideNumber" method="divide"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>

</package>
</struts>

Here note that we use the same action class in all the action mappings but only the method
name differs. So now When the request URL is Number the execute() method in the
CalculatorAction class will be executed. When the request URL is addNumber the add()
method in the CalculatorAction class will be invoked, this is specified using the method
attribute of the action tag in struts xml. Similarly for subtract, multiply and divide request the
subtract() ,multiply() and divide() methods will be invoked respectively.

This way configuring a separate action mapping for each method of same action class can be
avoided by using a feature called Dynamic Method Invocation. We will learn about this in our
upcoming tutorial.

Jsp

In the curd.jsp page we create five different buttons to invoke the different methods in the
CalculatorAction class.

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Dispatch Action</title>
</head>
<body>
<s:form action="Number">
<table>
<tr><td><s:textfield name="number1" label="Number 1 "
id="number1"/></td></tr>
<tr><td><s:textfield name="number2" label="Number 2 "
id="number2"/></td></tr>
<tr><td><s:textfield name="result" label="Result "
readonly="true" /></td></tr>
<tr>
<td><s:textfield name="methodName" label="Method involked "
readonly="true" /></td>
</tr>
<tr>
<td><s:submit action="addNumber" value="Add"
align="left"/></td>
<td><s:submit action="subtractNumber" value="Subtract"
align="left"/></td>
<td><s:submit action="divideNumber" value="Divide"
align="left"/></td>
<td><s:submit action="multiplytNumber" value="Multiply"
align="left"/></td>
<td><s:submit align="left"/></td>
</tr>
</table>
</s:form>
</body>
</html>

On running the example the following page will be displayed in the browser. Now when the
user click a button the appropriate method in the CalculatorAction class gets invoked.



For example When the user clicks the add button the add() method in the CalculatorAction
class gets executed and the following page is displayed.



Note: Dispatch action functionality is used when you have multiple submit buttons in a single
form.


Zip file DispatchAction.zip
War file DispatchAction.war


Struts 2 Dynamic Method Invocation using
Action Wildcards
Posted by Mohaideen Jamil on Sep 21, 2013 in Struts 2 Tutorial, Struts-2 | 2 comments

This tutorial is a continuation of previous example ( DispatchAction functionality ). In this
example you will see about avoiding configuration of separate action mapping for each method
in Action class by using the wildcard method. Look at the following action mapping to under
stand the concept.

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

Action mapping From previous example

<struts>

<package name="default" extends="struts-default">

<action name="Number"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="addNumber" method="add"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="multiplytNumber" method="multiply"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="subtractNumber" method="subtract"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
<action name="divideNumber" method="divide"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>

</package>
</struts>

Action mapping Using Wildcard

<struts>
<package name="default" extends="struts-default">
<action name="*Number" method="{1}"
class="com.simplecode.action.CalculatorAction">
<result name="success">/curd.jsp</result>
</action>
</package>
</struts>

As you can see we have replaced all the method names with an asterisk(*) symbol. The word
that matches for the first asterisk will be substituted for the method attribute. So when the
request URL is divideNumber the divide() method in the CalculatorAction class will be
invoked.

Do read :
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Note :

1. We can also substitute asterisk in the jsp pages.
For example


<action name="*Number" method="{1}">
<result name="success">/{1}curd.jsp</result>
</action>

2. The wild card can be placed in any position in a action name
For example

<action name="Number*" method="{1}">
<result name="success">/{1}curd.jsp</result>
</action>

3. You can have multiple wild card , for example

<action name="*Number*" method="{1}">
<result name="success">/{1}curd{2}.jsp</result>
</action>

To match first wildcard, we have to use {1}, to match second wild card we have to use {2}.


War file Dynamic Method Invocation.war
Zip file Dynamic Method Invocation.zip

ActionError & ActionMessage Example in Struts
2
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 1, Struts 2 Tutorial, Struts-2 | 1 comment

In this tutorial we will learn about ActionError & ActionMessage class and its usage.



a) ActionError class is used to send error feedback message to user and it get rendered in
jsp by using <s:actionerror/> tag.

b) ActionMessage class is used to send information feedback message to user, and it get
rendered in jsp using<s:actionmessage/> tag.

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

In this tutorial we will use the previous tutorials example to implement the functionality
of ActionError and ActionMessageclass.



Heres a simple login form, display the error message (actionerror) if the username is empty,
Otherwise redirect to another page and display the a welcome message (actionmessage).

1. Folder Structure



Action Class

The action class, do a simple checking to make sure that the username is not empty, if the
userName is not valid then the action class set the error message with addActionError() , if its
valid then it set the successful message withaddActionMessage().

package com.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID =
6677091252031583948L;

private String userName;

public String execute() {

return SUCCESS;
}

public String getUserName() {
return userName;
}

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

public void validate() {
if (userName.isEmpty()) {
addActionError("Username can't be blanked");
} else {
addActionMessage("Welcome " + userName + ", You have
been Successfully Logged in");
}
}
}

You might be interested to read:
jQuery form validation using jQuery Validation plugin
FieldError in Struts 2 Example

JSP

Two simple JSP pages with css style to customize the error message.

login.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>ActionError &amp; ActionMessage Example</h3>
<s:actionerror />
<s:form action="loginUser">
<s:textfield name="userName" placeholder="Username"
label="Username" />
<s:submit value="Submit" />
</s:form>
</body>
</html>

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>

struts.xml

The mapping in struts.xml should be as below
<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>

Run it

http://localhost:8089/ActionErrorMessage/


When Username is invalid, display error message with <s:actionerror/>



When Username is valid, display welcome message <s:actionmessage/>



Note:

In struts 2 when you use <s:actionerror /> tag, it displays the errors with bullets, read the article
on Change default style of s:actionerror / s:actionmessage tag in order to remove this

FieldError in Struts 2 Example
Posted by Mohaideen Jamil on Aug 14, 2014 in Struts 2 Tutorial, Struts-2 | 6 comments



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
Interceptors in Struts 2
Exception handling in Struts 2

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:
jQuery form validation using jQuery Validation plugin
ActionError & ActionMessage Example in Struts 2

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

Struts 2 Namespace Configuration
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments


Struts 2 Namespace is a new concept to handle the multiple modules by giving a namespace
to each module

The namespace attribute of element in struts.xml is an optional attribute. The default
namespace is . i.e. an empty string.
The value of your namespace must always begin with a /.
Namespaces are used to group together a set of actions.
An action with the same name can exist in several namespaces. The action that will be invoked
depends upon the namespace in which it is called.

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

See this picture to understand how an URL matches to Struts 2 action namespace.



1. Final project structure



2. Namespace configuration

Let us go through a Struts 2 namespace configuration example to know how it matches with
URL and folder.

Note :
The package name will not affect the result, just give a meaningful name.


File:struts.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration
2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

<package name="default" namespace="/" extends="struts-
default">
<action name="default">
<result>jsp/home.jsp</result>
</action>
</package>

<package name="staff" namespace="/staff" extends="struts-
default">
<action name="Staff">
<result>/jsp/staff.jsp</result>
</action>
</package>

<package name="student" namespace="/student" extends="struts-
default">
<action name="Student">
<result>/jsp/student.jsp</result>
</action>
</package>

</struts>

3. JSP Pages

File:home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h2> Welcome user</h2>
</body>
</html>

File:Staff.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Staff home page</title>
</head>
<body>
<h2>Welcome staff</h2>
</body>
</html>

File:Student.jsp


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

<head>
<title>Student home page</title>
</head>
<body>
<h2>Welcome Student</h2>
</body>

</html>

4. Mapping - How it works?

Example 1

The URL : http://localhost:8089/Name_Space/student/Student.action
.
Will match the root namespace, and display the content of WebContent/jsp/student.jsp.
<package name="student" namespace="/student" extends="struts-
default">
<action name="Student">
<result>/jsp/student.jsp</result>
</action>
</package>

Example 2

URL : http://localhost:8089/Name_Space/staff/Staff.action
Will match the common namespace, and display the content of WebContent/jsp/staff.jsp
<package name="staff" namespace="/staff" extends="struts-default">
<action name="Staff">
<result>/jsp/staff.jsp</result>
</action>
</package>

Example 3

URL : http://localhost:8089/Name_Space/default
Will match the common namespace, and display the content of WebContent/jsp/home.jsp.
<package name="default" namespace="/" extends="struts-default">
<action name="default">
<result>jsp/home.jsp</result>
</action>
</package>

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

Note :
Given below is the genaralised url
Http://<server>:<port>/<webapp>/<namespace>/<action>.action




Struts 2- Include multiple Struts configuration
files
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments


Struts 2 comes with include file- feature to include multiple Struts configuration files
into a single unit.

Single Struts configuration file

Bad way of Struts 2 configuration example (From Previous Example).

File:struts.xml

<struts>

<package name="default" namespace="/" extends="struts-
default">
<action name="default">
<result>jsp/home.jsp</result>
</action>
</package>

<package name="staff" namespace="/staff" extends="struts-
default">
<action name="Staff">
<result>/jsp/staff.jsp</result>
</action>
</package>

<package name="student" namespace="/student" extends="struts-
default">
<action name="Student">
<result>/jsp/student.jsp</result>
</action>
</package>

</struts>

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

In the above Struts configuration file, it groups all the -student and staff-
settings in a single file, which is not recommended and MUST BE AVOID. You should break
this struts.xml file into smaller module related pieces. Multiple Struts configuration files In
Struts 2, you should always assign each module a struts configuration file. In this case, you
can create three files :

1. student.xml - Put all student module settings here.
2. staff.xml - Put all staff modules settings here.
3. struts.xml - Put default settings and include the staff.xml and student.xml.

File:student.xml - Put all student module settings here.

<struts>
<package name="student" extends="struts-default">
<action name="Student">
<result>/jsp/student.jsp</result>
</action>
</package>
</struts>

File: Staff.xml Put all staff modules settings here.

<struts>
<package name="staff" extends="struts-default">
<action name="Staff">
<result>/jsp/staff.jsp</result>
</action>
</package>
</struts>

File: Struts.xml Put default settings and include the staff.xml and student.xml

<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true"
/>

<package name="default" namespace="/" extends="struts-
default">
<action name="default">
<result>jsp/home.jsp</result>
</action>
</package>

<include file="student.xml"/>
<include file="staff.xml"/>

</struts>

Final project structure





Remove .action extension in struts2 and to give
user defined extension
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments


In Older version of Struts 2, all action class by default has .action as extension,

For example, by default to access an action say LoginAction class, we will use the
following URL

Action URL: http://localhost:8089/Struts2/Login.action

In its latest version i.e version after 2.2.x by default action class has no extension, in this case
the default wat to access an action is

Action URL: http://localhost:8089/Struts2/Login

This article aims to change this default extension.

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

So in order to remove or to give any user defined extension, just declare a
constant struts.action.extension in struts.xml and set the value to the extension you
wish.

For example to change the extension from .action to .jsp, the following code is used.
<constant name="struts.action.extension" value="jsp"/>

Output URL will be shown like this:-

Action URL: http://localhost:8089/Struts2/Login.jsp

Suppose If you want to shown empty extension URL try this:-
<constant name="struts.action.extension" value=""/>

Output URL will be shown like this:-

Action URL: http://localhost:8089/Struts2/Login

Hope This Help You :)

Article to read Next:
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Struts 2 Development Mode Example
Posted by Mohaideen Jamil on Mar 27, 2013 in Struts 2 Tutorial | 1 comment


Struts 2 has a setting which can be set to true or false in struts.properties called devMode.
When this setting is enabled, Struts 2 will provide additional logging and debug information,
which can significantly speed up development.

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

Enable the Strut2 development mode

Set the struts.devMode value to true, either in Struts properties file or XML
configuration file.

struts.properties
struts.devMode = true

struts.xml
<struts>
<constant name="struts.devMode" value="true" />
</struts>

Note :

1.By default, the development mode is disabled, because it has a significant impact on
performance, since the entire configuration will be reloaded on every request.

2. The development mode is only suitable in development or debugging environment. In
production environment, you have to disable it. As It will caused significant impact on
performance, because the entire application configuration, properties files will be reloaded on
every request, many extra logging and debug information will be provide also.

Do read :
How to Debug a java application in Eclipse

Disable the Strut2 development mode

Set the struts.devMode to false, either in Struts properties file or XML configuration
file.
struts.properties
struts.devMode = false

struts.xml

<struts>
<constant name="struts.devMode" value="false" />
</struts>

Reference
Struts 2 development mode documentation


How to use a JavaBean class as a property in
struts 2 action class.
Posted by Mohaideen Jamil on Feb 24, 2014 in Struts-2 | 0 comments


In this tutorial we will learn how to use a JavaBean class as a property in struts 2 action.

Consider a scenario, in which you have written an action class, which in turn has a JavaBean
class as its property as shown below.

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

Action class

HelloAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.Action;
import com.simplecode.bo.User;

public class HelloAction implements Action
{
private User user;

public User getUser()
{
return user;
}

public void setUser(User user)
{
this.user = user;
}

public String execute()
{
if (getUser().getUserName().isEmpty())
return ERROR;
else
return SUCCESS;
}
}

Transferring the JavaBeans property values to Action
class

In Struts 2 transferring of data to the Java bean object is automatically done by the params
interceptor, all we have to do is to create a JavaBeans object and its corresponding getter and
setter methods in the action class.

Retrieving the JavaBeans property from action class to
Jsp

To refer the attributes of User class, we need to first get the User object and then access its
properties. For example to access the Users, userName attribute in the Action class, the
following syntax is used.

getUser().getUserName();

JavaBean class

User.java

package com.simplecode.bo;

public class User
{
private String userName;

public String getUserName()
{
return userName;
}

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

JSP

In jsp page the user attributes cannot be directly referenced. Since the attributes we refer in the
jsp page belongs to the User object (JavaBean object) we need to go one level deeper to
reference the attributes. To refer the userName attribute of User class, the value of the name
attribute in the s:property tag should be

"user.userName"

login.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>Struts 2 JavaBeans as property</h3>

<s:form action="hello">
<s:textfield name="user.userName" label="User
name"/>
<s:submit name="submit" />
</s:form>
</body>
</html>

success.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
Welcome, <s:property value="user.userName" />
</body>
</html>

error.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Error Page</title>
</head>
<body>
Login failed! Please enter a valid user name
</body>
</html>

Demo

http://localhost:8089/JavaBean/


On entering the details and clicking the Submit button the following page will be dispalyed.



In struts 2 there is a concept call Model objects, using which we can refer to the JavaBean
objects attributes directly, instead of doing a deeper reference as shown in this example above.
In our next article we will learn about struts 2 Model Objects which simplifies the amount of
code written above via ModelDriven interface


Zip file JavaBean.zip



ModelDriven Interceptors in Struts 2
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


In our last article we have learned how to use a JavaBean class as a property in struts 2
action.

In this tutorial we will learn about Struts 2 support for model objects.

The Model object is a simple JavaBean object, which will be available to action class directly
from ValueStack,
i.e we dont need to do deeper referencing to refer its attribute(JavaBeans attribute).

To make a JavaBean object as a model object, our Action class should implement
ModelDriven interface which forces the getModel() method to be implemented. This method
provides the model object to be pushed into the Value Stack.

Here the getModel() must be invoked earlier for populating its input properties with data from
request parameters,
To make sure that the model is available in Value Stack when input parameters are being set,
the ModelDrivenInterceptor is configured for the Action in struts.xml.

Most Popular Article for Reference
AJAX implementation in Struts 2 without JQuery
AJAX implementation in Struts 2 using JQuery and JSON

Since the ModelDriven interceptor is already included in the default stack, we dont need to
inculde modelDriven interceptor explicitly.

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

Lets see a sample example of POJO form, which can be injected in the action as its model.

Bean Class(Model Class)

File : User.java

package com.simplecode.bo;

public class User
{
private String userName;

public String getUserName()
{
return userName;
}

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

Action Class

Action class implements the ModelDriven interface, declared the getModel() method to
return the users object. When the form data is submitted to this action, it will transfers the
form data into the user properties automatically.

File : HelloAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
import com.simplecode.bo.User;

public class HelloAction implements Action,ModelDriven<User>
{
// Need to initialize model object
private User user = new User();

public String execute()
{
if (user.getUserName().isEmpty())
return ERROR;
else
return SUCCESS;
}

public User getModel() {
return user;
}
}

Note:
1. Since the model object to be pushed into ValueStack must not be null hence model must be
initialized before returned by getModel() method.
2. We can use only one model object per action class

Do read :
Difference between Action Chaining & Action redirect in Struts 2
GridView in struts 2 using jQuery DataTable plugin
Autocomplete in Struts 2 using Jquery via Ajax

JSP page

JSP pages for the ModelDriven demonstration.

login.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>Struts 2 ModelDriven Example</h3>

<s:form action="hello">
<s:textfield name="userName" label="User name"/>
<s:submit name="submit" />
</s:form>
</body>
</html>

success.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
Welcome, <s:property value="userName" />
</body>
</html>

error.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Error Page</title>
</head>
<body>
Login failed! Please enter a valid user name
</body>
</html>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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="hello"
class="com.simplecode.action.HelloAction">
<result
name="success">/jsp/success.jsp</result>
<result name="error">/jsp/error.jsp</result>
</action>
</package>
</struts>

Demo

http://localhost:8089/ModelDriven/


When I enter a non empty value in the textbox and press submit button, then the application
redirects to success page as shown.


On Clicking submit button without any value in textbox, then the application redirects to error
page as shown.


File Upload Example in Struts 2
Posted by Mohaideen Jamil on Nov 18, 2012 in Struts 2 Tutorial, Struts-2 | 1 comment


In Struts 2 file uploading can done with the help of built-in FileUploadInterceptor. We
use <s:file> tag to create a file upload component, which allow users to select file from their
local disk and upload it to the server. The encoding type of the form should be set to
multipart/form-data and the HTTP method should be set to post. The Struts 2 File
UploadInterceptor is based on MultiPartRequestWrapper, which is automatically applied to the
request if it contains the file element. Then it adds the following parameters to the request

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

(assuming the uploaded file name is uploadDoc).
[uploadDoc]File Will store the actual uploaded File
[uploadDoc]ContentType : This String will store the content type of the file
[uploadDoc]FileName : This String will store the actual name of the uploaded file (not the
HTML name)
In the action class you can get the file, the uploaded file name and content type by just creating
getter and setters.

For example
private File uploadDoc;
This will store actual uploaded File
private String uploadDocFileName;
This string will contain the file name of uploaded file.
private String uploadDocContentType;
This string will contain the Content Type of uploaded file.

The file upload interceptor also does the validation and adds errors. These error messages are
stored in the struts-messsages.properties file. The values of the messages can be overridden
by providing the text for the following keys:

struts.messages.error.uploading error when uploading of file fails
struts.messages.error.file.too.large error occurs when file size is large
struts.messages.error.content.type.not.allowed when the content type is not allowed


Do read :
AJAX style File Upload in Java Web Application using jQuery
Creating Custom Interceptors in Struts2

Parameters

You can use the following parameters to control the file upload functionality.
maximumSize This parameter is optional. The default value of this is 2MB.
Example:
<param name="maximumSize">1024000</param>

Note:
You can also set the upload file size using the following code
<constant name="struts.multipart.maxSize" value="20097152" />
allowedTypes This parameter is also optional. It allows you to specify the allowed content
type.
Note:
To upload txt file

<param name="allowedTypes"> text/plain </param>
To upload PDF files

<param name="allowedTypes"> application/pdf</param>

Recommended reading
Struts 2 File Download Example

Folder Structure



Action class

FileUploadAction.java

package com.simplecode.action;

import java.io.File;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private File uploadDoc;
private String uploadDocFileName;
private String uploadDocContentType;

public String execute() {
return SUCCESS;
}

public File getUploadDoc() {
return uploadDoc;
}

public void setUploadDoc(File uploadDoc) {
this.uploadDoc = uploadDoc;
}

public String getUploadDocFileName() {
return uploadDocFileName;
}

public void setUploadDocFileName(String uploadDocFileName) {
this.uploadDocFileName = uploadDocFileName;
}

public String getUploadDocContentType() {
return uploadDocContentType;
}

public void setUploadDocContentType(String
uploadDocContentType) {
this.uploadDocContentType = uploadDocContentType;
}
}


JSP Page

fileupload.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>file upload page</title>
</head>
<body>
<h3>Struts 2 file upload example</h3>
<s:form action="fileUpload" method="post"
enctype="multipart/form-data">
<s:file name="uploadDoc" label="Choose file to upload" />
<s:submit value="upload" align="center" />
</s:form>
</body>
</html>

uploadSuccess.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Upload Successful</title>
<s:head />
</head>
<body>

<h3>Struts 2 file upload example</h3>
File Name : <s:property value="uploadDocFileName"></s:property><br
/>
Content type: <s:property
value="uploadDocContentType"></s:property><br />
User file : <s:property value="uploadDoc"></s:property>
</body>
</html>

struts.xml

Make sure you have done action mapping properly in struts.xml file. An example of this is given
below,
<struts>
<package name="" namespace="/jsp" extends="struts-default">
<action name="fileUpload"
class="com.simplecode.action.FileUploadAction" >
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="fileUpload">
<param name="maximumSize">1024000</param>
<param name="allowedTypes">application/pdf</param>
</interceptor-ref>
<interceptor-ref name="validation">
<param
name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param
name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<result name="success">/jsp/uploadSuccess.jsp</result>
<result name="input">/jsp/fileUpload.jsp</result>
</action>
</package>

</struts>

Demo

http://localhost:8089/Struts2_FileUpload/


Error message prompts if you upload a file which is more than 10kb, or not a text file.



The uploaded file will be treat as a temporary file, with a long random file name,
upload__376584a7_12981122379__8000_00000010.tmp. This file will be stored some where
in the metadata directory



Note:
In order to save the .tmp file in a desired location ,which you wish , then use the following code
in yourstruts.xml

<constant name="struts.multipart.saveDir" value="D:/your folder"/>


To more about overriding these default file upload error message, click on- Override struts 2.x
file upload messages


Caution :

The problem with above code snippet is, you cannot see the uploaded file in the target folder.
Also the file uploaded wont have any proper extension, instead it will have the extension as
.tmp.

Struts 2 Upload File to Desire Folder Location

So in-order to upload and save a file in target space and in-order to have a file with proper
extension, i.e .pdf , .doc etc, we should use the following code snippet in the action classs
execute method.

Modified execute method

public String execute()
{
// Location to store the uploaded file in our desired path
String targetPath = "D:/file target/";
File fileToCreate = new File(targetPath, uploadDocFileName);
try
{
FileUtils.copyFile(this.uploadDoc, fileToCreate);
}
catch (IOException e)
{
addActionError(e.getMessage());
}
return SUCCESS;
}


Zip file FileUpload.zip
War file FileUpload.war



How to override struts 2.x file upload error
messages?
Posted by Mohaideen Jamil on Sep 28, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


In my previous tutorial I have explained about how to upload file in struts 2 web application.
This article aims at overriding the default file upload error message which are added by file
upload interceptor during file upload validation. These error messages are stored in the struts-
messsages.properties file. The values of the messages can be overridden by providing the text
for the following keys:

struts.messages.error.uploading - error when uploading of file fails
struts.messages.error.file.too.large - error occurs when file size is
large
struts.messages.error.content.type.not.allowed - when the content
type is not allowed
struts.messages.error.file.extension.not.allowed - when the file
extension is not allowed

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

In-order to override these message, you need follow the below steps.

1. Create a global.properties file in the src folder and add the following test to your
global.properties file:

struts.messages.error.file.too.large = Uploaded File size is too
large
struts.messages.error.uploading = File upload failed
struts.messages.error.content.type.not.allowed =File type is not
allowed.
struts.messages.error.file.extension.not.allowed =File extension is
not allowed.

2. Add the constant In struts.xml:

<constant name="struts.custom.i18n.resources" value="global" />

After implementing these changes restart the application, and now in case of error in
validation you get the custom error message which we have written in the properties
file.

File Download Example in Struts 2
Posted by Mohaideen Jamil on Sep 29, 2013 in Struts 2 Tutorial, Struts-2 | 2 comments


This tutorial will help you understanding how to create a Struts 2 action class that allows users
to download files from server to their local computer.

struts.xml

Struts 2 provides a custom result type called stream that performs file download by
streaming an InputStream of a file to the client through the HttpServletResponse. Heres an
example that shows how to define this result type element in struts.xml:

The struts.xml file should have the following mapping
<struts>
<package name="default" namespace="/jsp" extends="struts-default">

<action name="download"
class="com.simplecode.action.DownloadAction">
<result name="success" type="stream">
<param
name="contentDisposition">attachment;filename=${fileName}</param>
<param name="contentType">application/vnd.ms-
excel</param>
<param name="inputName">fileInputStream</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>

Note that we declare a property placeholder called fileName which will be dynamically
updated by Struts. Now in the action class, we need to declare a variable with the same name
along with getter and setter method. By this way we have configured the download file name
dynamically.

In addition to that, we must define an InputStream object which has the same name as the
name specified by the inputName parameter in struts.xml. All the variables must have
appropriate getter methods.

Recommended Article
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Struts 2 using Jquery via Ajax
Tab Style Login and Signup example using jQuery in Java web application

Action Class

package com.simplecode.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.Action;

public class DownloadAction implements Action
{
private InputStream fileInputStream;
// Used to set file name dynamically
private String fileName;

public InputStream getFileInputStream()
{
return fileInputStream;
}

public String execute() throws Exception
{
File fileToDownload = new
File("C:/Download/MyFile.xls");
fileName = fileToDownload.getName();
fileInputStream = new
FileInputStream(fileToDownload);
return SUCCESS;
}

public String getFileName()
{
return fileName;
}

public void setFileName(String fileName)
{
this.fileName = fileName;
}
}

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

Jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<title>File Download</title>
<body>
<h3>Struts 2 file download example</h3>
<s:url id="fileDownload" namespace="/jsp"
action="download"></s:url>
<h4>
Download file - <s:a href="%{fileDownload}">MyFile.xls</s:a>
</h4>
</body>
</html>

Related Article
File Upload Example in Struts 2
Demo


On running this application



Struts 2 <s:textfield> example
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments


In Struts 2 , you can use the <s:textfield> to create a HTML input textbox. For example, you
can declare the s:textfield with a key attribute or label and name attribute.

<s:textfield key="userName" />
//or
<s:textfield label="Username" name="userName" />

In Struts 2, the name will map to the JavaBean property automatically. In this case, on
form submit, the textbox value with name=userName will call the corresponding
Actions setUsername(String xx) to set the value

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

Struts 2 <s:textfield> example

1. Properties file

Two properties files to store the message.

project.properties
project.username = Username
project.submit = Submit

LoginAction.properties
username.required = Username Cannot be blank

2. Action

A simple Action class with a validation to make sure the username is not empty, otherwise
return an error message.

LoginAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID =
6677091252031583948L;

// Need to Initiize a morden driven object
private String userName;
private String password;

public String getUserName() {
return userName;
}

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

public String getPassword() {
return password;
}

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

public String execute() {

return SUCCESS;
}

public void validate() {
if (userName.equals("")) {
addFieldError("userName",
getText("username.required"));
}
}
}

3. View page

Result page to use Struts 2 s:textfield to create a HTML textbox input field.

login.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Login</title>
</head>
<body>
<h3>Struts 2 &lt; S:textfield &gt; Textbox Examplee</h3>
<s:form action="welcome">
<s:textfield name="userName" key="project.username"
/>
<s:submit key="project.submit" name="submit" />
</s:form>
</body>
</html>

success.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
<h3>Struts 2 &lt; S:textfield &gt; Textbox Example</h3>
<h4>
Welcome <s:property value="userName" />
</h4>
</body>
</html>

4. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

<constant name="struts.custom.i18n.resources" value="project" />
<package name="default" extends="struts-default"
namespace="/jsp">
<action name="Login">
<result>/jsp/login.jsp</result>
</action>
<action name="welcome"
class="com.simplecode.action.LoginAction">
<result
name="success">/jsp/success.jsp</result>
<result name="input">/jsp/login.jsp</result>
</action>
</package>
</struts>

5. Demo

http://localhost:8089/Struts2_textfield/




Download It -
Struts2_textfield.zip
Struts2_Textbox.war


Struts 2 <s:password> example
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments



Download It -
Struts2-Password-Example without Library files
Struts2-Password-Example with Library files (war)



In Struts 2 , you can use the <s:password> to create a HTML password field. For example,
you can declare the s:password with a key attribute or label and name attribute.

<s:password key="password" />
//or
<s:textfield label="Password" name="password" />

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

In Struts 2, the name will map to the JavaBean property automatically. In this case, on
form submit, the textbox value with name=password will call the corresponds
Actions setPassword(String xx) to set the value
Struts 2 <s:password> example

A page with password and confirm password fields, and do the validation to
make sure the confirm password is match with the password.

1. Properties file

Two properties files to store the message.
project.properties

project.username = Username
project.password= Password
project.submit = Login
LoginAction.properties
username.required = Username Cannot be blank
password.required = Password Cannot be blank

2. Action

LoginAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private String userName;
private String password;

public String getUserName() {
return userName;
}

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

public String getPassword() {
return password;
}

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

public String execute() {

return SUCCESS;
}

public void validate() {
if (userName.equals("")) {
addFieldError("userName",
getText("username.required"));
}
if (password.equals("")) {
addFieldError("password",
getText("password.required"));
}
}
}

3. View page

Result page with Struts 2 s:password tag to create a HTML password field.
login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Login</title>
</head>
<body>
<h3>Struts 2 &lt; s:password &gt; Example</h3>

<s:form action="welcome">
<s:textfield name="userName" key="project.username"
/>
<s:password name="password" key="project.password" />
<s:submit key="project.submit" name="submit" />
</s:form>
</body>
</html>

success.jsp

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

<body>
<h3>Struts 2 &lt; s:password &gt; Textbox Examplee</h3>
<h4>
Username : <s:property value="userName" /><br/>
Password : <s:property value = "password"/>
</h4>
</body>
</html>

4. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

<constant name="struts.custom.i18n.resources" value="project"
/>
<package name="default" extends="struts-default"
namespace="/jsp">
<action name="Login">
<result>/jsp/login.jsp</result>
</action>
<action name="welcome"
class="com.simplecode.action.LoginAction">
<result
name="success">/jsp/success.jsp</result>
<result name="input">/jsp/login.jsp</result>
</action>
</package>
</struts>

5. Demo


http://localhost:8089/Struts2_password/





Download It -
Struts2-Password-Example without Library files
Struts2-Password-Example with Library files (war)


Struts 2 <s:hidden> example
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 2 comments



Download It -
Struts2_hidden.zip
Struts2_hidden.war



In Struts 2 , you can use the <s:hidden> tag to create a HTML hidden field.

<s:hidden name="hiddenValue" value="simplecodestuffs" />

It will render as the following HTML code.

<input type="hidden" name="hiddenValue" value="simplecodestuffs" />

Struts 2 <s:hidden> example

A page with a url hidden value, and display the hidden value after form is submitted.

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

1. Folder Structure :



2. Action class

HiddenAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class HiddenAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private String hiddenValue;

public String getHiddenValue() {
return hiddenValue;
}

public void setHiddenValue(String hiddenValue) {
this.hiddenValue = hiddenValue;
}

public String execute() {
return SUCCESS;
}

}

3. JSP View page

Struts 2 s:hidden tag to create a hidden value field.
hidden.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Hidden</title>
</head>
<body>
<h3>Struts 2 - &lt;s:hidden&gt; tag example</h3>
This page has a hidden value (view source):
<s:form action="Hidden">
<h4>

<s:hidden name="hiddenValue"
value="simplecodestuffs" />
<s:submit key="project.submit" name="submit"
/>
</h4>
</s:form>
</body>
</html>


success.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
<h3>Struts 2 - &lt;s:hidden&gt; tag example</h3>

The hidden value :
<s:property value="hiddenValue" />

</body>
</html>

4. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

<constant name="struts.custom.i18n.resources" value="project"
/>
<package name="default" extends="struts-default"
namespace="/jsp">
<action name="Hiddenjsp">
<result>/jsp/hidden.jsp</result>
</action>
<action name="Hidden"
class="com.simplecode.action.HiddenAction">
<result
name="success">/jsp/success.jsp</result>
<result name="input">/jsp/hidden.jsp</result>
</action>
</package>
</struts>

5. Demo

http://localhost:8089/Struts2_hidden/jsp/Hiddenjsp




Output :





Download It -
Struts2_hidden.zip
Struts 2_hidden.war

Struts 2 <S:textarea> example
Posted by Mohaideen Jamil on Apr 18, 2013 in Struts 2 Tutorial | 0 comments



Download It -
Struts2_Textarea-Example without Library files
Struts2_Textarea-Example with Library files (war)



In Struts 2 , you can use the <s:textarea> to create a HTML textarea field.

Example:
<s:textarea label="Address" name="address" cols="50" rows="10"/>

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

Struts 2 <s:textarea> example
A page contains address textarea field, and displays the textarea value after the form is
submitted.
1. Action class

TextAreaAction.java

package com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class TextAreaAction extends ActionSupport{

private static final long serialVersionUID = 1L;
private String address;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String execute() {
return SUCCESS;
}

}

2. View page

Struts 2 s:textarea tag to create a textarea field.

textarea.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Text area</title>
</head>

<body>
<h2>Struts 2 - &lt;s:textarea&gt; example</h2>

<s:form action="helloTextarea" namespace="/">

<s:textarea label="Address" name="address" cols="50"
rows="10" />
<s:submit value="submit" name="submit" />

</s:form>

</body>
</html>

result.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<title>Text area</title>
<body>
<h2>Struts 2 - &lt;s:textarea&gt; example</h2>

<s:property value="address" />

</body>
</html>

3. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.devMode" value="true" />

<package name="textarea" namespace="/jsp" extends="struts-
default">
<action name="textarea">
<result>/jsp/textarea.jsp</result>
</action>
<action name="helloTextarea"
class="com.simplecode.action.TextAreaAction">
<result name="success">/jsp/result.jsp</result>
</action>
</package>

</struts>

4. Demo


http://localhost:8089/Struts2_Textarea/jsp/textarea






Download It -
Struts2_Textarea-Example without Library files
Struts2_Textarea-Example with Library files (war)


Handling double form submissions in Struts2
Posted by Mohaideen Jamil on Apr 12, 2013 in Struts-2 | 2 comments


Double form submissions(either by refreshing or by hitting the browser back button) can be
irritating and in some cases leads to big problem .Luckly struts2 has a build in functionality that
prevents such scenarios :<s:token/> tag and token interceptor. As an example, lets say
that we have a form that looks like this:

<s:form action="someAction">
<s:textfield key="key"/>
<s:textfield key="otherKey"/>
<s:textfield key="someOtherKey"/>
<s:submit/>
</s:form>

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

In order to prevent double submissions all we have to do is to add tag in the above form. This
tag will add a unique identifier in the form that will be used later from the token interceptor in
order to check if the form is submitted for the first time or not. In case the form is not submitted
for the first time, interceptors result will be invalid.token.

<action name="actionClass" class="com.simplecode.actionClass">
<interceptor-ref name="token"/>
<interceptor-ref name="defaultStack"/>
<result name="input">/inputPage.jsp</result>
<result name="invalid.token">/invalidToken.jsp</result>
<result name="success">/successPage.jsp</result>
</action>
Note that invalid.token result in the above action declaration actually means that in the case
of invalid token the user should be redirected in invalidToken.jsp

Struts 2 <s:head> example
Posted by Mohaideen Jamil on Mar 27, 2013 in Struts 2 Tutorial | 0 comments


The <s:head /> tag should be placed in the headsection of the HTML page. The s:head tag
automatically generates links to the css and javascript libraries that are necessary to render the
form elements.
This tag is used to output the HTML head information like encoding, CSS or JavaScript file.
See the following snippet

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

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

Here Since no theame is provided in <s:head> tag ,it uses the default xhtml theme, it will
render the output according to the template\xhtml\head.ftl file as shown below

<html>
<head>
<link rel="stylesheet" href="/your_project/struts/xhtml/styles.css"
type="text/css"/>
<script src="/your_project/struts/utils.js"
type="text/javascript"></script>
</head>

To include your own user defiend js or css file, just add it into the
template\xhtml\head.ftl template file, and output it via<s:head>tag
The tag also includes the option to set a custom datepicker theme if needed.


<head>
<title>My page</title>
<s:head theme="ajax" calendarcss="calendar-green"/>
</head>

If you use the ajax theme you can turn a debug flag by setting the debug parameter to true.

<head>
<title>My page</title>
<s:head theme="ajax" debug="true"/>
</head>

Struts 2 datetimepicker example
Posted by Mohaideen Jamil on Mar 27, 2013 in Struts 2 Tutorial, Struts-2 | 3 comments



Zip file Date Picker.zip
War file Date Picker.war



Click here to learn about Datetime picker in struts 2 using jquery jar

To create a date time pick component in struts 2, please follow this two steps :

1. Add struts2-dojo-plugin.jar in your class path.
2. Include the struts-dojo-tags tag and its header in your jsp page

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

<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>

Recommended Article
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Struts 2 using Jquery via Ajax

Action class

DatePickerAction.java

package com.simplecode.action;

import java.util.Date;

import com.opensymphony.xwork2.Action;

public class DatePickerAction implements Action
{
private Date birthDay;

public Date getBirthDay()
{
return birthDay;
}

public void setBirthDay(Date birthDay)
{
this.birthDay = birthDay;
}

public String execute() throws Exception
{
return SUCCESS;
}
}

JSP Page

datepicker.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title>Date Picker</title>
<sx:head />
</head>
<body>
<h3>Struts2 Date Picker example</h3>
<s:form action="resultAction">
<sx:datetimepicker name="birthDay" label="Format (dd-MM-yyyy)"
displayFormat="dd-MM-yyyy" required="true" />
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>

result.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Date Picker Result</title>
</head>
<body>
<h3>Struts2 Date Picker example</h3>
Birthday : <s:property value="birthDay" />
</body>
</html>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="" namespace="/jsp" extends="struts-default">
<action name="dateTimePicker"
class="com.simplecode.action.DatePickerAction">
<result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>

Demo

On running the above example
http://localhost:8089/Struts2_DatePicker/



Now on clicking the date picker icon, the calendar gets displayed as shown below.


On selecting the date and clicking the submit button, the following output is obtained


Suppose you want to include a static date in jsp, then the following code can be used

<sx:datetimepicker name="staticDateFromJsp" label="Format (dd-MMM-
yyyy)"
displayFormat="dd-MMM-yyyy" value="%{'1989-12-19'}" />

Suppose you want to include a static date in jsp, then the following code can be used

<sx:datetimepicker name="todaysDate" label="Format (dd-MMM-yyyy)"
displayFormat="dd-MMM-yyyy" value="%{'today'}" />

So now when you run the application, these values will be displayed in the jsp page. Inorder to
make this values appear in the result page, you just need to include the getter and setter
for staticDateFromJsp and todaysDate in the action class, and render it via property tag in
result.jsp page

Click here to learn about Datetime picker in struts 2 using jquery jar

Datetime picker in struts 2 using jquery
Posted by Mohaideen Jamil on Nov 10, 2013 in Struts-2 | 1 comment



Zip file Jquery DatePicker



Last time when I worked out how to get the dojo datetimepicker Well, it faced some issues like,
I could not customize the size of the text box, and also its appearance. As an alternative I
found out a plugin Struts2- Jquery which provide a lots of customizing features.

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

To create a date time pick component in struts 2, please follow this two steps :

1. Add struts2-jquery-plugin-3.6.1.jar in your class path.
2. Include the struts-jquery-tags tag and its header in your jsp page

<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head />
</head>

Do read :
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Feature of jquery

Simple Calculator
<sj:datepicker id="1" name="simpleCalander" displayFormat="dd-mm-yy"
label="Simple Calander"/>



Calander with change year Option
<sj:datepicker id="2" name="changeYear" displayFormat="dd-mm-yy"
changeYear="true"
label="Change Year"/>



Calander with ChangeYear and Monthyear Option
<sj:datepicker id="3" name="changeYearAndMonth" label="Change Month
and Year"
changeMonth="true" changeYear="true"/>



Calander with Button Pannel Option
<sj:datepicker id="5" name="withPannel" label="With Button Panel"
showButtonPanel="true"/>



Calander with Show Seconds Option
<sj:datepicker id="4" name="showSeconds" label="Show Seconds"
timepicker="true"
timepickerShowSecond="true" timepickerFormat="hh:mm:ss"/>



Now lets see the complete example

Jsp Page

File: datepicker.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>

<html>
<head>
<title>Date Picker</title>
<sj:head />
</head>

<body>
<h3>Struts2 Date Picker example</h3>
<s:form action="dateTimePicker" theme="xhtml">
<sj:datepicker id="1" name="simpleCalander" displayFormat="dd-mm-yy"
label="SimpleCalander"/>
<sj:datepicker id="2" name="changeYear" displayFormat="dd-mm-yy"
changeYear="true"
label="ChangeYear"/>
<sj:datepicker id="3" name="changeYearAndMonth"
label="Change Month and Year" changeMonth="true"
changeYear="true" />
<sj:datepicker id="4" name="showSeconds" label="Show Seconds"
timepicker="true" timepickerShowSecond="true"
timepickerFormat="hh:mm:ss" />
<sj:datepicker id="5" name="withPannel" label="With Button Panel"
showButtonPanel="true" />
<sj:datepicker id="6" name="slideDownEffect"
label="With fast slideDown Animation" showAnim="slideDown"
duration="fast" />
<sj:datepicker id="7" name="fadeInEffect"
label="With slow fadeIn Animation" showAnim="fadeIn"
showOptions="{direction: 'up' }" duration="slow" />
<sj:datepicker id="8" name="yearRage" label="Show Years only from
2000 until 2020"
yearRange="2000:2020" changeYear="true" />
<sj:datepicker id="9" name="withOutButton" label="Without Button"
showOn="focus" />

<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>

File: result.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Date Picker Result</title>
</head>
<body>
<h3>Struts2 Date Picker using Jquery</h3>
simpleCalander : <s:property value="simpleCalander" />
<br />
changeYear : <s:property value="changeYear" />
<br />
changeYearAndMonth : <s:property value="changeYearAndMonth"
/>
<br />

showSeconds : <s:property value="showSeconds" />
<br />
withPannel : <s:property value="withPannel" />
<br />
slideDownEffect : <s:property value="slideDownEffect" />
<br />
fadeInEffect : <s:property value="fadeInEffect" />
<br />
yearRage : <s:property value="yearRage" />
<br />
withOutButton : <s:property value="withOutButton" />
<br />

</body>
</html>

Action Class

package com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class DatePickerAction implements Action {

private String simpleCalander;
private String changeYear;
private String changeYearAndMonth;
private String showSeconds;
private String withPannel;
private String slideDownEffect;
private String fadeInEffect;
private String yearRage;
private String withOutButton;

public String getSimpleCalander() {
return simpleCalander;
}

public String getChangeYear() {
return changeYear;
}

public String getChangeYearAndMonth() {
return changeYearAndMonth;
}

public String getShowSeconds() {
return showSeconds;
}

public String getWithPannel() {
return withPannel;
}

public String getSlideDownEffect() {
return slideDownEffect;
}

public String getFadeInEffect() {
return fadeInEffect;
}

public String getYearRage() {
return yearRage;
}

public String getWithOutButton() {
return withOutButton;
}

public void setSimpleCalander(String simpleCalander) {
this.simpleCalander = simpleCalander;
}

public void setChangeYear(String changeYear) {
this.changeYear = changeYear;
}

public void setChangeYearAndMonth(String changeYearAndMonth)
{
this.changeYearAndMonth = changeYearAndMonth;
}

public void setShowSeconds(String showSeconds) {
this.showSeconds = showSeconds;
}

public void setWithPannel(String withPannel) {
this.withPannel = withPannel;
}

public void setSlideDownEffect(String slideDownEffect) {
this.slideDownEffect = slideDownEffect;
}

public void setFadeInEffect(String fadeInEffect) {
this.fadeInEffect = fadeInEffect;
}

public void setYearRage(String yearRage) {
this.yearRage = yearRage;
}

public void setWithOutButton(String withOutButton) {
this.withOutButton = withOutButton;
}

public String execute() {
return SUCCESS;
}
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="" namespace="/jsp" extends="struts-default">
<action name="dateTimePicker"
class="com.simplecode.action.DatePickerAction" method="execute">
<result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>

Demo

On running the application:-



Autocompleter Textbox & dropdown in Struts 2
Posted by Mohaideen Jamil on Oct 26, 2013 in Struts 2 Tutorial, Struts-2 | 14 comments


To create a Autocompleter component in struts 2, please follow this two steps :

1. Add struts2-dojo-plugin.jar in your class path.
2. Include the struts-dojo-tags tag and its header(shown below) in your jsp page

<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>

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

Action class

AutoCompleteAction.java

package com.simplecode.action;

import java.util.ArrayList;
import com.opensymphony.xwork2.Action;

public class AutoCompleteAction implements Action
{
public ArrayList<String> cricketNations = new
ArrayList<String>();
public String country;

public String execute()
{
populateCircketNations();
return SUCCESS;
}

public void populateCircketNations()
{
cricketNations.add("Australia");
cricketNations.add("England");
cricketNations.add("India");
cricketNations.add("West Indies");
cricketNations.add("New Zealand");
cricketNations.add("Pakistan");
cricketNations.add("Bangladesh");
cricketNations.add("South Africa");
cricketNations.add("Sri Lanka");
cricketNations.add("Zimbabwe");
}

public String displayCountry()
{
return SUCCESS;
}

public String getCountry()
{
return country;
}

public void setCountry(String country)
{
this.country = country;
}
}

Do read: Autocomplete in Struts 2 using Jquery and JSON via Ajax

JSP Page

autoComplete.jsp

Here <%@taglib uri="/struts-dojo-tags" prefix="sx"%> is a directive used in jsp for including
dojo ajax tag files.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-dojo-tags" prefix="sx"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<sx:head />
<head>
<title>Auto complete</title>
</head>
<body>
<h3>Auto complete Dropdown | Textbox</h3>
<s:form action="displayCountry">
<sx:autocompleter name="country" list="cricketNations"
showDownArrow="false"
label="Cricket Nations"/>
<s:submit />
</s:form>
</body>
</html>

Note: In <sx :autocompleter> tag, showDownArrow property indicates whether to show
dropdown or not, on setting to false textbox will appear and when set to true dropdown box will
appear.
struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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" namespace="/">
<action name="autoComplete"
class="com.simplecode.action.AutoCompleteAction">
<result name="success">autoComplete.jsp</result>
</action>
<action name="displayCountry"
class="com.simplecode.action.AutoCompleteAction"
method="displayCountry">
<result name="success">WelcomeToCountry.jsp</result>
</action>
</package>
</struts>


Do read: AJAX implementation in Struts 2 using JQuery and JSON

Demo

On running the above example
http://localhost:8089/AutoComplete/autoComplete.action

Setting showDownArrow = true



Setting showDownArrow = false




Zip file AutoCompleter.zip
War file AutoCompleter.war

Struts 2 Bean Tag
Posted by Mohaideen Jamil on Aug 12, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


The bean tag is like a hybrid of the set and push tags. The main difference is that you dont
need to work with an existing object. You can create an instance of an object and either push it
onto the ValueStack or set a top-level reference to it in the Action-Context. By default, the
object will be pushed onto the ValueStack and will remain there for the duration of the tag.

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

In this tutorial let us learn how to use the Struts 2 Bean Tag with the help of a DollarConverter
bean example. In this example we will convert dollars to rupees.


Download It BeanTag Example.zip


1.Bean Class

File name : DollarConverter .java

package com.simplecode.action;

public class DollarConverter {

private double rupees;
private double dollars;

public double getRupees() {
return dollars * 55;
}

public void setRupees(double rupees) {
this.rupees = rupees;
}

public double getDollars() {
return rupees / 55;
}

public void setDollars(double dollars) {
this.dollars = dollars;
}
}

The next step is to create an instance of the DollarConverter bean in the jsp page using the
bean tag.
We can use the bean tag in two ways.
1. By pushing the value onto the ValueStack.
2. By setting a top-level reference to it in the ActionContext.
Lets implement both the methods one by one.

Method 1

Hear we will see how we can do this by pushing the value onto the ValueStack. We do this
using the following code in jsp.

<h5>Method 1 - push the value onto the ValueStack</h5>
<s:bean name="com.simplecode.action.DollarConverter ">
<s:param name="dollars" value="100" />
100 Dollars = <s:property value="rupees" /> Rupees
</s:bean>
<br />
The name attribute of the bean tag hold the fully qualified class name of the JavaBean. The
param tag is used to set the dollar value. We now use the property tag to retrive the equivalent
value in rupees. The DollarConverter bean will resides on the ValueStack till the duration of the
bean tag. So its important that we use the property tag within the bean tag.

Method 2

Now we will see how we can do the same by creating a top-level reference to the bean in the
ActionContext. We do this using the following code.


<h5>Method 2 - Set a top-level reference to it in the
ActionContext</h5>
<s:bean name="com.simplecode.action.DollarConverter "
var="converter">
<s:param name="dollars" value="100"></s:param>
</s:bean>
100 Dollars = <s:property value="#converter.rupees" /> Rupees

To create an instance of the bean in the ActionContext we need to specify the instance name
using the var attribute of the bean tag. Here our instance name is converter. Once we do this
we can access the bean values outside the bean tag. Since the value is in the ActionContext
we use the # operator to refer it.

4. Demo

http://localhost:8089/BeanTag
Output



Struts 2 Push Tag Example
Posted by Mohaideen Jamil on Aug 12, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


Struts 2 push tag is used to push a value into the ValueStack. The value we pushed using
push tag will be on top of the ValueStack, so it can be easily referenced using the first-level
OGNL expression instead of a deeper reference. The following code show how to do this.

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


Download It PushTag



1. Action
package com.simplecode.action;

import com.simplecode.util.AuthorBean;

//PushTag Action class
public class BookInfoAction {

private AuthorBean authorBean;

public String populate() {
authorBean = new AuthorBean
("Mohammed masjid", "Akuland Nz","8051 Micro
Controller");
return "populate";
}

public String execute() {
return "success";
}

public AuthorBean getAuthorBean() {
return authorBean;
}

public void setAuthorBean(AuthorBean authorBean) {
this.authorBean = authorBean;
}

}

2. Bean

A simple AuthorBean class, later will push it into the stack for easy access.
package com.simplecode.util;

public class AuthorBean {

private String name;
private String university;
private String book;

public AuthorBean(String name, String university, String
book) {
this.name = name;
this.university = university;
this.book = book;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getUniversity() {
return university;
}

public void setUniversity(String university) {
this.university = university;
}

public String getBook() {
return book;
}

public void setBook(String book) {
this.book = book;
}

}

3. Push tag example

It shows the use of push tag.

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Book Details</title>
</head>
<body>
<p>Author name property can be accessed in two ways:</p>

<br /> (Method 1 - Normal method)
<br /> <b>Author Name:</b>
<s:property value="authorBean.name" />
<br /> <b> University: </b>
<s:property value="authorBean.university" />
<br/><b>Book Title :</b>
<s:property value="authorBean.book" />


<br /> <br /> (Method 2-push tag)

<s:push value="authorBean">
<b>Author Name:</b>
<s:property value="name" />
<b> University: </b>
<s:property value="university" />
<b>Book Title :</b>
<s:property value="book" />
</s:push>

</body>
</html>


How it work?

Normally, if you want to get the beans property, you may reference it like
<s:property value="authorBean.name" />
With push tag, you can push the authorBean to the top of the stack, and access the
property directly
<s:property value="name" />
Both are returned the same result, but with different access mechanism only.

4. Struts.xml
Link it

<?xml version="1.0" encoding="UTF-8" ?>
<!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="*BookAction" method="{1}"
class="com.simplecode.action.BookInfoAction">
<result
name="populate">/bookDetails.jsp</result>
</action>
</package>
</struts>

5. Demo

http://localhost:8089/PushTag/populateBookAction.action

Run it



Struts 2 Debug Tag Example
Posted by Mohaideen Jamil on Aug 2, 2013 in Struts 2 Tutorial | 0 comments


In Struts 2, the debug tag is used to output the content of the Value Stack and Stack
Context details in the web page.

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

1. Jsp debug tag example

A JSP page to output the systems Value Stack and Stack Context using debug tag.

debug.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Debug tag</title>
</head>
<body>
<h3>Debug tag</h3>
<s:debug />
</body>
</html>

2. Action class

A Action class, with a field named actionProperty property, show in value stack in jsp.

DebugTag.java

package com.simplecode.action;
import com.opensymphony.xwork2.Action;

public class DebugTag implements Action
{
public String actionProperty;

public String getActionProperty()
{
return actionProperty;
}

public void setActionProperty(String actionProperty)
{
this.actionProperty = actionProperty;
}
}

3. struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="debugTagAction"
class="com.simplecode.action.DebugTag">
<result name="success">/debug.jsp</result>
</action>
</package>
</struts>

4. Demo

http://localhost:8089/Debug/debugTagAction.action
Output
The <s:debug /> will generate a text link named debug, On clicking this link, it expands to
show the debugging details.






Download It Struts2Debug.zip

Struts 2 URL tag example
Posted by Mohaideen Jamil on Aug 7, 2013 in Struts 2 Tutorial | 0 comments


The Struts 2 url tag can be useful if you need to use a url in many places and dont want to
repeat the code again and again. You need to specify an id attribute for your url and you can
also use actions instead of simple links in this tag. Adding parameters to the url can be done by
using the param tag.

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

Url tag example

Here are some examples to show the use of Struts 2 url tag.

1. Create an image url.

<img src="<s:url value="/image/android.jpg"/>" />

Output (assume the root context name is URLtag)
<img src="/URLtag/image/android.jpg" />

2. Create a Yahoo text and link it to http://www.yahoo.com.

<a href="<s:url value="http://www.yahoo.com"/> >Yahoo</a>

Output
<a href="http://www.yahoo.com">Yahoo</a>


Note :

When you define the URL value with starting of www or http, Struts 2 will not add extra root
context, instead it will display as it is.

3. Adding parameters to the url using param tag
<s:url id="urlValue" action="urlTag.action">
<s:param name="age">25</s:param>
</s:url>
<s:a href="%{urlValue}">urlTag With Parameter</s:a>

On clicking the above <s:a> tag, the following url is generated in the browser

http://localhost:8089/URLtag/urlTag.action?age=25


Complete jsp page

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<title>URL Tag</title>
</head>
<body>
<h2>Struts 2 URL tag</h2>
<ol>
<li><img src="<s:url value="/image/struts.jpg"/>" /></li>
<li><a href="<s:url value="http://www.yahoo.com"
/>">Yahoo</a></li>
<li>
<s:url id="urlValue" action="urlTag.action">
<s:param name="age">25</s:param>
</s:url>
<s:a href="%{urlValue}">urlTag With Parameter</s:a>
</li>
</ol>
</body>
</html>

Demo

http://localhost:8080/URLtag/urlTag.action



Interceptors in Struts 2
Posted by Mohaideen Jamil on Aug 3, 2014 in Struts-2 | 0 comments

Interceptors are introduced as part of the Struts2 framework, power mechanism for controlling
request and are responsible for the most of request processing.


Interceptors are invoked by controller before and after invoking action and sits between the
controller and action.
An interceptor allows common, cross-cutting tasks to be defined into a clean, reusable
component, which is different than the action code.
Tasks like data validation, type conversion, and file upload are done using interceptors in
Struts2.0.
The built-in interceptors, declared in the defaultStack of the struts-default package, handle
most of the fundamental tasks.

Functioning of Interceptors
From architectural point of view, interceptors improve separation of concerns in web
applications.
An example of a pre-processing task is the data transfer achieved with the params
interceptor.
Instead of having a simple controller that directly invokes an action, we now have a component
that sits between the controller and the action.
In Struts 2, no action is invoked in isolation, the invocation of an action is a layered process. It
always includes the execution of a stack of interceptors prior to and after the actual execution
of the action itself.
Rather than directly invoking the actions execute ( ) method, the framework creates an object
called an ActionInvocation. This object encapsulates the action. Subsequently, all the
interceptors that have been configured to fire before and after that action start their execution.

Interceptor Order
Diagrammatic Representation

The figure above represents the normal workflow; here none of the interceptors have diverted
the invocation. This action will ultimately execute and return a control string that selects the
appropriate result.
After the result execution, each of the interceptors, in reverse order, gets a chance to do
some post-processing work.
As we will see, the interceptors have access to the action and other contextual values. This
allows them to be aware of what is happening during the processing.
One of the powerful functional aspects of interceptors is their ability to alter the workflow of
the invocation.
As we noted, the figure shown in the above depicts an instance where none of the interceptors
has intervened in the workflow. It thus allows the action to execute, and determine the result
that should render the view.
Sometimes, one of the interceptors will determine that the action should not execute. In such
cases, the interceptor can halt the workflow by itself by returning a control string.

Creating Custom Interceptors in Struts2
Posted by Mohaideen Jamil on Aug 4, 2014 in Struts 2 Tutorial, Struts-2 | 0 comments

In my previous post here I demonstrated about Concepts of Interceptor in Struts 2. In this post
we will see how to create a simple interceptor that will execute and print a few lines to the
server logs, both before and after an action is executed.
A few points need to be kept in mind before writing your own interceptors;
You can create your own custom interceptor in two ways
a)Implement the Interceptor interface
b)Extend the AbstractInterceptor class.
If You are implementing the Interceptor interface, you have to provide implementations to three
methods :
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
The init method is called before the intercept method is called. An interceptor instance is
created
once and is reused over many requests. Hence the interceptor code must be written to be
thread safe.
The intercept is the place where you write the business logic code of your interceptor.
The destroy method is executed on application shutdown and is used to release resources
used by the interceptor that have been allocated in the init method
If you are extending the AbstractInterceptor class, you only need to override the method:
String intercept(ActionInvocation invocation) throws Exception method to provide your own
implementation.
In our example we will be extending the AbstractInterceptor class.

Action Class

Now lets create a dummy action class
package action;

import com.opensymphony.xwork2.Action;

public class DummyAction implements Action{

public String execute()
{
System.out.println("Inside Action Class");
return SUCCESS;
}
}

Interceptors

create two interceptor classes and name it MyInterceptor1 and MyInterceptor2.
File : MyInterceptor1.java
package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class MyInterceptor1 extends AbstractInterceptor{

@Override
public String intercept(ActionInvocation ai) throws Exception {
System.out.println("Inside MyInterceptor1- Before Executing
Action class");
String invocationResult = ai.invoke();
System.out.println("Inside MyInterceptor1- After Executing
Action class");
return invocationResult;
}
}


File : MyInterceptor2.java
package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class MyInterceptor2 extends AbstractInterceptor{

@Override
public String intercept(ActionInvocation ai) throws Exception {
System.out.println("Inside MyInterceptor2- Before Executing Action
class");

String invocationResult = ai.invoke();

System.out.println("Inside MyInterceptor2- After Executing Action
class");
return invocationResult;
}
}

Configuring Interceptor in struts.xml

The configuration of struts.xml should be as show below
<struts>
<package name="default" extends="struts-default">
<interceptors>
<interceptor class="interceptors.MyInterceptor1"
name="myInterceptor1"></interceptor>
<interceptor class="interceptors.MyInterceptor2"
name="myInterceptor2"></interceptor>
</interceptors>

<action class="action.DummyAction" name="dummyAction">
<interceptor-ref name="myInterceptor1"></interceptor-ref>
<interceptor-ref name="myInterceptor2"></interceptor-ref>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>

Jsp

File : index.jsp
This file triggers dummyAction during application start up which is used to Test Interceptors
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=dummyAction">

Since the action is already configured such that the two interceptors will be called before and
after it is executed, you can check your server logs to ensure that the interceptors are
executing in the order as specified in the configuration.

Demo

On running the application, my Tomcat logs show the following :
Inside MyInterceptor1- Before Executing Action class
Inside MyInterceptor2- Before Executing Action class
Inside Action Class
Inside MyInterceptor2- After Executing Action class
Inside MyInterceptor1- After Executing Action class

Explanation

Consider the intercept method of MyInterceptor1. This method is called with an argument of
type ActionInvocation. TheActionInvocation object is created by the struts framework and is
used as a handle to the execution environment of the interceptor.

Since there are several interceptor defined in struts-default xml, the information of the
sequence in which these interceptors are executed for the action is stored in the
ActionInvocation object. The next interceptor in the sequence is called by calling the invoke()
method of the ActionInvocation object. For the first Interceptor, the invoke() method is called by
the ActionProxy object.

Since the invoke method causes the next interceptor/action in the sequence to be executed,
the interceptor is in absolute control of the execution and can decide at any moment whether to
proceed with the next step in the sequence or to return an error to the caller without
proceeding.

Here the String value returned by the invoke() method in Interceptor is the value that is
retrieved after the action have been executed. In our example, when the myInterceptor1
interceptor calls its invoke, control is passed on to the myInterceptor2, which in turn calls the
action. The action upon execution returns success as the string, which is in turn returned to
the myInterceptor2, which is in turn returned to myInterceptor1.

I our next article we shall learn to implement an Login interceptor which can be used in a real
time application.

Login Interceptor in Struts 2
Posted by Mohaideen Jamil on Aug 5, 2014 in Struts-2 | 1 comment

In our previous tutorial we have learned about concepts of interceptor and how interceptors
gets execute before and after action class by creating a custom interceptor. In this article we
shall create a custom LoginInterceptor which could be used in real time struts 2 application



This LoginInterceptor will perform these tasks:-
Check user exist in session or not.
Runs before every action to check .If someone try to access direct URL of welcome page and if
he is not present in session then it will redirect towards login page.
If user already in session then call the action called by user.
If session time expired and if user clicks on any link, then redirect towards login page.

File : LoginInterceptor.java

package com.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

@Override
public String intercept(ActionInvocation invocation) throws
Exception {
Map<String, Object> session =
invocation.getInvocationContext().getSession();

String loginId = (String) session.get("loginId");

if (loginId == null)
{
return Action.LOGIN;
}
else
{
return invocation.invoke();
}
}
}

Here LoginInterceptor class extended the AbstractInterceptor and in its intercept method we
have written business which checks weather the user present in session or not.
In the intercept method, we can make use of com.opensymphony.xwork2.ActionInvocation i.e.
Action Invocation object to get the action name trigger and decide on the further flow of
application associated with it. On the similar lines we can also make use of the
org.apache.struts2.ServletActionContext to get the request, response, session object etc.
which can be used further to decide on flow of the application.

LoginAction.java

package com.action;

import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements
SessionAware {

private static final long serialVersionUID = 1L;
private String userName;
private Map<String, Object> session;

public String home() {
return SUCCESS;
}

// Log Out user
public String logOut() {
session.remove("loginId");
addActionMessage("You have been Successfully Logged
Out");
return SUCCESS;
}

// Login user
public String login() {
if (userName.isEmpty()) {
addActionError("Username can't be blanked");
return LOGIN;
} else {
session.put("loginId", userName);
return SUCCESS;
}
}

public String getUserName() {
return userName;
}

public Map<String, Object> getSession() {
return session;
}

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

public void setSession(Map<String, Object> map) {
this.session = map;
}
}

LoginAction class with simple business logic, such as you can login with any username but
cannot leave blank the mandatory fields.

Configuring the custom interceptors in struts.xml

Here we configure our custom interceptor named LoginInterceptor defining loginStack as
default stack.

<struts>
<package name="default" extends="struts-default">
<interceptors>
<interceptor class="com.interceptor.LoginInterceptor"
name="loginInterceptor">
</interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>

<!-- login action -->
<action name="loginUser" class="com.action.LoginAction"
method="login">
<result name="success"
type="redirect">homeAction</result>
<result name="login">login.jsp</result>
</action>

<!-- home link action -->
<action name="homeAction" class="com.action.LoginAction"
method="home">
<interceptor-ref name="loginStack" />
<result name="login">login.jsp</result>
<result name="success">home.jsp</result>
</action>

<!-- logout action -->
<action name="logOut" class="com.action.LoginAction"
method="logOut">
<result>login.jsp</result>
</action>
</package>
</struts>

web.xml:

In web.xml define session time out to 1 min, for demonstrating point 4

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecu
teFilter
</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>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

Demo
Now on running this application



Now on entering a valid User name and hitting Submit button, the following page get appeared.



Now once I hit logout link or if the session gets expired, then if the try to access the
localhost:8089/LoginInterceptor/homeAction url, then the application redirects to Login page as
shown below.



Pagination in Struts 2 Using display tag
Posted by Mohaideen Jamil on Mar 13, 2013 in Display Tag, Struts-2 | 49 comments



In Struts 2 Pagination can be implemented with the help of Displaytag. This tag can handle
feature such as pagination, sorting and exporting of a table. In the following example we will
see how to display data using display tag and to do pagination, sorting and exporting.

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

Download the Latest version of displaytag.jar in the following link


Download It Display Tag



Now Create a Dynamic web project and make sure that you have the following libraries are in
your WEB-INF/lib directory.
commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-digester-2.0.jar
commons-io-2.0.1.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
displaytag-1.2.jar
freemarker-2.3.19.jar
ognl-3.0.6.jar
struts2-core-2.3.8.jar
xwork-core-2.3.8.jar
displaytag-export-poi.jar is used to export the files in xls,csv or xml format.

** RELATED POST: AJAX based Pagination in struts 2 using jQuery DataTable plugin


Action Class

StudentAction.java
package com.simplecode.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.simplecode.form.StudentBean;

public class StudentAction extends ActionSupport
{
private static final long serialVersionUID = 1L;
private List<StudentBean> students = new ArrayList<StudentBean>();

public String displayStudentList()
{
students.add(new StudentBean("o7bb002", "Gokul", "ECE", 4));
students.add(new StudentBean("o7bc074", "Muthu Vijay", "CSE",
6));
students.add(new StudentBean("o7bb040", "Jaya Prakash",
"ECE", 10));
students.add(new StudentBean("o7bc055", "Mohiadeen", "CSE",
7));
students.add(new StudentBean("o7bd047", "HariPriya", "IT",
1));
students.add(new StudentBean("o7bd024", "Pavithra", "IT",
3));
students.add(new StudentBean("o7bb009", "Aswin", "ECE", 8));
students.add(new StudentBean("o7ba029", "Sharmila", "IT",
11));
students.add(new StudentBean("o7ba027", "Nilafar", "IT", 2));
students.add(new StudentBean("o7bd081", "Dinesh Babu",
"MECH", 13));
students.add(new StudentBean("o7ba062", "Lourde", "MECH",
9));
students.add(new StudentBean("o7bc079", "Nisha", "CSC", 5));
students.add(new StudentBean("o7bb039", "Guru Prasad",
"MECH", 12));
students.add(new StudentBean("o7bc033", "Gowtham Raj", "CSE",
15));
students.add(new StudentBean("o7bb039", "Ibrahim Sha", "ECE",
14));
students.add(new StudentBean("o7bd081", "Dinesh Babu",
"MECH", 16));

return SUCCESS;
}

public List<StudentBean> getStudents()
{
return students;
}

public void setStudents(List<StudentBean> students)
{
this.students = students;
}
}

StudentBean.java

package com.simplecode.form;

public class StudentBean
{
private String rollNo;
private String studentName;
private String department;
private int rank;

public StudentBean(String rollNo, String studentName, String
department, int rank)
{
this.rollNo = rollNo;
this.studentName = studentName;
this.department = department;
this.rank = rank;
}
public String getRollNo()
{
return rollNo;
}
public void setRollNo(String rollNo)
{
this.rollNo = rollNo;
}
public String getStudentName()
{
return studentName;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String getDepartment()
{
return department;
}
public void setDepartment(String department)
{
this.department = department;
}
public int getRank()
{
return rank;
}
public void setRank(int rank)
{
this.rank = rank;
}
}

displaytag.jsp


<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="display" uri="http://displaytag.sf.net"%>

<title>Students Details</title>
<style type="text/css">

/* for hiding the page banner */
.pagebanner
{
display: none;
}
/* for customizing page links */
.pagelinks
{
color: maroon;
margin: 20px 0px 20px 50px;
}
/* for shifting all the Export options*/
.exportlinks
{
margin: 20px 0px 20px 30px;
}
/* For changing the spaces between export link */
.export
{
margin-left: 30px;
}
/* For Table css */
table
{
border: 1px solid #666;
width: 60%;
margin: 20px 0 20px 0px;
}
/* For odd and even row decoration */
tr.odd
{
background-color: #fff
}
tr.tableRowEven,tr.even
{
background-color: #CCCCCC
}
/* Css for table elements */
th,td
{
padding: 2px 4px 2px 4px;
text-align: left;
vertical-align: top;
}
thead tr
{
background-color: #999999;
}
/* For changing the background colour while sorting */
th.sorted
{
background-color: #CCCCCC;
}
th.sorted a,th.sortable a
{
background-position: right;
display: block;
width: 100%;
}
th a:hover
{
text-decoration: underline;
color: black;
}
th a,th a:visited
{
color: black;
}
</style>

<html>
<body>
<display:table id="studentTable" name="students" pagesize="5"
cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;"
requestURI="">
<display:column property="rollNo" title="Roll No"/>
<display:column property="studentName" title="Student Name"/>
<display:column property="department" title="Department"/>
<display:column property="rank" title="Rank"/>
</display:table>
</body>
</html>

Questions:
How to make Struts 2 tag work inside Display tag?
How to get checkbox values from displaytag using struts2
Displaytag export option is not working?

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!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="displayStudentList"
class="com.simplecode.action.StudentAction"
method="displayStudentList">
<result name="success">/displaytag.jsp</result>
</action>
</package>
</struts>

After executing the project, you will get the following output:



Recommended reading :
AJAX implementation in Struts 2 using JQuery and JSON
Gridview in Struts2 using jQuery DataTable
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

Auto-sorting

If you want to allow the user to sort the data displayed then set the attribute sortable=true on
the display:column tag that you want to sort by.

<display:column property="rollNo" title="Roll No" sortable="true"/>
<display:column property="studentName" title="Student Name"
sortable="true"/>
<display:column property="department" title="Department"
sortable="true"/>
<display:column property="rank" title="Rank" sortable="true"/>

Now on clicking the rank header the student resultset are sorted according to rank as shown
below.


Here the problem is whenever we sort the table by clicking on any sortable column header it
only sort the data visible in that page. We can override this behavior by setting sort attribute in
column to list as shown below.

<display:table export="true" id="studentTable" name="students"
pagesize="5" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;"
requestURI="" sort = "list">

So now when you click on sort, the data will be sorted based on whole list.



Data exporting

When you set the Table Tags export attribute to true, footer will appear below the sorted
result, which will allow you to export the data being shown in various formats(CSV, XLS, and
XML).

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

<display:table export="true" id="studentTable" name="students"
pagesize="5" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;"
requestURI="">



Suppose if you want to place the banner at bottom , then you can use the following code,
within the display-table tag
<display:setProperty name="paging.banner.placement" value="bottom" />

** Update The below screenshot is the demo of pagination in struts 2 via ajax using
using jQuery jTable plugin, this plugin has several inbuilt theme and lot may cool features
like crud implementation via ajax, internalization etc, to know more about this plugin, please
refer the article here.




Zip file DisplayTagExample.zip
War file DisPlayTag


Struts 2 tag not working in Display tag
Solution
Posted by Mohaideen Jamil on Dec 24, 2013 in Display Tag, Struts 2 Tutorial, Struts-2 | 0
comments


Consider a scenario, such that you want to display a value of a column based on certain
condition.

For example:

if a students 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 markis 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?

How to get checkbox values from struts2
checkbox in displaytag to action class
Posted by Mohaideen Jamil on Dec 25, 2013 in Display Tag, Struts 2 Tutorial, Struts-2 | 1
comment


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.
Displaytag export option is not working-
Solution
Posted by Mohaideen Jamil on Feb 18, 2014 in Java, Struts 1, Struts-2 | 2 comments


In this article we will learn to resolve the issue which occurs while exporting the file using
display tag,

In order to enable export functionality in display tag, configure display tag in JSP as shown
below.

<display:table name="studentList" pagesize="5" export ="true"
requestURI="/displaytag.jsp">
<display:column property="rollNo" title="Roll No"/>
<display:column property="studentName" title="Student Name"/>
<display:column property="department" title="Department"/>
<display:column property="rank" title="Rank"/>
</display:table>

Here export=true option enable export functionality in displaytag.

Displaytag Export Issue

After enabling displaytag export functionality, though it was working in test program, export
option on display tag for CSV, Excel, XML and PDF was not working on actual project.

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

My Application throws the following exception and error message, when user clicks on export
button :
org.displaytag.exception.BaseNestableJspTagException Exception: [.TableTag] Unable to
reset response before returning exported data. You are not using an export filter. . . . configure
the export filter.

Cause of Displaytag export problem:

This issue occurs when you have declared filter in web.xml

Solution :

To fix displaytag export issue the following steps are needed to be followed:

Add ResponseOverrideFilter filter as shown below.

<filter>
<filter-name>ResponseOverrideFilter</filter-name>
<filter-
class>org.displaytag.filter.ResponseOverrideFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ResponseOverrideFilter</filter-name>
<url-pattern>*.*</url-pattern>
</filter-mapping>

How to Override Default Theme in Struts 2 ?
Posted by Mohaideen Jamil on Jan 13, 2014 in Struts 2 Tutorial, Struts-2 | 3 comments


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 :
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Ajax implementation in Struts 2 without jQuery
plugin
Posted by Mohaideen Jamil on Dec 12, 2013 in Ajax, Struts-2 | 1 comment



Zip file AjaxInStruts2.zip



AJAX is a technique for creating better, faster, and more interactive web applications. With
AJAX, your JavaScript can communicate directly with the server, using the JavaScript
XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server,
without reloading the page.

This post elaborates on how to implement Ajax in Struts 2 application.

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

Action class

package com.simplecode.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.Action;

public class AjaxAction implements Action
{

private String userName;
private InputStream inputStream;

public String ajaxMethod()
{
System.out.println("ajaxMethod() is called");
byte[] bArray;

if(!userName.isEmpty())
{
bArray = ("Welcome " + userName).getBytes();
inputStream = new ByteArrayInputStream(bArray);
}
else
{
bArray = ("User name cant be blank").getBytes();
inputStream = new ByteArrayInputStream(bArray);
}

return SUCCESS;
}

public String execute()
{
return SUCCESS;
}

public String getUserName()
{
return userName;
}

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

public InputStream getInputStream()
{
return inputStream;
}
}


Recommended reading:
AJAX implementation in Struts 2 using JQuery and JSON

Jsp Pages

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

<html>
<head>
<title>Ajax implementation in Struts 2 </title>

<script type="text/javascript">

//Get XMLHTTP Object
function getXMLHTTPObject()
{
var xmlhttpObject = null;
try
{
// For Old Microsoft Browsers
xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
// For Microsoft IE 6.0+
xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e1)
{
// No Browser accepts the XMLHTTP Object then false
xmlhttpObject = false;
}
}

if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined')
{
//For Mozilla, Opera Browsers
xmlhttpObject = new XMLHttpRequest();
}
// Mandatory Statement returning the ajax object created
return xmlhttpObject;
}


// Change the value of the outputText field
function setAjaxOutput()
{
document.getElementById('userNameDiv').innerHTML =
xmlhttpObject.responseText;
}

function handleServerResponse()
{
if (xmlhttpObject.readyState == 4)
{
if (xmlhttpObject.status == 200)
{
setAjaxOutput();
}
else
{
alert("Error during AJAX call. Please try
again");
}
}
}

// Implement business logic
function doAjaxCall()
{
xmlhttpObject = getXMLHTTPObject();
if (xmlhttpObject != null)
{
var URL = "myAjaxAction.action?userName=" +
document.getElementById('userName').value;
xmlhttpObject.open("POST", URL, true);
xmlhttpObject.onreadystatechange = handleServerResponse;
xmlhttpObject.send(null);
}
}
</script>
</head>

<body>
<h3>Ajax implementation in Struts2</h3>
<br/>
<div id="userNameDiv" style="color: red; font-weight: bold"></div>
<br/>
Please Enter your Name :
<s:textfield id="userName" theme="simple" name="userName"
onblur="doAjaxCall();"/>
<br />

</body>
</html>

AJAX implementation in Struts 2 using JQuery
and JSON
Posted by Mohaideen Jamil on May 23, 2014 in Ajax, jQuery, Struts-2 | 27 comments



In this post, we will learn to implement AJAX calls from a JSP page to a Struts 2 Action class
using JQuery and update the same JSP page back with the Json response from the Struts 2.

Library required

Since the response to be sent to jQuery is of type JSON, to handle it you need struts2-json-
plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute which has getter
and setter into a JSON object.

Steps done to set up our action for JSON

From the browser perspective: jQuery
jQuery allows you to issue an ajax request and expects a JSON object as a response.

Jsp Page

Now, let us create a JSP page with two drop down lists, one contains values for countries and
the other that is going to be populated with values for states based on the value selected in the
first drop down list. This is done without a page refresh, by making AJAX calls to the Struts 2
action on first drop down list change event.

Recommended reading :
AJAX implementation in Struts 2 without JQuery

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>AJAX in Struts 2 using JSON and jQuery</title>
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#country').change(function(event) {
var country = $("select#country").val();
$.getJSON('ajaxAction', {
countryName : country
}, function(jsonResponse) {
$('#ajaxResponse').text(jsonResponse.dummyMsg);
var select = $('#states');
select.find('option').remove();
$.each(jsonResponse.stateMap, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<h3>AJAX calls to Struts 2 using JSON and jQuery</h3>
<s:select id="country" name="country"
list="{'Select Country','India','US'}" label="Select Country"
/>
<br />
<br />
<s:select id="states" name="states" list="{'Select State'}"
label="Select State" />
<br />
<br />
<div id="ajaxResponse"></div>
</body>
</html>

Note that I have referenced jQuery files in the head section of the jsp which is responsible for
the AJAX call made to the struts 2 action and for displaying the response back in the JSP.

Whenever the value is selected in the country drop down list, its change event is fired and the
getJSON function executes ajaxAction (first argument of getJSON) configured in struts.xml. I
have explained about the parameters of getJSON method in the article here.

From the servers perspective: Struts 2

In action class you need to create instance variables and its respective getter and setter
methods. Here all the variables that have a setter can be set to the values received as
parameters from jQuery and all the variables that have a getter method can be retrieved in the
client javascript code.

Also read :
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Struts 2 using Jquery via Ajax
Tab Style Login and Signup example using jQuery in Java web application
Action class

package com.action;

import java.util.LinkedHashMap;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class AjaxJsonAction implements Action{

private Map<String, String> stateMap = new LinkedHashMap<String,
String>();
private String dummyMsg;
//Parameter from Jquery
private String countryName;

public String execute() {
if (countryName.equals("India")) {
stateMap.put("1", "Kerala");
stateMap.put("2", "Tamil Nadu");
stateMap.put("3", "Jammu Kashmir");
stateMap.put("4", "Assam");
} else if (countryName.equals("US")) {
stateMap.put("1", "Georgia");
stateMap.put("2", "Utah");
stateMap.put("3", "Texas");
stateMap.put("4", "New Jersey");
} else if (countryName.equals("Select Country")) {
stateMap.put("1", "Select State");
}
dummyMsg = "Ajax action Triggered";
return SUCCESS;
}

public Map<String, String> getStateMap() {
return stateMap;
}

public String getDummyMsg() {
return dummyMsg;
}

public String getCountryName() {
return countryName;
}

public void setStateMap(Map<String, String> stateMap) {
this.stateMap = stateMap;
}

public void setDummyMsg(String dummyMsg) {
this.dummyMsg = dummyMsg;
}

public void setCountryName(String countryName) {
this.countryName = countryName;
}
}

In the above code, we create a maps and populates its value based on the country parameter
passed to the action class by the AJAX call made by the JQuerys getJSON() method.

struts.xml

Since the response needed by jQuery is of type json, so we need to convert this map objects to
json strings, for this you need to configure this Action class in struts.xml such that it returns a
json object. This configuration is as follows:
Create a package in struts.xml file, which extend json-default and specify the result type of
your action class inside this package to be json. The json-default package contains an
interceptor and the result type configuration for JSON requests and responses.
<struts>
<package name="default" extends="json-default">
<action name="ajaxAction" class="com.action.AjaxJsonAction">
<result type="json">/index.jsp</result>
</action>
</package>
</struts>

AJAX implementation in Struts 2 using JQuery
and JSON
Posted by Mohaideen Jamil on May 23, 2014 in Ajax, jQuery, Struts-2 | 27 comments



In this post, we will learn to implement AJAX calls from a JSP page to a Struts 2 Action class
using JQuery and update the same JSP page back with the Json response from the Struts 2.

Library required

Since the response to be sent to jQuery is of type JSON, to handle it you need struts2-json-
plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute which has getter
and setter into a JSON object.

Steps done to set up our action for JSON

From the browser perspective: jQuery
jQuery allows you to issue an ajax request and expects a JSON object as a response.

Jsp Page

Now, let us create a JSP page with two drop down lists, one contains values for countries and
the other that is going to be populated with values for states based on the value selected in the
first drop down list. This is done without a page refresh, by making AJAX calls to the Struts 2
action on first drop down list change event.

Recommended reading :
AJAX implementation in Struts 2 without JQuery

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>AJAX in Struts 2 using JSON and jQuery</title>
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#country').change(function(event) {
var country = $("select#country").val();
$.getJSON('ajaxAction', {
countryName : country
}, function(jsonResponse) {
$('#ajaxResponse').text(jsonResponse.dummyMsg);
var select = $('#states');
select.find('option').remove();
$.each(jsonResponse.stateMap, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<h3>AJAX calls to Struts 2 using JSON and jQuery</h3>
<s:select id="country" name="country"
list="{'Select Country','India','US'}" label="Select Country"
/>
<br />
<br />
<s:select id="states" name="states" list="{'Select State'}"
label="Select State" />
<br />
<br />
<div id="ajaxResponse"></div>
</body>
</html>

Note that I have referenced jQuery files in the head section of the jsp which is responsible for
the AJAX call made to the struts 2 action and for displaying the response back in the JSP.

Whenever the value is selected in the country drop down list, its change event is fired and the
getJSON function executes ajaxAction (first argument of getJSON) configured in struts.xml. I
have explained about the parameters of getJSON method in the article here.

From the servers perspective: Struts 2

In action class you need to create instance variables and its respective getter and setter
methods. Here all the variables that have a setter can be set to the values received as
parameters from jQuery and all the variables that have a getter method can be retrieved in the
client javascript code.

Also read :
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Struts 2 using Jquery via Ajax
Tab Style Login and Signup example using jQuery in Java web application
Action class

package com.action;

import java.util.LinkedHashMap;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class AjaxJsonAction implements Action{

private Map<String, String> stateMap = new LinkedHashMap<String,
String>();
private String dummyMsg;
//Parameter from Jquery
private String countryName;

public String execute() {
if (countryName.equals("India")) {
stateMap.put("1", "Kerala");
stateMap.put("2", "Tamil Nadu");
stateMap.put("3", "Jammu Kashmir");
stateMap.put("4", "Assam");
} else if (countryName.equals("US")) {
stateMap.put("1", "Georgia");
stateMap.put("2", "Utah");
stateMap.put("3", "Texas");
stateMap.put("4", "New Jersey");
} else if (countryName.equals("Select Country")) {
stateMap.put("1", "Select State");
}
dummyMsg = "Ajax action Triggered";
return SUCCESS;
}

public Map<String, String> getStateMap() {
return stateMap;
}

public String getDummyMsg() {
return dummyMsg;
}

public String getCountryName() {
return countryName;
}

public void setStateMap(Map<String, String> stateMap) {
this.stateMap = stateMap;
}

public void setDummyMsg(String dummyMsg) {
this.dummyMsg = dummyMsg;
}

public void setCountryName(String countryName) {
this.countryName = countryName;
}
}

In the above code, we create a maps and populates its value based on the country parameter
passed to the action class by the AJAX call made by the JQuerys getJSON() method.

struts.xml

Since the response needed by jQuery is of type json, so we need to convert this map objects to
json strings, for this you need to configure this Action class in struts.xml such that it returns a
json object. This configuration is as follows:
Create a package in struts.xml file, which extend json-default and specify the result type of
your action class inside this package to be json. The json-default package contains an
interceptor and the result type configuration for JSON requests and responses.
<struts>
<package name="default" extends="json-default">
<action name="ajaxAction" class="com.action.AjaxJsonAction">
<result type="json">/index.jsp</result>
</action>
</package>
</struts>

GridView in Struts2 using jQuery DataTable via
Ajax
Posted by Mohaideen Jamil on May 31, 2014 in Ajax, jQuery, Struts-2 | 11 comments

In this post, I am going to explain on how to use DataTable plugin to display data in Gridview
format with pagination feature in Struts 2 web application.



DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as
filtering, paging sorting, changing page length, server side processing etc.

Library
struts2-json-plugin-x.x.x.jar
DataTable Plugin
OpenCSV(Optional I am using this to deal with a csv file as data source instead of database
to keep it simple)
jQuery UI themes
In this example, I am going to retrieve values from a csv file and display it in html table. For
this, I am going to use OpenCSVlibrary which simplifies the work of parsing CSV files. Here the
Data table will load the data by making an Ajax call.

Note:
Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .

Since the response to be generated from the action class is of type JSON, So to handle it you
need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute
(which has getter and setter) into a JSON object. Refer this article here for more detail.

Now create a dynamic web project in eclipse and create two folders named js and css under
WebContent, and add the following javascript files from DataTable to the js folder
jquery.dataTables.js
jquery.js
Add the following css files from DataTable & jQuery ui to css folder.
demo_page.css
demo_table_jui.css
jquery-ui-x.x.x.css

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

Download the csv file from which the data is to be read from here and place it under src folder,
This files contains four columns company, country, revenue, and year.

Project Structure



Model class

Create a model class that gets and sets the data from the four columns (company, country,
revenue, and year) of the csv file.

package com.model;

public class RevenueReport {

public RevenueReport(String company, String country, String
year,
String revenue) {
this.company = company;
this.country = country;
this.year = year;
this.revenue = revenue;
}

private String company;
private String country;
private String year;
private String revenue;

public String getCountry() {
return country;
}

public String getRevenue() {
return revenue;
}

public String getCompany() {
return company;
}

public String getYear() {
return year;
}

public void setCountry(String country) {
this.country = country;
}

public void setRevenue(String revenue) {
this.revenue = revenue;
}

public void setCompany(String company) {
this.company = company;
}

public void setYear(String year) {
this.year = year;
}
}

Business class

Create a Business Service class that would fetch data from the csv file using model class.

package com.service;

import java.io.*;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;

import com.model.RevenueReport;

public class BusinessService {

public static List<RevenueReport> getCompanyList() {

List<RevenueReport> listOfCompany = new
LinkedList<RevenueReport>();
String fileName = "Company_Revenue.csv";

InputStream is =
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
BufferedReader br = new BufferedReader(new
InputStreamReader(is));

try {
CSVReader reader = new CSVReader(br);
String[] row = null;
while ((row = reader.readNext()) != null)
{
listOfCompany.add(new RevenueReport(row[0], row[1],
row[2], row[3]));
}
reader.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
return listOfCompany;
}
}

Jsp

Now create the jsp file to display the data fetched from csv file in html table and enhance the
table features using DataTable plugin.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Gridview in Struts2 using jQuery DataTable plugin</title>

<link href="css/demo_table_jui.css" rel="stylesheet" />
<link href="css/jquery-ui.css" rel="stylesheet" />
<link href="css/demo_page.css" rel="stylesheet" />

<script src="js/jquery.js"></script>
<script src="js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$(".jqueryDataTable").dataTable({
"sPaginationType" : "full_numbers",
"bProcessing" : false,
"bServerSide" : false,
"sAjaxSource" : "dataTablesAction",
"bJQueryUI" : true,
"aoColumns" : [
{ "mData": "company" },
{ "mData": "country" },
{ "mData": "year" },
{ "mData": "revenue" }
]
} );
} );
</script>

</head>

<body id="dt_example">
<div id="container">
<h1>Ajax based Gridview in Struts2 using jQuery DataTable plugin</h1>
<div id="demo_jui">
<table class="display jqueryDataTable">
<thead>
<tr>
<th>Company</th>
<th>Country</th>
<th>Year</th>
<th>Revenue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>

Do read :
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Java web application using jQuery
Tab Style Login and Signup example using jQuery in Java web application

Action class

In reply to each request for information that DataTables makes to the server, it expects to get a
well formed JSON object with the parameter below.
1. aaData- The data in a 2D array.

package com.action;

import java.util.List;

import com.model.RevenueReport;
import com.opensymphony.xwork2.Action;
import com.service.BusinessService;

public class GridViewAction implements Action {

private List<RevenueReport> aaData;

public List<RevenueReport> getAaData() {
return aaData;
}

public void setAaData(List<RevenueReport> aaData) {
this.aaData = aaData;
}

public String execute() {
aaData = BusinessService.getCompanyList();
return SUCCESS;
}
}

struts.xml

<struts>
<package name="default" extends="json-default">
<action name="dataTablesAction"
class="com.action.GridViewAction">
<result type="json">grid.jsp</result>
</action>
</package>

</struts>
Note that I have extended json-default package instead of struts-default package and I have
set the result type to json, I have explained about the reason for extending json-default
package in the article AJAX implementation in Struts 2 using JQuery and JSON, please refer
the mentioned link if you are not aware of the same.

Recommended reading:
Ajax in struts 2 implementation without jQuery library

web.xml

Make sure you have done servlet mapping properly in web.xml file as shown below
<web-app>
<display-name>Struts2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExec
uteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Demo




Download It GridViewDataTableStruts.war
Setting up jQuery jTable plugin in Struts 2
framework
Posted by Mohaideen Jamil on Apr 19, 2013 in jQuery, jTable, Struts 2 Tutorial, Struts-2 | 25
comments

In this article we will learn to setup jTable and dependent libraries in Struts 2 web application.
jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding
HTML or Javascript, to know more about jTable please refer the article here

Steps done to set up our application for jTable

Libraries required for the setup,
jQuery
jQuery UI
jTable
struts2-json-plugin-2.x.x.jar
Commonly required Struts 2 jars

Now to start with demonstration of above topic, let us Create a Dynamic Web Project in
Eclipse, with following project structure.



As show in the image download the required library mentioned and place it in js and css folder
of eclipse work-space, and refer these files in the head section in the jsp as shown below.

Setup done from the browser perspective: jTable

jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object
as a response, hence the following configuration needs to be made in Jsp file

Jsp Page

File : jTable.jsp
<html>
<head>
<title>jTable in Struts 2</title>
<!-- jTable Metro theme -->
<link href="css/metro/blue/jtable.css" rel="stylesheet"
type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet"
type="text/css" />

<!-- jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js"
type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#StudentTableContainer').jtable({
title : 'Students List',
actions : {
listAction : 'listAction'
},
fields : {
studentId : {
title : 'Student Id',
width : '30%',
key : true,
list : true,
create : true
},
name : {
title : 'Name',
width : '30%',
edit : false
},
department : {
title : 'Department',
width : '30%',
edit : true
},
emailId : {
title : 'Email',
width : '20%',
edit : true
}
}
});
$('#StudentTableContainer').jtable('load');
});
</script>

</head>
<body>
<div>
<h3>Integrating jTable jQuery plugin and Struts 2
framework</h3>
<div id="StudentTableContainer"></div>
</div>
</body>
</html>

As you can see, jTable just needs a div container as the only HTML tag. It fields options are
explained below:
title: Title of the table.
actions: URLs of actions that are used to create/delete/update/list records.
fields: It defines the field names that represent columns of the record. Note that the field name
should exactly match the instance variable defined in the model class.

Setup done from the servers perspective: Struts 2 Action class

In the Action class, we are populating a list of type Student(Model). Since jTable accepts data
only in Json format, so we are converting this List (Java Object) to Json(Javascript object
Notation) format using struts2-json-plugin.jar.
**Update:: In the article AJAX implementation in Struts 2 using JQuery and JSON I have
explained about usage of struts2-json-plugin.jar clearly, So if you are not aware of how struts2-
json-plugin works, then please go thorough the above mentiioned link.

Action Class

package com.simplecodestuffs.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Action;
import com.simplecodestuffs.model.Student;

public class JtableAction {

private List<Student> records = new ArrayList<Student>();
private String result;

public String list() {
// Add data to Student list
records.add(new Student(1, "Haripriya", "IT",
"xyz@xyz.com"));
records.add(new Student(2, "Dinesh", "ECE",
"xyz@gmail.com"));
records.add(new Student(3, "Prabhu", "MECH",
"abc@gmail.com"));
records.add(new Student(4, "Badru", "ECE",
"efg@gmail.com"));
records.add(new Student(5, "Lahir nisha", "CSC",
"xyz@gmail.com"));
records.add(new Student(6, "Nilafar nisha", "CSC",
"123@gmail.com"));
records.add(new Student(7, "Jamil", "ECE",
"789@gmail.com"));
records.add(new Student(8, "Mahes", "ECE",
"123@gmail.com"));
records.add(new Student(9, "Lourde", "IT",
"xyz@gmail.com"));
result = "OK";

return Action.SUCCESS;
}

public List<Student> getRecords() {
return records;
}

public void setRecords(List<Student> records) {
this.records = records;
}

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}
}

In case of read operations in jTable, Result property must be OK if operation is successful. If
an error occurs, then Result property must be ERROR. If Result is OK, the Records
property will contain an array of records defined in the action class. If its ERROR, a Message
property will contain an error message to show to the user. A sample return value for listAction
is show below

{
"Result":"OK",
"Records":
[{
"studentId":1,
"name":"Haripriya",
"department":"IT",
"emailId":"xyz@xyz.com"
}]
}

Model Class

Create the Model class which will have getters and setters for fields specified in jTable script.

package com.simplecodestuffs.model;

public class Student {

public Student() {
}

public Student(int studentId, String name, String department,
String emailId) {
super();
this.studentId = studentId;
this.name = name;
this.department = department;
this.emailId = emailId;
}

private int studentId;
private String name;
private String department;
private String emailId;

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public String getDepartment() {
return department;
}

public String getEmailId() {
return emailId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setDepartment(String department) {
this.department = department;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}
}

Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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="json-default">
<action name="listAction"
class="com.simplecodestuffs.action.JtableAction"
method="list">
<result type="json">/jTable.jsp</result>
</action>
<action name="getJSONResult"
class="com.simplecodestuffs.action.JtableAction" method="list">
<result type="json" />
</action>
</package>
</struts>
Since jTable accepts data only in Json format, So in order to convert java object to json object I
have extended json-default package instead of struts-default package, please refer
article here for more detail on json-default package.

Demo

On running the application i got the following response



Since I have not handled any exception, so the message displayed in error box is empty.

While debugging the error I found that the json response formed in struts application as below.


Hear the property names of jTable plugin are case sensitive. Only Result, Records and
Message will work. In struts 2 the json response generated is in lower case["result",
"records" and "message"], hence I edited the jtable.js to replace Result to result, Records
to records and Message to message then it worked.

**Note: Along with the above keyword replace TotalRecordCount to totalRecordCount
respectively, since this parameter will be used to display pagination count(Which I will
implement in upcoming tutorial)



Now on including action for create, update and delete in jsp page as below
actions : {
listAction : 'list',
createAction : 'create',
updateAction : 'update',
deleteAction : 'delete'
}

On running the application


On clicking Add new record


On clicking edit button


On clicking delete button


Note :

In the above program I have not included the logic for create, delete and update functions. In
the article CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax I have implemented
CRUD operation using jTable jQuery plugin in Struts 2, and in the article Pagination in Struts 2
using jQuery jTable plugin I have implemented paging feature using the same plugin.



Reference

jTable official website
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in

CRUD Operations in Struts 2 using jTable
jQuery plugin via Ajax
Posted by Mohaideen Jamil on Jun 12, 2013 in Ajax, jQuery, Struts-2 | 34 comments



In the previous article Setting up jQuery jTable plugin with Struts 2 framework I have
explained about how to setup jTable plugin in struts 2 application. This article describes on how
to implement Ajax based curd operation in Struts 2 using the JQuery jTable plugin, If you have
not read the previous articles Setting up jQuery jTable plugin with Struts 2 framework I will
recommend that you read that article first because it explains what jTable plugin is and how
you can integrate it in Struts 2 application.

Steps done to set up our application for jTable

Libraries required for the setup,
jQuery
jQuery UI
jTable
struts2-json-plugin-2.x.x.jar
Commonly required Struts 2 jars

Create a dynamic project in eclipse and setup above required libraries as explained here. The
final project structure of this looks as below.



Setup from the browser perspective: jTable

JSP

<html>
<head>
<title>jTable in Struts 2</title>
<!-- jTable metro styles. -->
<link href="css/metro/blue/jtable.css" rel="stylesheet"
type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet"
type="text/css" />

<!-- jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js"
type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<!-- User defined Jtable js file -->
<script src="js/userDefinedJtable.js"
type="text/javascript"></script>

</head>
<body>
<div style="text-align: center;">
<h3>AJAX based CRUD operation in Struts 2 using jTable
plugin</h3>
<div id="StudentTableContainer"></div>
</div>
</body>
</html>

JS file for implementing CRUD

$(document).ready(function() {
$('#StudentTableContainer').jtable({
title : 'Students List',
actions : {
listAction : 'listAction',
createAction : 'createAction',
updateAction : 'updateAction',
deleteAction : 'deleteAction'
},

fields : {
studentId : {
title : 'Student Id',
width : '30%',
key : true,
list : true,
edit : false,
create : true
},
name : {
title : 'Name',
width : '30%',
edit : true
},
department : {
title : 'Department',
width : '30%',
edit : true
},
emailId : {
title : 'Email',
width : '20%',
edit : true
}
}
});
$('#StudentTableContainer').jtable('load');
});

I have explained the working of above jTable js file in my previous article Setting up JQuery
jTable plugin in Struts 2, hence Im not going to explain it again.

Now create a student table in Oracle database using the query below. On this table we are
going to perform CRUD operation via ajax

create table Student(studentid int,name varchar(50),department
varchar(50),
email varchar(50));

CurdDao
Create a class that performs CRUD operation in database

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.jdbc.DataAccessObject;
import com.model.Student;

public class CrudDao {

private Connection dbConnection;
private PreparedStatement pStmt;

public CrudDao() {
dbConnection = DataAccessObject.getConnection();
}

public void addStudent(Student student) {
String insertQuery = "INSERT INTO STUDENT(STUDENTID, NAME, "
+
"DEPARTMENT, EMAIL) VALUES (?,?,?,?)";
try {
pStmt = dbConnection.prepareStatement(insertQuery);
pStmt.setInt(1, student.getStudentId());
pStmt.setString(2, student.getName());
pStmt.setString(3, student.getDepartment());
pStmt.setString(4, student.getEmailId());
pStmt.executeUpdate();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}

public void deleteStudent(int userId) {
String deleteQuery = "DELETE FROM STUDENT WHERE STUDENTID =
?";
try {
pStmt = dbConnection.prepareStatement(deleteQuery);
pStmt.setInt(1, userId);
pStmt.executeUpdate();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}

public void updateStudent(Student student) {
String updateQuery = "UPDATE STUDENT SET NAME = ?, " +
"DEPARTMENT = ?, EMAIL = ? WHERE STUDENTID =
?";
try {
pStmt =
dbConnection.prepareStatement(updateQuery);
pStmt.setString(1, student.getName());
pStmt.setString(2, student.getDepartment());
pStmt.setString(3, student.getEmailId());
pStmt.setInt(4, student.getStudentId());
pStmt.executeUpdate();

} catch (SQLException e) {
System.err.println(e.getMessage());
}
}

public List<Student> getAllStudents() {
List<Student> students = new ArrayList<Student>();

String query = "SELECT * FROM STUDENT ORDER BY STUDENTID";
try {
Statement stmt = dbConnection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Student student = new Student();

student.setStudentId(rs.getInt("STUDENTID"));
student.setName(rs.getString("NAME"));
student.setDepartment(rs.getString("DEPARTMEN
T"));
student.setEmailId(rs.getString("EMAIL"));
students.add(student);
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return students;
}
}
I hope the above code is self explanatory

Setup from the servers perspective: Servlet

In Struts 2 Action class, I have defined 4 method- create, read, update and delete to perform
CRUD operations. Since jTable accepts data only in Json format, so we are converting this List
(Java Object) to Json(Javascript object Notation) format using struts2-json-plugin.jar.
**Update: In the article AJAX implementation in Struts 2 using JQuery and JSON I have
explained in detail about how to use struts2-json-plugin.jar clearly, So if you are not aware of
how struts2-json-plugin works, then please go thorough the above mentioned link.

Action class

package com.action;

import java.io.IOException;
import java.util.List;

import com.dao.CrudDao;
import com.model.Student;
import com.opensymphony.xwork2.Action;

public class JtableAction {

private CrudDao dao = new CrudDao();

private List<Student> records;
private String result;
private String message;
private Student record;

private int studentId;
private String name;
private String department;
private String emailId;

public String list() {
try {
// Fetch Data from Student Table
records = dao.getAllStudents();
result = "OK";
} catch (Exception e) {
result = "ERROR";
message = e.getMessage();
System.err.println(e.getMessage());
}
return Action.SUCCESS;
}

public String create() throws IOException {
record = new Student();

record.setStudentId(studentId);
record.setName(name);
record.setDepartment(department);
record.setEmailId(emailId);

try {
// Create new record
dao.addStudent(record);
result = "OK";

} catch (Exception e) {
result = "ERROR";
message = e.getMessage();
System.err.println(e.getMessage());
}
return Action.SUCCESS;
}

public String update() throws IOException {
Student student = new Student();

student.setStudentId(studentId);
student.setName(name);
student.setDepartment(department);
student.setEmailId(emailId);

try {
// Update existing record
dao.updateStudent(student);
result = "OK";
} catch (Exception e) {
result = "ERROR";
message = e.getMessage();
System.err.println(e.getMessage());
}
return Action.SUCCESS;
}

public String delete() throws IOException {
// Delete record
try {
dao.deleteStudent(studentId);
result = "OK";
} catch (Exception e) {
result = "ERROR";
message = e.getMessage();
System.err.println(e.getMessage());
}
return Action.SUCCESS;
}

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public String getDepartment() {
return department;
}

public String getEmailId() {
return emailId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setDepartment(String department) {
this.department = department;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Student getRecord() {
return record;
}

public void setRecord(Student record) {
this.record = record;
}

public List<Student> getRecords() {
return records;
}

public String getResult() {
return result;
}

public String getMessage() {
return message;
}

public void setRecords(List<Student> records) {
this.records = records;
}

public void setResult(String result) {
this.result = result;
}

public void setMessage(String message) {
this.message = message;
}
}

If you read my article on CRUD Operations in Java Web Applications using jTable jQuery
plugin via Ajax then you might have noted once difference here, i.e. I have not created any
request or response object in action class to get the student parameters, because those
parameter from jsp file auto bounded to my struts 2 action, this is done via struts2-jquery-
plugin. One only requirement for this parameter to be passed from jsp is, you have create the
member variable for those parameter in action class along with getters and setters as in above
file.

You might be interested to read:
GridView in struts 2
Ajax implementation in Struts 2 without jQuery plugin
Tab Style Login and Signup example using jQuery in Java web application

I have explained in detail about difference response generated for create, read, update and
delete operation in the articleCRUD Operations in Java Web Applications using jTable jQuery
plugin via Ajax, So please refer to this article mentioned above, if you are not aware of the
different response created for CRUD operation in Jtable plugin.

Jtable Issue related to Struts 2

As mentioned in my previous article , the property names of jTable plugin are case sensitive.
Only Result, Records and Message will work. In struts 2 the json response generated is
in lower case["result", "records" and "message"], hence I edited the jtable.js to replace Result
to result, Records to records and Message to message then it worked.
**Note: Along with the above keyword replace TotalRecordCount to totalRecordCount,
since this parameter will be used to display pagination count (Which I will implement in
upcoming tutorial)

Model class

Create Model class used in the controller, which will have getters and setters
for fields specified in jTable script.
package com.model;

public class Student {

private int studentId;
private String name;
private String department;
private String emailId;

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public String getDepartment() {
return department;
}

public String getEmailId() {
return emailId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setDepartment(String department) {
this.department = department;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}
}

DAO Class

Create utility class which connect to database Using Oracle JDBC driver
package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DataAccessObject {
private static Connection connection = null;

public static Connection getConnection() {
if (connection != null)
return connection;
else {
// database URL
String dbUrl = "jdbc:oracle:thin:@localhost:1521:XE";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
// set the url, username and password for the
database
connection = DriverManager.getConnection(dbUrl,
"system", "admin");
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
}

Struts.xml

Make sure that you have the following mapping in struts.xml
<struts>
<package name="default" extends="json-default">
<action name="*Action"
class="com.action.JtableAction"
method="{1}">
<result type="json">/jTable.jsp</result>
</action>
<action name="getJSONResult"
class="com.action.JtableAction" method="list">
<result type="json" />
</action>
</package>
</struts>

web.xml

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepare
AndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Demo

On running the application



On clicking Add new record


Now the new record will be added with fade out animation


On clicking edit button


On clicking delete button


In the next article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging
feature in the CRUD example.



Pagination in Struts 2 using jQuery jTable plugin
Posted by Mohaideen Jamil on Dec 18, 2013 in Ajax, jQuery, Struts-2 | 0 comments



In the previous article Setting up JQuery jTable plugin in Struts 2 I have explained how to
setup jTable plugin in struts 2 and in the article Ajax based curd operation in Struts 2 using
JQuery jTables plugin I have implemented Ajax based curd operation using JTable plugin.

This is the third article on jQuery jTable plugin in Struts 2 that describes on how to implement
pagination feature to do server side paging in struts 2 using the JQuery jTable plugin and it will
not explain how to setup jTable plugin in struts 2 here. So If you have not read the previous
articles Setting up JQuery jTable plugin in Struts 2 and Ajax based curd operation in Struts 2
using JQuery jTables plugin, I will recommend that you read that article first because first one
explains how you can integrate the JTable plug-in with a Struts 2 application and in second
article explains on how to implement ajax based curd operation using jTable plugin. This article
will assume that the code for the integration of the jQuery JTable plug-in is implemented, and
only the code required for implementing pagination in Struts 2 using jTable will be explained
here.

Setup

As described above, the prerequisite for this code is that you integrate the jQuery jTable plugin
into the Struts 2. You can find detailed instructions here, at JQuery jTable plugin in Struts 2, so
now I am going to take the sample application I created for explaining AJAX based crud
operations in jTable plugin and continue to implement paging for that application.

1. Download sample application from here and import the project in eclipse
2. Follow the steps in this article here to create table in database.

Steps to enable Paging:

From the browser perspective: jTable

To enable paging, paging option must set to true. You can also set pageSize option (default
value is 10) in jQuery Script code.

$('#StudentTableContainer').jtable({
//...
paging: true, //Set paging enabled
pageSize: 3, //Set page size
actions: {
//...
},
fields: {
//...
}
});

Note: pageSize sets the initial number of records to be displayed per page.

Modified Jsp page

<!DOCTYPE html>
<html>
<head>
<title>jTable Pagination in Java Web Applications</title>

<!-- Include one of jTable styles. -->
<link href="css/metro/blue/jtable.css" rel="stylesheet"
type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet"
type="text/css" />

<!-- Include jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js"
type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#StudentTableContainer').jtable({
title : 'Students List',
paging : true, //Enable paging
pageSize : 3, //Set page size (default: 10)
actions : {
listAction : 'listAction',
createAction : 'createAction',
updateAction : 'updateAction',
deleteAction : 'deleteAction'
},
fields : {
studentId : {
title : 'Student Id',
width : '30%',
key : true,
list : true,
edit : false,
create : true
},
name : {
title : 'Name',
width : '30%',
edit : true
},
department : {
title : 'Department',
width : '30%',
edit : true
},
emailId : {
title : 'Email',
width : '20%',
edit : true
}
}
});
$('#StudentTableContainer').jtable('load');
});
</script>

</head>
<body>
<div style="text-align: center;">
<h3>jTable Pagination in Java Web Applications</h3>
<div id="StudentTableContainer"></div>
</div>
</body>
</html>

From the servers perspective: Servlet

If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX
call:
jtStartIndex: Start index of records for current page.
jtPageSize: Count of maximum expected records.
And it expects additional information from server:
TotalRecordCount: Total count of records.

In our previous example the url specified in the listAction option has business logic to fetch
all records from database. Now in order to handle pagination this listAction option should fetch
only a part of records for each page, So handle this there are two changes that has to be done
in the server side .

1. Modify oracle query to fetch only a subset of records based on the jtStartIndex and
jtPageSize.
Since these values are sent along with the request as string parameters by jTable so add
following member variable in struts 2 action class and create getters and setters for the same
// Holds Start Page Index
private int jtStartIndex;
// Hold records to be displayed per Page
private int jtPageSize;

2. As mentioned above, jTable need TotalRecordCount to be present in the json response,
For which add a member variable totalRecordCount in struts 2 action class and create getters
and setters for the same.

Now replace the list method in action class with the below code,

public String list() {
try {
// Fetch Data from Student Table
records = dao.getAllStudents(jtStartIndex, jtPageSize);
// Get Total Record Count for Pagination
totalRecordCount = dao.getStudentCount();
result = "OK";
} catch (Exception e) {
result = "ERROR";
message = e.getMessage();
}
return Action.SUCCESS;
}

Changes made at Dao class

Add below two methods in CrudDao.java file
1. Method to get the count of total number of records in the result set.

public int getStudentCount()
{
int count=0;
try
{
Statement stmt = dbConnection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT
FROM STUDENT");
while (rs.next())
{
count=rs.getInt("COUNT");
}
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
return count;
}

2. In order to return only a subset of records according to the page offset (jtStartIndex and
jtPageSize), oracle query should be modified as follows,
In case of Oracle database:
SELECT * from (Select M.*, Rownum R from STUDENT M) where r > + < jtStartIndex> +
and r <= "+< jtStartIndex + jtPageSize >;

In case of MySql database:
select * from STUDENT limit <jtStartIndex>,<jtPageSize>

Now modify getAllUsers in CurdDao.java using below code

public List<Student> getAllStudents(int startPageIndex, int
recordsPerPage) {
List<Student> students = new ArrayList<Student>();
int range = startPageIndex+recordsPerPage;
String query="SELECT * from (Select M.*, Rownum R From STUDENT M)
where r > " + startPageIndex +" and r <= "+range;
try
{
Statement stmt = dbConnection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
Student student = new Student();
student.setStudentId(rs.getInt("STUDENTID"));
student.setName(rs.getString("NAME"));
student.setDepartment(rs.getString("DEPARTMENT"));
student.setEmailId(rs.getString("EMAIL"));
students.add(student);
}
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
return students;
}

This function returns only a subset of records according to the page offset (jtStartIndex and
jtPageSize).

Now on running the application, with the above changes, the final demo looks as shown below:





Struts 2 + Spring Integration Example
Posted by Mohaideen Jamil on Jul 13, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


In this following example we shall see how to integrate Spring and Struts 2 using the struts2-
spring-plugin. We integrate Spring with Struts2 to utilize the Springs Dependency Injection
feature.
First add the org.springframework.web.context.ContextLoaderListener to the web.xml file.

** UPDATE: Spring Complete tutorial now available here.

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

File : 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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"
version="2.5">
<display-name>Struts2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.
StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<listener>
<listener-class>org.springframework.web.context.
ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

By default the applicationContext.xml file will be used for doing the Spring bean configuration.

File : applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloWorldClass" class="com.simplecode.HelloWorld" >
<property name="msg" value="Struts 2 + Spring Integration
Example!" />
</bean>
</beans>

As you can see we have registered the HelloWorld class and injected the Hello World!
message to the message attribute using the setter injection method.
All the Struts 2 action configuration goes in the struts.xml file.

File : 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="helloWorld" class="helloWorldClass">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>

The only change here is instead of referring the com.simplecode.HelloWorld class directly, we
relate it using the bean name given in the spring bean configuration file.
The HelloWorld class is shown below. In the execute() method we simply return SUCCESS
and themessage attribute is set using setter injection.

File : HelloWorld.java

package com.simplecode;

public class HelloWorld
{
private String msg;

public String getMsg()
{
return msg;
}

public void setMsg(String msg)
{
this.msg = msg;
}

public String execute()
{
return "SUCCESS";
}
}

In the index.jsp page we forward the request to the helloWorld action.

<META HTTP-EQUIV="Refresh" CONTENT="0;URL=helloWorld.action">

After invoking the execute() method the user will be directed to the success.jsp page. In this
page we dispaly the message value.




You need to have the following jar files in the WEB-INF/lib directory.

commons-fileupload-1.2.1
commons-io-1.3.2
commons-logging-1.1
freemarker-2.3.13
junit-3.8.1
ognl-2.6.11
struts2-convention-plugin-2.1.6
struts2-core-2.1.6
xwork-2.1.2
struts2-spring-plugin-2.1.6
antlr-runtime-3.0
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3
org.springframework.web-3.0.0.M3
org.springframework.web.servlet-3.0.0.M3
Struts 2 + Log4j integration example
Posted by Mohaideen Jamil on Jun 20, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


In this tutorial we will learn about integrate Log4j with Struts 2 framework.


Download It Logger-Without Library files


Log4j Appender

Create a text file named log4j.properties, put it at the root of the project classpath.
The log4j.properties or appender fileis the Log4j configuration file, it defines how the Log4j
logging mechanism work.

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

In this example, it will log all the logging detail and outputs it to an external file
C:\\loggerfile.txt.
log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loggerfile.txt
log4j.appender.file.MaxFileSize=10MB

log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L
- %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p
%c{1}:%L - %m%n

# Root logger option
log4j.rootLogger=warn, file, stdout


Action Class

To use Log4j in Struts 2 framework, you can get the Log4j logger via Logger.getLogger() and
log it directly.
package com.simplecode.action;

import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;

public class LoggerAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private static final Logger logger =
Logger.getLogger(LoggerAction.class);

public String execute() throws Exception {
logger.warn("Warning .......");
logger.error("Error .......");
return SUCCESS;
}
}

Demo

Now, all the logging details will be logged into the file, named C:\\loggerfile.txt. See sample :
23:37:38,165 WARN LoggerAction:14 Warning .
23:37:38,166 ERROR LoggerAction:15 Error .


Download It Logger-Without Library files

Struts2-Jfreechart integration
Posted by Mohaideen Jamil on May 1, 2014 in JFreeChart, Struts-2 | 1 comment


In this article we will learn to integrate Struts 2 with JFreeChart using struts2-jfreechart-plugin-
x.x.x.jar for creating a pie chart in web application using JFreeChart library.

The JFreeChart is easiest and the most widely used library for creating a wide variety of good
looking charts.
The Struts-JFreeChart plugin allows Struts 2 Actions to easily return generated charts and
graphs.
Instead of streaming a generated chart directly to the HTTP response, this plugin provides a
ChartResult, which handles the generation for you. This allows you to generate the chart in one
class, and render it out in another class, effectively decoupling the view from the Actions.

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

Libraries required :
struts2-jfreechart-plugin-x.x.x.jar
Commonly required Struts 2 jars
jfreechart-x.x.x.jar
jcommon-x.x.x.jar
Jfreechart library can be downloaded here.

Now Create a New Dynamic Web Project in eclipse with following folder structure



Struts 2 Action

File : JfreeChartAction.java
package com.simplecodestuffs.action;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import com.opensymphony.xwork2.Action;

public class JfreeChartAction implements Action {

private JFreeChart chart;

public String execute() throws Exception {

DefaultPieDataset dataSet = new DefaultPieDataset();
dataSet.setValue("Agriculture", 10);
dataSet.setValue("Residential heating", 4);
dataSet.setValue("Commercial products", 15);
dataSet.setValue("Industry", 42);
dataSet.setValue("Transportation", 26);
dataSet.setValue("Others", 3);

chart = ChartFactory.createPieChart(
"Source of Air Pollution ", // Title
dataSet, // Data
true, // Display the legend
true, // Display tool tips
false // No URLs
);

chart.setBorderVisible(true);

return SUCCESS;
}

// This method will get called if we specify <param
name="value">chart</param>
public JFreeChart getChart() {
return chart;
}
}


Recommended reading:
Create Auto-Refreshing Pie Chart/Bar Chart dynamically using JFreeChart
Pie Chart using YUI3 jquery chart plugin in Java web application

Here Jfreechart provides DefaultPieDataset method to set static data and createPieChart()
method creates the pie chart using the dataset.

struts.xml

To use the plugin, have your Struts configuration package extend the jfreechart-default
package, which provides the chart result type.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- package should extend jfreechart-default package -->
<package name="default" namespace="/" extends="jfreechart-
default">
<action name="displayChart"
class="com.simplecodestuffs.action.JfreeChartAction">
<result name="success" type="chart">
<param name="value">chart</param>
<param name="type">jpeg</param>
<param name="width">600</param>
<param name="height">400</param>
</result>
</action>
</package>
</struts>

Jsp page

<html>
<head>
<title>Struts2-Jfreechart integration</title>
</head>
<body>
<h3>Struts2-Jfreechart integration</h3>
<br />
<img src="displayChart"/>
</body>
</html>

In Jsp, servlet is called via img tags src attribute. This triggers the Action and render the image
on the page.

** UPDATE: To Create Auto-Refreshing Pie Chart dynamically the following tutorial will
help here.

Demo

Now right click on the project name and select Run As > Run on Server.




Zip file Struts2-JfreeChart


Struts 2 and Tiles Framework Integration
Posted by Mohaideen Jamil on May 5, 2014 in Struts-2 | 2 comments


Apache Tiles is a templating framework used to simplify the development of web application
user interfaces. Tiles allow defining page fragments which can be combined into a complete
page at runtime. These fragments, or tiles, can be used as reusable templates in order to
reduce the duplication of common page elements or even embedded within other tiles. See the
snapshot below.

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


Advantage of tiles framework
Code reusability
Easy to modify
Easy to remove
Jar Required


Folder structure



web.xml

Provide entry of listener class Struts2TilesListener in the web.xml file.
<listener>
<listener-
class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>

Recommended Article
Introduction to Struts 2 Framework
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2

Jsp Pages

Now We will define the template for our web application in baseLayout.jsp file. This template
will contain different segments of web page (Header, Footer, Menu, Body).

File : baseLayout.jsp
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<style>
.one {
border-style: solid;
border-color: #0000ff;
border-collapse: collapse;
}
</style>
</head>
<body>
<table border="1" align="center" class="one" width="80%">
<tr>
<td height="30" colspan="2" class="one" width="20%">
<tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td height="250" class="one">
<tiles:insertAttribute name="menu" />
</td>
<td width="350" class="one">
<tiles:insertAttribute name="body" />
</td>
</tr>
<tr>
<td height="30" colspan="2" class="one">
<tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>

File : header.jsp
<html>
<body>
<div align="center" style="color: gray; font-weight: bold;">
Struts 2 - Tiles Demo - Header page
</div>
</body>
</html>

File : footer.jsp
<html>
<body>
<div align="center" style="color: gray; font-weight: bold;">
Footer page &copy; SimpleCodeStuffs.com
</div>
</body>
</html>

File : body.jsp
<html>
<body>
<p align="center" style="color: gray;font-weight: bold;">Home
Page</p>
</body>
</html>

File : menu.jsp
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<s:url action="strutsAction" var="strutsAction" />
<s:url action="springAction" var="springAction" />
<div align="center">
Menu <br /> <br /> <br /> <br />

<s:a href="%{strutsAction}">Struts Tutorial</s:a>
<br /> <br />
<s:a href="%{springAction}">Spring Tutorial</s:a>
</div>
<br>
</body>
</html>

File : springTutorial.jsp
<html>
<body>
<p align="center" style="color: gray;font-weight: bold;">Spring
Tutorial !!!</p>
</body>
</html>

File : strutsTutorial.jsp
<html>
<body>
<p align="center" style="color: gray;font-weight:
bold;">Struts Tutorial !!!</p>
</body>
</html>

File : index.jsp
It triggers homeAction during application start up
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=homeAction">

Action Class

package com.simplecodestuffs.action;

public class TilesAction {

public String home() {
return "home";
}

public String struts() {
return "struts";
}

public String spring() {
return "spring";
}
}

struts.xml

In struts.xml, inherit the tiles-default package and define all the result type as tiles
<!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="tiles-default">
<action name="*Action" method="{1}"
class="com.simplecodestuffs.action.TilesAction">
<result name="home" type="tiles">home</result>
<result name="struts" type="tiles">struts</result>
<result name="spring" type="tiles">spring</result>
</action>
</package>
</struts>

Do read :
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Autocomplete in Java web application using jQuery
Tab Style Login and Signup example using jQuery in Java web application

tiles.xml

The tiles.xml file must be located inside the WEB-INF directory, in which define all the tiles
definitions
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

<definition name="baseLayout" template="/baseLayout.jsp">
<put-attribute name="title" value="Template" />
<put-attribute name="header" value="/header.jsp" />
<put-attribute name="menu" value="/menu.jsp" />
<put-attribute name="body" value="/body.jsp" />
<put-attribute name="footer" value="/footer.jsp" />
</definition>

<definition name="home" extends="baseLayout">
<put-attribute name="title" value="Home" />
<put-attribute name="body" value="/home.jsp" />
</definition>

<definition name="struts" extends="baseLayout">
<put-attribute name="title" value="Struts Tutorial" />
<put-attribute name="body" value="/strutsTutorial.jsp" />
</definition>

<definition name="spring" extends="baseLayout">
<put-attribute name="title" value="Spring Tutorial" />
<put-attribute name="body" value="/springTutorial.jsp" />
</definition>

</tiles-definitions>

Demo

Home Page with Tiles


Struts Page with Tiles


Spring Page with Tiles


How to define multiple tiles files in struts 2 application?

To define multiple tiles, you need to add following entry in your web.xml file.
<context-param id="struts_tiles">
<param-
name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
</param-name>
<param-value>
/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value>
</context-param>


Download It Struts2-Tiles
Integrating Quartz Scheduler in Struts 2 Web
Application
Posted by Mohaideen Jamil on Aug 6, 2014 in Quartz Scheduler, Struts-2 | 0 comments



In our previous article we learn about Quartz 2 hello world example along with types of
Triggers in Quartz 2, In this article we shall learn to Integrating Quartz 2 Scheduler in Struts 2
web Application. To know more about Quartz please visit itsOfficial website.

Library required

Commonly Required Struts 2 Jars
commons-logging-1.1.1.jar
log4j-1.2.16.jar
quartz-2.2.1.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar

Scheduler Job

Create a Quartzs job
package com.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class QuartzJob implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Struts 2 + Quartz 2.2.1");
}
}

Servlet Listener

Now Create servlet listener class by implementing ServletContextListener interface and
override contextInitialized and contextDestroyed methods with your logics.
In contextInitialized() method method I have written a code to start the Quartz Scheduler, and
since this method will be executed automatically during Servlet container initialization, hence
the code for Quartz scheduler job gets invoked, and so it runs for every 10 seconds.
contextDestroyed() method will be executed when the application shuts down, So in this
function I have invoked the shutdown function of quartz scheduler

package com.quartz;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzListener implements ServletContextListener {
Scheduler scheduler = null;

@Override
public void contextInitialized(ServletContextEvent
servletContext) {
System.out.println("Context Initialized");

try {
// Setup the Job class and the Job group
JobDetail job =
newJob(QuartzJob.class).withIdentity(
"CronQuartzJob",
"Group").build();

// Create a Trigger that fires every 5
minutes.
Trigger trigger = newTrigger()
.withIdentity("TriggerName", "Group")
.withSchedule(CronScheduleBuilder.cronSchedul
e("0/5 * * * * ?"))
.build();

// Setup the Job and Trigger with Scheduler &
schedule jobs
scheduler = new
StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
catch (SchedulerException e) {
System.err.println(e.getMessage());
}
}

@Override
public void contextDestroyed(ServletContextEvent
servletContext) {
System.out.println("Context Destroyed");
try
{
scheduler.shutdown();
}
catch (SchedulerException e)
{
System.err.println(e.getMessage());
}
}
}

Recommended Article
Interceptors in Struts 2
Creating Custom Interceptors in Struts2
Login Interceptor in Struts 2
web.xml

Configure the listener class QuartzSchedulerListener.java into the web.xml file as shown below
<web-app>
<display-name>Quartz 2 + Struts 2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecut
eFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>
com.quartz.QuartzListener
</listener-class>
</listener>
</web-app>

Demo

Now on starting the Tomcat Server, the project gets started, and so the listener class
QuartzSchedulerListener.java registered in web.xml will be fired, and following logs is obtained
at the console



Difference between Struts2 FilterDispatcher
and StrutsPrepareAndExecuteFilter?
Posted by Mohaideen Jamil on Jan 28, 2013 in Struts-2 | 0 comments


The FilterDispatcher is used in the early Struts2 development, and it has deprecated since
Struts 2.1.3.

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

If you are using Struts version >= 2.1.3, its recommended to upgrade the new filter
class StrutsPrepareAndExecuteFilter

The new filter was introduced for the following reasons
1. There were a lot of issued with the FilterDispatcher and its deployment.
2. New Filter provides a better way to enable customizations and overrides.
3. Make it crystal clear to developers what filters are doing what processes.
4. make dispatch process be more flexible to support things like native operation in OSGi or
plugin system.

For your reference, the following code should be used when you are about to use Struts
version <=2.1.3
1. FilterDispatcher example

...
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
...

The following code should be used when you are about to use Struts version >=2.1.3
2. StrutsPrepareAndExecuteFilter example

...
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
...

How to exclude action methods from validation
in struts2
Posted by Mohaideen Jamil on Jun 13, 2013 in Struts-2 | 0 comments



My Action class have the following methods,
1.addAction
2.deleteAction
3.updateAction
4.populateAction

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

Consider a scenario where I want to apply validation for addAction and deleteAction method
alone and not for other method , then all you to do a configuration in struts.xml file by listing all
the methods you dont want to be run through the validation framework in the excludeMethods
parameter. Since we only want addElement and deleteElement validated, list the other two
methods as follows:

<interceptor-ref name="validation">
<param name="excludeMethods">updateAction,populateAction</param>
</interceptor-ref>

How To Get The ServletContext In Struts 2
Posted by Mohaideen Jamil on Jan 30, 2013 in Struts-2 | 0 comments


In Struts 2 , you can use the following two methods to get the ServletContext object.

1. ServletContextAware

Make your class implements the org.apache.struts2.util.ServletContextAware interface.

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

When Struts 2 servlet-config interceptor is seeing that an Action class is implemented
the ServletContextAwareinterface, it will pass a ServletContext reference to the requested
Action class via the setServletContext()method.

package com.simplecode.action;

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.Action;

public class ContextAction implements ServletContextAware,Action {

ServletContext context;

public String execute() throws Exception
{
return SUCCESS;
}

public void setServletContext(ServletContext context)
{
this.context = context;
}
}

2. ServletActionContext

Get the ServletContext object directly from org.apache.struts2.ServletActionContext


package com.simplecode.action;

import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class ContextAction implements Action
{
public String execute() throws Exception
{
ServletContext context =
ServletActionContext.getServletContext();
return SUCCESS;
}
}

Difference between Action Chaining & Action
redirect in Struts 2
Posted by Mohaideen Jamil on Sep 8, 2013 in Struts-2 | 2 comments

In Struts 2, sometimes you may want to process another action when one action completes.
For example on successfully submitting a form you want to render output from other action.

This can be done by two methods

1) Action Chaining
2) Action redirect



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

Difference between Action redirect & Action Chaining:

Difference between Action Chaining & Action redirect is, Action Redirect starts from scratch, it
is like you called the other action class for the first time while Action Chaining keeps the values
of the first Action class on the value stack and adds the variables of the new action. Look at the
example below to understand the above concepts.

Action Chaining:

<package name="default" extends="struts-default">
<action name="Register"
class="com.simplecode.action.RegisterAction">
<result name="success" type="chain">dbAction</result>
</action>
<action name="dbAction"
class="com.simplecode.action.DataBaseAction">
<result name="success">/success.jsp</result>
</action>
</package>

Action redirect:

<package name="default" extends="struts-default">
<action name="Register"
class="com.simplecode.action.RegisterAction">
<result name="success" type="redirect">dbAction</result>
</action>
<action name="dbAction"
class="com.simplecode.action.DataBaseAction">
<result name="success">/success.jsp</result>
</action>
</package>

Difference between # , $ and % signs in Struts2
Posted by Mohaideen Jamil on Oct 14, 2013 in Struts 2 Tutorial, Struts-2 | 3 comments


Use of #

OGNL is used to refer to objects in the ActionContext as follows:
myObject: object in the ValueStack, such as an Action property
#myObject: object in the ActionContext but outside of the ValueStack
#myObject: ActionContext object that has been created using the Struts2 data tags with the
default action scope (e.g., <s:set name=data value=Some data />, referenced by<s:property
value=#data />)
#parameters.myObject: request parameter
#request.myObject: request-scoped attribute
#session.myObject: session-scoped attribute
#application.myObject: application-scoped attribute
#attr.myObject: attribute in page, request, session, or application scope, searched in that order.

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

The scoped map references above (parameters, request, session, and application) can be
made one of two ways:
1. #scopeName['myObject']
2. #scopeName.myObject

Use of $

Struts2 OGNL does not make use of the dollar sign. However, it can be used to evaluate JSTL
expressions. For example:

Struts2: <s:property value="someProperty" />
(is equivalent to)
JSTL: ${someProperty}

Use of %

% character is used to force OGNL evaluation of an attribute that would normally interpreted as
a String literal. For eample,

<s:url id="urlAtt" action="urlTag.action">
<s:a href="%{urlAtt}">Call Action</s:a>
Now <s:a> tag will query the stack for urlAtt value.
Exception handling in Struts 2
Posted by Mohaideen Jamil on Nov 3, 2013 in Struts-2 | 0 comments



Zip file Struts2Exception.zip



The Struts 2 framework provides some easy way to handle any uncaught exceptions. It works
on exception interceptor which is part of default-stack in struts-default.xml file.

There are two ways to handle uncaught exceptions in Struts2:
Global exception handling: specifies exception mappings which apply to all action classes in
a Struts2.
Exception handling per action: specifies exception mappings which apply to a specific action
class.
Both methods require adding exception mappings in struts.xml configuration file.

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

Global Exception Handling :

Add the following code snippet just after the <package> element in struts.xml file:
<global-results>
<result name="null">/jsp/NullPointer.jsp</result>
<result name="globalException">/jsp/GlobalExceptioon.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping result="null"
exception="java.lang.NullPointerException"/>
<exception-mapping result="globalException"
exception="java.lang.Exception"/>
</global-exception-mappings>

<global-exception-mappings> specifies a set of element which maps an exception type to a
view name.
<global-results> element defines global view names and its mapping page.

Here in global-exception-mapping the exception of type java.lang.NullPointerException is
mapped to the view name null. So when any uncaught exception of type
java.lang.NullPointerException or its sub types is thrown, Struts will redirect users to the view
page mapped with the name null and in the view named null is mapped with the view page
jsp/NullPointer.jsp.

Exception Handling Per Action

If you need to handle an exception in a specific way for a certain action you can use the
exception-mapping node within the action node.
// Here an action configuration adds an addition exception handler.
<action name="Addition" class="simplecode.action.Addition">
<exception-mapping result="error"
exception="java.lang.NumberFormatException" />
<result name="success">/jsp/Success.jsp</result>
<result name="error">/jsp/Error.jsp</result>
</action>

Here If NumberFormatException occurs in Addition action then Error.jsp will be executed else
framework searches in the global exception list and execute the respective page using global-
result type.

In the Error page we can access information of the exception as follows:
1. Exception name: <s:property value=exception/>
2. Exception stack trace: <s:property value=exceptionStack/>
3. Exception in the value stack: <s:property value=[0].top />

Implementation exception handling in Struts 2.

File: Struts.xml

<struts>
<package name="default" extends="struts-default">
<global-results>
<result name="null">/jsp/NullPointer.jsp</result>
<result name="globalException">/jsp/GlobalExceptioon.jsp</result>
</global-results>

// Here the results are expected to be global results.
<global-exception-mappings>
<exception-mapping result="null"
exception="java.lang.NullPointerException"/>
<exception-mapping
result="globalException" exception="java.lang.Exception"/>
</global-exception-mappings>

// Here an action configuration adds an addition exception handler.
<action name="Addition" class="simplecode.action.Addition">
<exception-mapping result="error"
exception="java.lang.NumberFormatException"/>
<result name="success">/jsp/Success.jsp</result>
<result name="error">/jsp/Error.jsp</result>
</action>

<action name="Action1" class="simplecode.action.Action1">
<result name="success">/jsp/Success1.jsp</result>
</action>

<action name="Action2" class="simplecode.action.Action2">
<result name="success">/jsp/Success1.jsp</result>
</action>
</package>
</struts>

Action class

File: Addition.java
For Exception Handling in Action class here if both numbers is not parsed in int, it will throw
NumberFormatException.
package simplecode.action;

import com.opensymphony.xwork2.Action;

public class Addition implements Action
{
private String number1, number2;
private String sum = "";

public String getNumber1() {
return number1;
}

public String getNumber2() {
return number2;
}

public void setNumber1(String number1) {
this.number1 = number1;
}

public void setNumber2(String number2) {
this.number2 = number2;
}

public String getSum() {
return sum;
}

public void setSum(String sum) {
this.sum = sum;
}

public String execute() throws Exception {
int num1 = Integer.parseInt(number1);
int num2 = Integer.parseInt(number2);
int sum = num1 + num2;
setSum("" + sum);
return SUCCESS;
}
}

File: Action1.java throw NullPointerException
package simplecode.action;

import com.opensymphony.xwork2.Action;

public class Action1 implements Action
{
public String execute() throws Exception
{
String string = null;
System.out.println(string.charAt(7));
return SUCCESS;
}
}
File: Action2.java throw NumberFormatException.
package simplecode.action;

import com.opensymphony.xwork2.Action;

public class Action2 implements Action
{
public String execute() throws Exception {
int num = Integer.parseInt("7b");
return SUCCESS;
}
}

Jsp Pages

File: index.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<s:form action="Addition">
<s:textfield label="Number 1" name="number1" />
<s:textfield label="Number 2" name="number2" />
<s:submit label="Add" />
</s:form>
<hr>
Null Pointer Exception example -
<a href="<s:url action="Action1"/>">ActionLink1</a>
<br>
<br> Global Exception -
<a href="<s:url action="Action2"/>">ActionLink2</a>
<br>
</body>
</html>

File : Error.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h2>Unexpected error occurred (Exception per Action page)</h2>
<p>
<font color="red">Please contact your system administrator</font>
</p>
<h3>Error Message</h3>
<br> Exception object transferred to value stack
<s:property value="[0].top" />
<br>
<s:property value="%{exception}" />
<hr />
<h3>Stack Trace</h3>
<s:property value="%{exceptionStack}" />
</body>
</html>

File: NullPointer.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<body>
<h2>Unexpected error occurred (Global - Null Pointer exception)</h2>
<p>
<font color="red">Please contact your system administrator</font>
</p>
<h3>Error Message</h3>
Exception object transferred to value stack
<s:property value="[0].top" />
<br>
<s:property value="%{exception}" />
</body>
</html>

File: GlobalException.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Global - NumberFormatException</title>
</head>
<body>
<h2>Global NumberFormatException occurred</h2>
<p>
<font color="red">Please contact your system administrator</font>
</p>
<h3>Error Message</h3>
<br> Exception object transferred to value stack
<s:property value="[0].top" />
<br>
<s:property value="%{exception}" />
</body>
</html>

Demo

http://localhost:8089/Struts2Exception/



On giving the input as above the result will be as shown.



Global exception- On clicking ActionLink1 and ActionLink2 the following global exception page
will be rendered.





How to Call Struts2 action from java script
Posted by Mohaideen Jamil on Dec 1, 2013 in Struts-2 | 0 comments


Action Class

package com.simplecode.action;
import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport
{
public String trueCall()
{
return SUCCESS;
}

public String falseCall()
{
return SUCCESS;
}
}

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

Jsp Pages

File : confirmBox.jsp

<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Calling Action from java script</title>
<script type="text/javascript">
function confirmBox()
{
var location = confirm("Do you want to go to this page?");
if (location == true)
{
window.location =
"${pageContext.request.contextPath}/trueAction";
}
else
{
window.location =
"${pageContext.request.contextPath}/falseAction";
}
}
</script>
</head>

<body>
<s:submit value="Submit" onclick="confirmBox();"
align="left"></s:submit>
</body>
</html>

Do read :
Call Struts2 action from java script via jquery
Difference between # , $ and % signs in Struts2

File : truePage.jsp

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
<h2>True Action</h2>
</body>
</html>

File :falsePage.jsp

<html>
<head>
<title>Calling Action from java script</title>
</head>
<body>
<h2>False Action</h2>
</body>
</html>

Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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" namespace="/">
<action name="trueAction" method="trueCall"
class="com.simplecode.action.MyAction">
<result>/truePage.jsp</result>
</action>

<action name="falseAction" method="falseCall"
class="com.simplecode.action.MyAction">
<result>/falsePage.jsp</result>
</action>
</package>
</struts>

Recommended Article :
GridView in struts 2 using jQuery DataTable plugin
CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax

Demo

On running the application we get



Here on clicking the submit button, we get a confirm box, in which on clicking Ok, trueAction
gets called and on clicking Cancel, falseAction gets called.

Dynamically add, remove list of objects from jsp
Using Struts2
Posted by Mohaideen Jamil on Dec 1, 2013 in Struts-2 | 14 comments


In this article we shall learn on how to dynamically add, remove list of objects from jsp Using
Struts2.

File : User.java (Model Class)

package com.simplecode.action;

import java.util.Collection;

public class User
{
int regNo;
String name;
Collection<Address> addresses;

public Collection<Address> getAddresses()
{
return addresses;
}

public void setAddresses(Collection<Address> addresses)
{
this.addresses = addresses;
}

public int getRegNo()
{
return regNo;
}

public void setRegNo(int regNo)
{
this.regNo = regNo;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}
}

File : Bean Class

package com.simplecode.action;

public class Address
{
private int houseNo;
private String street;
private String city;
private String country;

public int getHouseNo()
{
return houseNo;
}

public String getStreet()
{
return street;
}

public void setHouseNo(int houseNo)
{
this.houseNo = houseNo;
}

public void setStreet(String street)
{
this.street = street;
}

public String getCountry()
{
return country;
}

public void setCountry(String country)
{
this.country = country;
}

public String getCity()
{
return city;
}

public void setCity(String city)
{
this.city = city;
}
}

In order to implement the above functionality via ajax, do read the article on CRUD Operations
in Struts 2 using jTable jQuery plugin via Ajax

Do read :
AJAX implementation in Struts 2 without JQuery
AJAX implementation in Struts 2 using JQuery and JSON
File : UserAction (Action Class)

package com.simplecode.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction implements Action, ModelDriven<User>
{
User user = new User();

public User getUser()
{
return user;
}

public void setUser(User user)
{
this.user = user;
}

public String execute()
{
return SUCCESS;
}

public User getModel()
{
return user;
}
}

In the above article I have used the concept of ModelDriven interface in struts2, if you are not
aware of what model driven interface is, then please read the article on modeldriven
interface here

Jsp Pages

File : index.jsp
<HTML>
<HEAD>
<title>Add/Remove dynamic rows</title>
<SCRIPT lang="javascript">
function addRow(tableID)
{
var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var counts = rowCount - 1;

var cell1 = row.insertCell(0);
var houseNo = document.createElement("input");
houseNo.type = "text";
houseNo.name = "addresses[" + counts + "].houseNo";
cell1.appendChild(houseNo);

var cell2 = row.insertCell(1);
var street = document.createElement("input");
street.type = "text";
street.name = "addresses[" + counts + "].street";
cell2.appendChild(street);

var cell3 = row.insertCell(2);
var city = document.createElement("input");
city.type = "text";
city.name = "addresses[" + counts + "].city";
cell3.appendChild(city);

var cell4 = row.insertCell(3);
var country = document.createElement("input");
country.type = "text";
country.name = "addresses[" + counts + "].country";
cell4.appendChild(country);

}
</SCRIPT>
</HEAD>
<BODY>

<form action="submit" method="post">
<table>
<tr>
<td>
Reg No
</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</td>
<td><INPUT type="text" name="regNo" /></td>
</tr>
<tr>
<td>Name</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</td>
<td><INPUT type="text" name="name" /></td>
</tr>
<tr><td><br/><b>Addresses</b></td>
</tr>

</table>


<TABLE id="addressesTable">
<TR>
<TD>House No</TD>
<TD>Street</TD>
<TD>City</TD>
<TD>Country</TD>
</TR>
<TR>
<TD><INPUT type="text" name="addresses[0].houseNo"
/></TD>
<TD><INPUT type="text" name="addresses[0].street"
/></TD>
<TD><INPUT type="text" name="addresses[0].city"
/></TD>
<TD><INPUT type="text" name="addresses[0].country"
/></TD>
</TR>
</TABLE>
<INPUT type="button" value="Add More"
onclick="addRow('addressesTable')" />
<input type="submit" value="SUBMIT" />
</form>
</BODY>
</HTML>

File : result.jsp
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>User Details</title>
</head>
<body>
<h1>User information</h1>
ID : <s:property value="regNo" /><br />
Name : <s:property value="name" /><br />
Addresses :

<table>
<tr>
<td width="10%">Reg No :</td>
<td width="15%" >Street :</td>
<td width="15%" >City :</td>
<td width="15%">Country :</td>
</tr>

<s:iterator value="addresses">
<tr>
<td width="10%"><s:property value="houseNo" /></td>
<td width="15%" ><s:property value="street"/></td>
<td width="15%" ><s:property value="city"/></td>
<td width="15%"><s:property value="country"/></td>
</tr>
</s:iterator>
</table>

</body>
</html>

Recommended reading :
Struts 2 iterator tag
Difference between # , $ and % signs in Struts2

Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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="submit"
class="com.simplecode.action.UserAction">
<result name="success">result.jsp</result>
</action>
</package>
</struts>

Run it

On running the application



Input



Output



Changing default style of s:actionerror /
s:actionmessage tag
Posted by Mohaideen Jamil on Jan 4, 2014 in Struts 2 Tutorial, Struts-2 | 0 comments



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

Recommended reading
Struts 2 ActionError & ActionMessage Example

Similar kind of approach is followed for <s:actionmessage /> tag.

Common Support class for Action classes in
Struts 2
Posted by Mohaideen Jamil on Oct 14, 2013 in Struts 2 Tutorial, Struts-2 | 0 comments


When you are about to create a complex application in struts 2, it is better to create a Base
action class for all your actions and make this class extend ActionSupport and implement all
necessary interfaces such as SessionAware, ParameterAware, HttpServletRequest,
HttpServletResponse etc and implement all other common logic for your actions in this class.
So now when you are about to create an action class, just extending this support class will suit
all your need in action class.

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

Following is a snippet of my ApplicationSupportAction class:

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

public abstract class ApplicationSupportAction extends ActionSupport
implements
SessionAware, ServletRequestAware, ParameterAware,
ServletResponseAware
{
private static final long serialVersionUID = 1L;

// Field to store session context.
private Map<String, Object> session;

// Field to store request parameters.
private Map<String, String[]> parameters;

// Field to store HttpServletRequest.
private HttpServletRequest servletRequest = null;

// Field to store HttpServletResponse.
private HttpServletResponse servletResponse = null;

// Result code for session expired action.
public final static String SESSION_EXPIRED =
"SessionExpired";

// Result code for Logout action.
public final static String LOGOUT = "logout";

// .....

// action to be triggered when session expires
public String execute() throws Exception
{
HttpSession sessionObj =
servletRequest.getSession(true);

if (sessionObj.getAttribute("currentUser") == null)
{
return SESSION_EXPIRED;
}
return executeAction();
}

public abstract String executeAction() throws Exception;

@Override
public void setSession(Map<String, Object> session)
{
this.session = session;
}

@Override
public void setParameters(Map<String, String[]> parameters)
{
this.parameters = parameters;
}

@Override
public void setServletResponse(HttpServletResponse
servletResponse)
{
this.servletResponse = servletResponse;
}

@Override
public void setServletRequest(HttpServletRequest
servletRequest)
{
this.servletRequest = servletRequest;
}

public Map<String, Object> getSession()
{
return session;
}

public Map<String, String[]> getParameters()
{
return parameters;
}

public HttpServletRequest getServletRequest()
{
return servletRequest;
}

public HttpServletResponse getServletResponse()
{
return servletResponse;
}

public String getCurrentUser()
{
return (String) session.get("currentUser");
}

public void setCurrentUser(String currentUser)
{
session.put("currentUser", currentUser);
}
}

You can handle following common concerns in the ApplicationSupportAction
class:
1. Session
2. Parameters
3. Http Request and response
4. Validating session.
5. Common result codes etc.

ApplicationSupportAction class would reduce your action class code to a large extent by
handling lot of common concerns in one centralized place.
There Is No Action Mapped For Namespace /
And Action Name YourActionName
Posted by Mohaideen Jamil on Jul 19, 2013 in Struts 2 Tutorial | 0 comments


Problem

Many Struts 2 developers have claimed that they had configured the action class properly but a
page not found error occurs when we try to access the action class and will get the following
error message in the browser(If the developer mode is enabled).

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

Struts has detected an unhandled exception:

Messages:
There is no Action mapped for namespace / and action name
"yourActionName".

Stacktraces
There is no Action mapped for namespace / and action name
"yourActionName".
- [unknown location]

com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy
.java:178)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.j
ava:61) ...



Solution

The above error message is saying that the action class is not available, it means you are did
something wrong in your action class configuration, it may be a namespace error, just double
check the name.
Heres a working action class configuration in struts.xml file, may use for your reference.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-
default">

<action name="myAction"
class="com.Simplecode.action.myAction" >
<result name="success">jsp/my.jsp</result>
</action>

</package>
</struts>

Assume the project root context is Struts2, so, you can access the above action via this URL

http://localhost:8089/Struts2/myAction.action

And it will be better if you learn about Struts2 Namespace configuration to avoid this issue

S-ar putea să vă placă și