Tuesday, August 2, 2011

Struts MVC Architecture

The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.

The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.

The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet.


The following events happen when the Client browser issues an HTTP request.


  • The ActionServlet receives the request.

  • The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.

  • During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.



When the ActionServlet receives the request it does the following tasks.

  • Bundles all the request values into a JavaBean class which extends Struts ActionForm class.

  • Decides which action class to invoke to process the request.

  • Validate the data entered by the user.

  • The action class process the request with the help of the model component. The model interacts with the database and process the request.

  • After completing the request processing the Action class returns an ActionForward to the controller.

  • Based on the ActionForward the controller will invoke the appropriate view.

  • The HTTP response is rendered back to the user by the view component.

Saturday, November 7, 2009

Struts 2 Login Application

Developing Struts 2 Login Application
In this section we are going to develop login application based on Struts 2 Framework. Our current login application does not validate the user against the database. Instead login name and password are validated against the hardcode values (User: Admin and Password: Admin) in the actions class.

Working of the application

1. Login page is displayed to take the input.
2. User enters user name and password and then clicks on the "Login" button.
3. User validation is done in action class and if user enters Admin/Admin in the user name/password fields, then success pages is displayed. Otherwise the error message is displayed on the screen.

Steps to develope the application

Here are simple and easy steps to develop Login page in the using Struts 2 framework.

1. # Develop Login Form
The GUI of the application consists of login form (login.jsp) and success message page (loginsuccess.jsp).
The login.jsp is used to display the login page to the user. In our application it is saved in "webapps\struts2tutorial\pages\" folder. Here is the code of login.jsp file:


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

<html>

<head>

<title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"
type="text/css"/>

</head>

<body>

<s:form action="doLogin" method="POST">

<tr>

<td colspan="2">


Login

</td>


</tr>


  <tr>
   <td colspan="2">

         <s:actionerror />

         <s:fielderror />

  
</td>

  </tr>

<s:textfield name="username" label="Login name"/>

<s:password name="password" label="Password"/>

<s:submit value="Login" align="center"/>

</s:form>


</body>

</html>

The code :

<s:actionerror />


<s:fielderror />


displays action errors and field validation errors.

The code <s:form action="doLogin" method="POST">generates the html form for the application.

The code :
<s:textfield name="username" label="Login name"/>

<s:password name="password" label="Password"/>


generates Login Name and Password fields.


The submit button is generated through <s:submit value="Login" align="center"/>

code.

When application is executed it generates the following html code:


<html>
<head>
<title>Struts 2 Login Application!</title>

<link href="/struts2tutorial/css/main.css" rel="stylesheet"
type="text/css"/>


</head>
<body>
<form id="doLogin" name="doLogin" onsubmit="return true;"
action="/struts2tutorial/jitendra/doLogin.action" method="POST">
<table class="wwFormTable">

<tr>
<td colspan="2">

Login
</td>

</tr>

<tr>
<td class="tdLabel"><label for="doLogin_username" class="label">

Login name:</label>
</td>
<td><input type="text" name="username" value="" id="doLogin_username"/>
</td>
</tr>


<tr>
<td class="tdLabel"><label for="doLogin_password" class="label">
Password:</label></td>
<td><input type="password" name="password" id="doLogin_password"/>

</td>
</tr>

<tr>
<td colspan="2"><div align="center"><input type="submit"
id="doLogin_0" value="Login"/>
</div></td>
</tr>

</table></form>
</body>

</html>


On viewing the above generated html code you will find that Struts 2 automatically generates form, html table, label for the html elements. This is the another great feature of Struts as compared to Struts 1.x.

The loginsuccess.jsp page displays the Login Success message when
user is authenticated successfully. Here is the code of loginsuccess.jsp file:


<html>

<head>


<title>Login
Success</title>


</head>


<body>



<p align="center"><font
color="#000080" size="5">Login
Successful</font></p>


</body>


</html>



2. Developing Action Class

