Dec 22, 2009

Developing a Struts2 application step by step

Introduction

Struts is a well-organized framework based on MVC architecture. In Model-View-Controller Architecture, Model stands for the business or database code, View represents the page design code and the Controller for navigational code. All these together makes Struts an essential framework for building Java applications. But with the development of new and lightweight MVC based frameworks like Spring, Stripes and Tapestry, it becomes necessary to modify the Struts framework. So, the team of Apache Struts and another J2EE framework, WebWork of OpenSymphony joined hand together to develop an advanced framework with all possible developing features that will make it developer and user friendly.

The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

Struts 2 Architecture

The following diagram depicts the architecture of Struts 2 Framework and also shows the initial request goes to the servlet container such as tomcat, which is then passed through standard filer chain.

clip_image001

The filter chain includes:

  • Action ContextCleanUp filter:
    The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin.
  • FilterDispatcher:
    Next the FilterDispatch is called, which in turn uses the ActionMapper to determine whether to invoke an Action or not. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy.
  • ActionProxy:
    The ActionProxy takes help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates. 
    Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.

Features of Struts 2 Framework

Some of the general features of the current Apache Strut 2 framework are given below. 
Architecture – First the web browser request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the functions like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.

Tags - Tags in Strut 2 allow creating dynamic web applications with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.

MVC – The Model View Controller in Strut 2 framework acts as a coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.

Configuration – Provides a deployment descriptor to initialize resources in XML format. The initialization takes place simply by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.

Configuration files are re-loadable that allows changes without restarting a web container.

Other Features:

  • All framework classes are based on interfaces and core interfaces are independent from HTTP. 
  • Check boxes do not require any kind of special application for false values.
  • Any class can be used as an action class and one can input properties by using any JavaBean directly to the action class. 
  • Strut 2 actions are Spring friendly and so easy to Spring integration. 
  • AJAX theme enables to make the application more dynamic. 
  • Portal and servlet deployment are easy due to automatic portlet support without altering code.

The request handling in every action makes it easy to customize, when required.

Developing and Configuring the Struts 2 Application

This is a step-by-step process of how to develop a web application from scratch using the Struts 2 Framework.

Prerequisites:

    • Java SDK (I am currently using version 1.5)
    • Servlet API 2.4
    • JSP API 2.0
    • Ant (using version 1.7)
    • Apache Tomcat (using version 6.0)
    • Eclipse 3.3 (Recommended, but not necessary)

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\struts2login\pages\" folder. Here is the code of login.jsp file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<%@ 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 loginsuccess.jsp page displays the Login Success message when user is authenticated successfully. Here is the code of loginsuccess.jsp file:



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Login Success</title>
</head>
<body>
<p align="center">
<font color="#000080" size="5">
Login Successful
</font>
</p>
</body>
</html>




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\ struts2login \WEB-INF\src\java\com" directoy. Here is the code of Login.java action class:



package com;
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>
*/
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;
}
}


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="com.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).



CSS file (main.css)



This css file is used to enhance the presentation of the login form. The main.css is saved into "\webapps\struts2login\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 {
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: 1.8em;
}

#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;
}


Validation Login application





The Struts 2 validation framework uses xml based configuration file. The file name should be <Your action class> -validation.xml. In our case our action class name is Login.java, so our validation configuration file will be Login-validation.xml. The Login-validation.xml will be saved into "webapps\struts2login\WEB-INF\src\java\com" directory. Here is the content of Login-validation.xml file:



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Login name is required</message>
</field-validator>

</field>

<field name="password">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Password is required</message>
</field-validator>
</field>
</validators>


Running Struts 2 Login Example



We will run the example on Tomcat 6.0 server and check how it works.



Running Tomcat - To run the Tomcat, go to its bin directory and then double click on startup.bat. The startup.bat will start the tomcat.



Testing application - To test the application type http://localhost:8080/struts2login/. Your browser should show the Login page as shown below:



clip_image001[5]



Now click on the "Login" button. Application will show the following error screen:



clip_image002



Now enter any password except "Admin", application will again show the error. This error is actually generated in the Action class.



clip_image003



Now enter the valid password "Admin" and click on "Login" button. Now the application will show you the welcome message as shown below.



clip_image004



Conclusion



Here we have seen the overview of a new framework that is getting popularity nowadays. We have gone through the Struts, architecture, advantages and developing and configuring the Struts application. This is just an introduction to know it better we need to dig it more. It has lots more to know, it has lots of features that we have discussed very briefly, and it has lots of other features to be known.



The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own.



Reference




0 comments:

Text Widget

Copyright © Vinay's Blog | Powered by Blogger

Design by | Blogger Theme by