Now let's develop the action class to handle the login request. In Struts 2
it is not necessary to implement the Action interface, any POJO object with
execute signature can be used in Struts 2. The Struts 2 framework provides a base ActionSupport class
to implement commonly used interfaces. In our action class (Login.java) we
have implemented ActionSupport interface. Our "Login.java" is
saved in the "webapps\struts2tutorial\WEB-INF\src\java\net\jitendra"
directoy. Here is the code of Login.java action class:


package net.jitendra;

import com.opensymphony.xwork2.ActionSupport;

import java.util.Date;





/**

 <p> Validate a user login. </p>


 */

public  class Login  extends ActionSupport {





    public String execute() throws Exception {


        System.out.println("Validating login");

    if(!getUsername().equals("Admin"|| !getPassword().equals("Admin")){


            addActionError("Invalid user name or password! Please try again!");

            return ERROR;

    }else{


      return SUCCESS;

    }

  }





    // ---- Username property ----



    /**


     <p>Field to store User username.</p>

     <p/>

     */

    private String username = null;






    /**

     <p>Provide User username.</p>

     *

     @return Returns the User username.


     */

    public String getUsername() {

        return username;

    }



    /**

     <p>Store new User username</p>


     *

     @param value The username to set.

     */

    public void setUsername(String value) {


        username = value;

    }



    // ---- Username property ----



    /**

     <p>Field to store User password.</p>


     <p/>

     */

    private String password = null;





    /**

     <p>Provide User password.</p>


     *

     @return Returns the User password.

     */

    public String getPassword() {


        return password;

    }



    /**

     <p>Store new User password</p>

     *


     @param value The password to set.

     */

    public void setPassword(String value) {


        password = value;

    }



}


3. Configuring action mapping (in struts.xml)

Now we will create action mapping in the struts.xml file. Here is the code
to be added in the struts.xml:

<action name="showLogin">

<result>/pages/login.jsp</result>

</action>



<action name="doLogin" class="net.jitendra.Login">

<result name="input">/pages/login.jsp</result>

<result name="error">/pages/login.jsp</result>

<result>/pages/loginsuccess.jsp</result>

</action>

In the above mapping the action "showLogin" is used to display the login page and "doLogin" validates the user using action class (Login.java).
4. CSS file (main.css)

This css file is used to enhance the presentation of the login form. The main.css
is saved into "\webapps\struts2tutorial\css" directory.

Here is the code of main.css:

@CHARSET "UTF-8";



body {

font: 12px verdana, arial, helvetica, sans-serif;

background-color:#FFFFFF;






table.wwFormTable {

font: 12px verdana, arial, helvetica, sans-serif;

border-width: 1px;

border-color: #030;

border-style: solid;

color: #242;


background-color: #ada;

width: 30%;

margin-left:35%;

margin-right:35%;

margin-top:15%;






table.wwFormTable th {

}



table.wwFormTable tr td {

background-color: #dfd;

margin: 5px;


padding: 5px;

}



.tdLabel {

/*

border-width: 1px;


border-color: #afa;

border-style: solid;

*/

font-weight: bold;

align: top;






.label {





.errorMessage {

color: red;

font-size: 0.8em;






#headerDiv {

border-style: solid;

border-width: 1px 1px 0px;

border-color: black;


padding: 5px;

background-color: #7a7;

/* height: 22px; */

height: 1.8em;

/* margin-bottom: 12px; */

}




#buttonBar {

border-width: 0px 1px 1px;

border-style: solid;

border-color: black;

color: white;


margin-bottom: 12px;

background-color: #7a7;

height: 1.6em;

padding: 5px;

}




#appName {

color: white;

font-size: 1.8em;

}



#pageTitle {


font-size: 1.4em;

color: #dfd;

clear: none;

}



#appName, #pageTitle {


float: right;

}



#menuContainer {

float: left;

}




#brandingContainer {

float: right:

text-align: right;

}

In the next section we will learn how to add validation to the login application.

Friday, November 6, 2009

Struts Configuration file - struts.xml

In this section we will introduce you to the struts.xml file. This section explains you how best you can use the struts.xml file for you big projects.

The struts.xml File

The Struts 2 Framework uses a configuration file (struts.xml) to initialize its own resources. These resources include:

* Interceptors that can preprocess and postprocess a request
* Action classes that can call business logic and data access code
* Results that can prepare views using JavaServer Pages, Velocity and FreeMarker templates

At runtime, there is a single configuration for an application. Prior to runtime, the configuration is defined through one or more XML documents, including the default struts.xml document. There are several elements that can be configured, including packages, namespaces, includes, actions, results, interceptors, and exceptions.


The struts.xml file is the core configuration file for the framework and it should be present in the class path of your web application. Features of struts 2 configuration file:

* The struts.xml file allows to break big struts.xml file into small files and configuration files to be included as needed. Here is the example:


<struts>

.....
......


<include file="file1.xml"/>

<include file="file2.xml"/>

.....

.....


</struts>


* You can even place struts-plugin.xml file in the JAR, and it will be automatically plugged into the application. This helps the programmers to develop self-configured components.

* If you want to use the frameworks such as Freemaker and Velocity modules, then the templates can also be loaded from classpath. This enables the developer to package entire module just in single JAR file.

Structure of the struts.xml file

In the last section we developed and tested the Hello World application. Here is the sample struts.xml file from the last example.


<?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.enable.DynamicMethodInvocation"
value="false" />



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



<package name="jitendra" namespace="/jitendra" extends="struts-default">



<action name="HelloWorld" class="net.jitendra.Struts2HelloWorld">



<result>/pages/HelloWorld.jsp</result>

</action>



<!-- Add actions here -->

</package>


<!-- Add packages here -->



</struts>


The struts.xml file must confirm to the Struts 2 Document Type Definition (DTD)

The DTD provides information about the structure and the elements that the struts.xml file should have.
Here is the Struts 2.0 DTD :



<!--
Struts configuration DTD.
Use the following DOCTYPE

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

-->



<!ELEMENT struts (package|include|bean|constant)*>



<!ELEMENT package (result-types?, interceptors?,
default-interceptor-ref?, default-action-ref?, global-results?,
global-exception-mappings?, action*)>

<!ATTLIST package name CDATA #REQUIRED
extends CDATA #IMPLIED
namespace CDATA #IMPLIED
abstract CDATA #IMPLIED
externalReferenceResolver NMTOKEN #IMPLIED>



<!ELEMENT result-types (result-type+)>



<!ELEMENT result-type (param*)>

<!ATTLIST result-type name CDATA #REQUIRED
class CDATA #REQUIRED
default (true|false) "false">



<!ELEMENT interceptors (interceptor|interceptor-stack)+>



<!ELEMENT interceptor (param*)>



<!ATTLIST interceptor name CDATA #REQUIRED
class CDATA #REQUIRED>



<!ELEMENT interceptor-stack (interceptor-ref+)>

<!ATTLIST interceptor-stack name CDATA #REQUIRED>



<!ELEMENT interceptor-ref (param*)>

<!ATTLIST interceptor-ref name CDATA #REQUIRED>



<!ELEMENT default-interceptor-ref (param*)>

<!ATTLIST default-interceptor-ref name CDATA #REQUIRED>



<!ELEMENT default-action-ref (param*)>

<!ATTLIST default-action-ref name CDATA #REQUIRED>



<!ELEMENT global-results (result+)>



<!ELEMENT global-exception-mappings (exception-mapping+)>



<!ELEMENT action (param|result|interceptor-ref|exception-mapping)*>

<!ATTLIST action name CDATA #REQUIRED class CDATA #IMPLIED
method CDATA #IMPLIED
converter CDATA #IMPLIED>



<!ELEMENT param (#PCDATA)>

<!ATTLIST param name CDATA #REQUIRED>



<!ELEMENT result (#PCDATA|param)*>

<!ATTLIST result name CDATA #IMPLIED
type CDATA #IMPLIED>



<!ELEMENT exception-mapping (#PCDATA|param)*>

<!ATTLIST exception-mapping name CDATA #IMPLIED
exception CDATA #REQUIRED
result CDATA #REQUIRED>



<!ELEMENT include (#PCDATA)>



<!ATTLIST include file CDATA #REQUIRED>



<!ELEMENT bean (#PCDATA)>

<!ATTLIST bean type CDATA #IMPLIED name CDATA #IMPLIED
class CDATA #REQUIRED scope CDATA #IMPLIED
static CDATA #IMPLIED
optional CDATA #IMPLIED
>



<!ELEMENT constant (#PCDATA)>

<!ATTLIST constant name CDATA #REQUIRED value CDATA #REQUIRED >



It is possible to remove the “struts.xml” file from your application completely if the functionality of your application does not depends on it. There are few configurations that can be handled alternatively such as annotations, “web.xml” startup parameters, and alternate URL mapping schemes. Still, there are few configurations that always need the “struts.xml” file like the global results, exception handling, and the custom interceptor stacks.

Exploring struts.xml

The tag is the root tag for the struts.xml. It may contain the following tags : package, include, bean and constant.

1. The Package Tag :

Packages are a way to group actions, results, result types, interceptors, and interceptor-stacks into a logical configuration unit. Conceptually, packages are similar to objects in that they can be extended and have individual parts that can be overridden by "sub" packages.

The tag is used to group together configurations that share common attributes such as interceptor stacks or URL namespaces. It may also be useful to organizationally separate functions, which may be further separated into different configuration files.

The package element has one required attribute, name, which acts as the key for later reference to the package. The extends attribute is optional and allows one package to inherit the configuration of one or more previous packages - including all interceptor, interceptor-stack, and action configurations.

Note that the configuration file is processed sequentially down the document, so the package referenced by an "extends" should be defined above the package which extends it.

The optional abstract attribute creates a base package that can omit the action configuration.
AttributeRequiredDescription
nameyeskey for other packages to reference
extendsnoinherits package behavior of the package it extends
namespacenoprovides a mapping from the URL to the package.
abstractnodeclares package to be abstract (no action configurations required in package)

1. name – unique name is given for a package.
2. extends – the name of a package that this package will extend; all configuration information (including action configurations) from the extended package will be available in the new package, under the new namespace.
3. namespace – the namespace provides a mapping from the URL to the package. i.e. for two different packages, with namespace attributes defined as “pack1” and “pack2”, the URLs would be something like “/webApp/pack1/my.action” and “/webApp/pack2/my.action”
4. abstract – if this attribute value is “true” the package is truly a configuration grouping and actions configured will not be accessible via the package name. It is important to make sure you are extending the correct parent package so that the necessary pre-configured features will be available to you.

2. The Include Tag:


The tag is used to modularize a Struts2 application that needs to include other configuration files. It contains only one attribute “file” that provides the name of the xml file to be included. This file has exactly the same structure as the “struts.xml” configuration file. For example, to break a configuration file of a finance application, you might choose to group together the invoices, admin, report configurations etc into separate files:




<struts>




<include file="invoices-config.xml"/>

<include file="admin-config.xml" />

<include file="reports-config.xml" />

</struts>



While including files, order is important. The information from the included file will be available from the point that the include tag is placed in the file.


There are some files that are included implicitly. These are the “strutsdefault.xml” and the “struts-plugin.xml” files. Both contains default configurations for result types, interceptors, interceptor stacks, packages as well as configuration information for the web application execution environment (which can also configured in the “struts.properties” file). The difference is that “struts-default.xml” provides the core configuration for Struts2, where “struts-plugin.xml” provides configurations for a particular plug-in. Each plug-in JAR file should contain a “struts-plugin.xml” file, all of which are loaded during startup.



3. The Bean Tag


Most applications won't need to extend the Bean Configuration. The bean element requires the class attribute which specifies the Java class to be created or manipulated. A bean can either


1. be created by the framework's container and injected into internal framework objects, or

2. have values injected to its static methods


The first use, object injection, is generally accompanied by the type attribute, which tells the container that which interface this object implements.


The second use, value injection, is good for allowing objects not created by the container to receive framework constants. Objects using value inject must define the the static attribute.

AttributeRequiredDescription
classyesthe name of the bean class
typenothe primary Java interface
this class implements
namenothe unique name of this
bean; must be unique among other beans that specify the same type
scopenothe scope of the bean; must
be either default, singleton, request, session,
thread
staticnowhether to inject static
methods or not; shouldn't be true when the type is
specified
optionalnowhether the bean is
optional or not



Bean Example (struts.xml)

<struts>


  <bean type="jitendra.net.ObjectFactory" name="factory" class="jitendra.net.MyObjectFactory" />

    ... 



</struts>



4. The Constant Tag


There are two key roles for constants.


1. They are used to override settings like the maximum file upload size or whether the Struts framework should be in devMode(= development mode) or not.

2. They specify which Bean should be chosen, among multiple implementations of a given type.


Constants can be declared in multiple files. By default, constants are searched for in the following order, allowing for subsequent files to override by the previous ones:


* struts-default.xml

* struts-plugin.xml

* struts.xml

* struts.properties

* web.xml


The struts.properties file is provided for backward-compatiblity with WebWork. In the struts.properties file, each entry is treated as a constant. In the web.xml file, any FilterDispatcher initialization parameters are loaded as constants.


In the various XML variants, the constant element has two required attributes : name and value.

AttributeRequiredDescription
nameyesthe name of the constant
valueyesthe value of the constant




Constant Example (struts.xml)

<struts>

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

</struts>



Constant Example (struts.properties)



struts.devMode = true

Thursday, November 5, 2009

Struts2 Writing JSP, Java and Configuration for Hello World Application

In this section we will write JSP, Java and required configuration files for our Struts 2 Hello World application. Now in struts 2 struts.xml is used to configure the applications.

Understanding the application

Our application is very simple application that displays Hello World message along with current date and time of the server. When user clicks on the "Run Struts 2 Hello World Application" link on the tutorial home page, a request is sent to the struts framework. Then struts framework sends the input to the action class (in our case Struts2HelloWorld.java). After action is fired the Result selects the resource "/pages/HelloWorld.jsp" to render the response.

In this example we have to develop three parts view, Action class and mapping (struts.xml) to couple action and page. By creating these three components we are separating the application in three parts View, Model and Controller.


Developing View:
This page is used to display the result on the browser. The HelloWorld.jsp is view part of our application. Create "HelloWorld.jsp" in the struts2tutorial\pages directory and add the following content:



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

<html>

<head>

<title>Struts 2 Hello World Application!</title>

</head>


<body>

<h2><s:property value="message" /></h2>

<p>Current date and time is: <b><s:property value="currentTime" /></b>

</body>


</html>



The line <%@ taglib prefix="s" uri="/struts-tags" %> declares data tag library of struts. The struts data tag is used to display the dynamic data. The tag and calls the methods getMessage() and getCurrentTime() respectively of the Struts2HelloWorld action class and merges the values with response.

Developing Action (to interact with Model):

Now create Struts2HelloWorld.java and saves it to the "struts2tutorial\WEB-INF\src\java\net\jitendra" directory. This action class creates the message to be displayed on the screen. Here is the code of Struts2HelloWorld.java:



import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

public class Struts2HelloWorld extends ActionSupport {

public static final String MESSAGE = "Struts 2 Hello World Tutorial!";

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

private String message;

public void setMessage(String message){
this.message = message;
}

public String getMessage() {
return message;
}

public String getCurrentTime(){
return new Date().toString();
}
}



Developing Controller Configuration File:

Struts 2 uses the struts.xml file for configuring the application. Create struts.xml file and save it in the "struts2tutorial\WEB-INF\src" directory with the following content.


<?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.enable.DynamicMethodInvocation" value="false" />

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



<package name="jitendra" namespace="/jitendra" extends="struts-default">




<action name="HelloWorld" class="net.jitendra.Struts2HelloWorld">

<result>/pages/HelloWorld.jsp</result>

</action>



<!-- Add actions here -->

</package>






<!-- Add packages here -->



</struts>


The struts.xml file should be present in the class path of the application, you can either include it in the jar and place in the lib directory of the application or place it in the classes directory of the web application
. In our application we are using ant build tool which is including it in the jar file.

Building the application

I am assuming that you have already installed ant build tool on your machine. Since we are using the ant built tool, building application by using is very easy. To build the application open command prompt and go to "struts2tutorial\WEB-INF\src" directory of the web application and issue the "ant" command. The ant build tool will compile the java file and create jar file "struts2tutorial.jar" into the lib directory of your web application. Here is the output of ant build tool:

C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src

>ant

Buildfile: build.xml



clean:

[delete] Deleting directory C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes


[mkdir] Created dir: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes



prepare:



resources:



compile:


[javac] Compiling 1 source file to C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src\classes

[jar] Building jar: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\lib\struts2tutorial.jar



project:



all:




BUILD SUCCESSFUL

Total time: 7 seconds

C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src

>

Testing Struts 2 Hello World Application

In the above section we have compiled our application and now finally we will test our application. To test the application start the tomcat server and type http://localhost:8080/struts2tutorial/ and then select "Run Struts 2 Hello World Application" from the list.
Here is the screen shot of our struts 2 tutorial home page:

Select "Run Struts 2 Hello World Application" link. Our first application "Struts 2 Hello World" will look like the following:

The application will display message "Struts 2 Hello World Tutorial!" along with current date and time of the server.

How application works?

Here is the brief description on how Struts 2 Hello World Application works:

Your browser sends a request to the web server for the URL http://localhost:8080/tutorial/HelloWorld.action.

1. When you click on the "Run Struts 2 Hello World Application" link, the browser sends a request for the url http://localhost:8080/struts2tutorial/jitendra/HelloWorld.action. The container requests for the resource "HelloWorld.action". By default web.xml file of struts blank application is configured to route all the request for *.action through org.apache.struts2.dispatcher.FilterDispatcher. Here is the configuration from web.xml file:

struts2
org.apache.struts2.dispatcher.FilterDispatcher



struts2
/*


2. Then the framework looks for the mapping for the action "HelloWorld" and then framework instantiates the appropriate class and calls the execute method. In this case action class is Struts2HelloWorld. Here is the configuration file from struts.xml which defines the action mapping:

/pages/HelloWorld.jsp


3. Then the execute method sets the message and returns SUCCESS.
public String execute() throws Exception {
setMessage(MESSAGE);
return SUCCESS;
}

Then framework determines which page is to be loaded if SUCCESS is returned. In our case framework tells the container to load HelloWorld.jsp and render the output.

In the struts 2 framework Actions are used to process the form and user request. The execute method of the action returns SUCCESS, ERROR, or INPUT value. Then based on these values framework tells the container to load and render the appropriate result.

4. Container process the HelloWorld.jsp and generates the output.

5. Then the output in the HTML format is sent to the browser.

Download the application and source code:
You can download the application and source code of the tutorial and to save your time and efforts spent on configuring the application. Click here to download the code.

Our goal is to provide the working skeleton of the application based on ant tool. So you can download the application and then use ant tool to compile the java classes. Application is in the exploded directory structure and can be deployed as it is on tomcat server. If any of our visitor finds and problem please discuss it. We request you to share your experiences with us.

Struts 2 Hello World Application Example, Learn how to develop Hello World application in struts 2.

In this section we will develop Hello World application based on Struts 2 Framework. Our Struts 2 Hello World application is your first step towards developing applications based on Struts 2 Framework. We are here providing step by step guide for developing Hello World application in Struts 2 framework.

Tutorial covers basic steps like creating directory structure, developing build.xml file to build the application using ant build tool. Then we explained Java, JSP and configuration files that are required in this application.

Creating directory structure for the project

Step1: Extract struts 2 download and copy struts2-blank-2.0.6.war(If you are using latest version of

struts 2 then version may be different for you) to your tomcats webapps directory. Rename struts2-blank-2.0.6.war to struts2tutorial and unzip it in the tomcats webapps directory. Now start the tomcat and type http://localhost:8080/struts2tutorial/ into your browser. You browser should show look like:


Congratulations you have successfully installed struts 2 blank application to start with.

Step 2: Now delete the content of struts2tutorial\WEB-INF\src and struts2tutorial\WEB-INF\classes directories, as we don't need these files that comes with struts 2 blank application.

Step 3: Create build.xml file in the struts2tutorial\WEB-INF\src and paste the following content in the build.xml file.


<project name="Struts 2 Tutorial" basedir="../" default="all">
<!-- Project settings -->
<property name="project.title" value="Struts 2 Tutorials"/>

<property name="project.jar.file" value="struts2tutorial.jar"/>

<path id="class.path">

<fileset dir="lib">

<include name="**/*.jar"/>

</fileset>

<fileset dir="libext">

<include name="**/*.jar"/>

</fileset>

</path>

<!-- Classpath for Project -->

<path id="compile.classpath">

<pathelement path ="lib/commons-beanutils.jar"/>

<pathelement path ="lib/commons-digester.jar"/>

<pathelement path ="lib/struts.jar"/>

<pathelement path ="libext/servlet-api.jar"/>

<pathelement path ="libext/catalina-ant.jar"/>

<pathelement path ="classes"/>

<pathelement path ="${classpath}"/>

</path>

<!-- Check timestamp on files -->

<target name="prepare">

<tstamp/>
<copy
file="src/struts.xml"
todir="src/classes"/>


</target>
<!-- Copy any resource or configuration files -->

<target name="resources">

<copy todir="src/classes" includeEmptyDirs="no">

<fileset dir="src/java">

<patternset>

<include name="**/*.conf"/>

<include name="**/*.properties"/>

<include name="**/*.xml"/>

</patternset>

</fileset>

</copy>

</target>

<!-- Normal build of application -->

<target name="compile" depends="prepare,resources">

<javac srcdir="src" destdir="src/classes"
debug="true" debuglevel="lines,vars,source">

<classpath refid="class.path"/>

</javac>

<jar

jarfile="lib/${project.jar.file}"

basedir="src/classes"/>

</target>
<!-- Remove classes directory for clean build -->

<target name="clean"

description="Prepare for clean build">

<delete dir="classes"/>

<mkdir dir="classes"/>

</target>

<!-- Build Javadoc documentation -->

<target name="javadoc"

description="Generate JavaDoc API docs">

<delete dir="./doc/api"/>

<mkdir dir="./doc/api"/>

<javadoc sourcepath="./src/java"

destdir="./doc/api"

classpath="${servlet.jar}:${jdbc20ext.jar}"

packagenames="*"

author="true"

private="true"

version="true"

windowtitle="${project.title} API Documentation"

doctitle="&lt;h1&gt;${project.title}
Documentation (Version ${project.version})&lt;/h1&gt;"

bottom="Copyright &#169; 2002">

<classpath refid="compile.classpath"/>

</javadoc>

</target>

<!-- Build entire project -->

<target name="project" depends="clean,prepare,compile"/>

<!-- Create binary distribution -->

<target name="dist"

description="Create binary distribution">

<mkdir

dir="${distpath.project}"/>

<jar

jarfile="${distpath.project}/${project.distname}.jar"

basedir="./classes"/>

<copy

file="${distpath.project}/${project.distname}.jar"

todir="${distpath.project}"/>



<war

basedir="../"

warfile="${distpath.project}/${project.distname}.war"

webxml="web.xml">

<exclude name="${distpath.project}/${project.distname}.war"/>

</war>

</target>


<!-- Build project and create distribution-->

<target name="all" depends="project"/>

</project>




Step 4: Create directory libext under the struts2tutorial\WEB-INF\ then you copy latest Servlets api jar (in our case servlet-api.jar) file over there. This library file will be used to compile Servlets in our application.

Step 5: Now create directories java and classes under struts2tutorial\WEB-INF\src. The directory struts2tutorial\WEB-INF\src\java will be used to put all the java sources file and directory struts2tutorial\WEB-INF\src\classes will be used by ant build utility to store compiled java files.

Now we have successfully created the directory structure and ant build file for our Struts 2 Hello World Application. In the next section we will create JSP, Java file and the configuration file and then test our Struts 2 Hello World application.

Download and Installing Struts 2

In this section we will download and install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and configure it as our development server. Then we will download Struts 2.0 and install the struts-blank application on the tomcat server to check the examples that come with the struts-blank application.

Downloading Struts 2.0

Visit the Struts download site http://struts.apache.org/download.cgi and download the Struts 2.0 for this tutorial.



We have downloaded the Struts 2.0.6 (struts-2.0.6-all.zip) for this tutorial.

Download the Tomcat

Download the latest version of tomcat from http://tomcat.apache.org/download-55.cgi. We have downloaded apache-tomcat-5.5.20.zip for this tutorial.


I am assuming that latest version of Java is installed on your system
. Extract downloaded file and run the C:\apache-tomcat-5.5.20\bin\startup.bat to start the tomcat. Type http://localhost:8080/ in your browser, it should show the welcome page in the browser window as shown below.



Congratulations you have now successfully installed latest version of tomcat for learning Struts 2.0. Now we will install the struts-blank application on the tomcat container and test the application.

Extracting Struts 2.0 distribution and installing on tomcat
Extract the downloaded struts distribution struts-2.0.6-all.zip into your favorite directory. To install the struts blank application copy "struts2-blank-2.0.6" from "\struts-2.0.6-all\struts-2.0.6\apps" into the webapps directory of tomcat. Tomcat will automatically deploy the application.


Feb 25, 2007 11:42:23 PM org.apache.coyote.http11.Http11BaseProtocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Feb 25, 2007 11:42:24 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Feb 25, 2007 11:42:24 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/141 config=null
Feb 25, 2007 11:42:24 PM org.apache.catalina.storeconfig.StoreLoader load
INFO: Find registry
server-registry.xml at classpath resource
Feb 25, 2007 11:42:24 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6672 ms
Feb 25, 2007 11:52:55 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive struts2-blank-2.0.6.war


To test the struts-blank application type http://localhost:8080/struts2-blank-2.0.6 in the browser and the struts-blank application get displayed in your browser window.



Click the English link and familiarize yourself with Struts Blank sample application.

Struts 2.0 distribution also contains the following sample applications that you can try:

* struts2-mailreader-2.0.6.war
* struts2-portlet-2.0.6.war
* struts2-showcase-2.0.6.war

You can simply copy these files to the webapps directory of your tomcat server. Tomcat will automatically deploy these applications and then you can test these applications.


Tuesday, November 3, 2009

Struts 1.x Vs Struts 2.x

In the following section, we are going to compare the various features between the two frameworks. Struts 2.x is very simple as compared to struts 1.x, few of its excelent features are:

1. Servlet Dependency:

Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original
request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2. Action classes

Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework.
Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts
2 Action object.

3. Validation
Struts1 and Struts 2 both supports the manual validation via a validate method.
Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4. Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5. Testability

Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6. Harvesting Input

Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input.
However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7. Expression Language

Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

8. Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9. Type Conversion

Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10. Control Of Action Execution

Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.


Simply visit Yavrim.comClick here for a great link