Wednesday, January 30, 2013

First Example

<--Previous                                                      Next-->

In this application we will take the input from the textbox and we will print it in another page using the struts2 framework.  To create this example we need the following things:
1.   Views (jsps) which will take the input and which will print the message. In our application we have two jsps.  Index.jsp is used to take the input and success.jsp is used to print the processed message.
2.   Action which will take the message from the index.jsp and process it.
3.   Struts.xml which is having the details of mapping for the actions and the views.
Now create the dynamic web project (First Example) in the eclipse. Add the required jars in to the lib folder.
Configure filter dispatcher in the following way in web.xml.  We can find the web.xml in the WEB-INF folder of the application (First Example) we created.
Folder structure:


Web.xml:
< ?xml version="1.0" encoding="UTF-8"?>


filter>

filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</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>


Note: The FilterDispatcher (org.apache.struts2.dispatcher.FilterDispatcher) is used in the early Struts development, and it’s deprecated since Struts 2.1.3. If you are using Struts version >= 2.1.3, it’s always recommend to declared the new filter class as StrutsPrepareAndExecuteFilter
Index.jsp:

In the index.jsp we will have one text box from which we will give the input to the application.  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!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=ISO-8859-1">

<title>Basic Struts 2 Application - Welcome</title>
</head>

<body>

<h1>Welcome To Struts 2!</h1>
<form action="hello" method="post">

<br/>

Hello:  <input type="text" name="sayHello" value=""/>
<br/>

<input type="submit" name="submit" value="say hello"/>

</form>

</body>

</html>




Action class:


package com.javaguide4beginners;

public class HelloExample {
private String sayHello;

public String getSayHello() {
 return sayHello;
}

public void setSayHello(String sayHello) {
 this.sayHello = sayHello;
}

public String execute(){
 return "success";
}
}
Success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hello ${request.sayHello}
</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>
<include file="struts-default.xml"/>
<package name="javaguide" extends="struts-default">
<action name="hello" class="com.javaguide4beginners.HelloExample">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>

Basic Flow of Execution of Struts2 and Jars Needed

<--Previous                                                        Next -->





Based on the above diagram, one can explain the user's request life cycle in Struts 2 as follows:
1.       User sends a request to the server for requesting for some resource (i.e. pages).
2.       The FilterDispatcher looks at the request and then determines the appropriate Action.
3.       Configured interceptors functionalities apply such as validation, file upload etc.
4.       Selected action is executed to perform the requested operation.
5.       Again, configured interceptors are applied to do any post-processing if required.
6.       Finally the result is prepared by the view and returns the result to the user.
Jars needed to run Struts 2 applications:
  1. We can download the latest jars of struts2 frame work from the following link. http://struts.apache.org/download.cgi
  2.  Extract the downloaded folder. We will see the folder with the name ‘Struts-version’. Inside that folder there is folder called ‘lib’. We can find all the jars that are needed to run the struts 2 applications.
  3. There are many jars in that folder for multiple purposes.  But to run the basic Struts 2 application we need the following jars.
a.       commons-logging-1.1.1.jar
b.      commons-fileupload-1.2.2.jar
c.       commons-io-2.0.1
d.      commons-lang-3.3.1
e.     freemarker-2.3.19.jar
f.     ognl-3.0.6.jar
g.    struts2-core-2.3.8.jar
h.     xwork-2.3.8.jar
i.      sturts2-convention-plugin-2.3.8
The last jar that is struts2-convention-plugin-2.3.8.jar is needed if we are using annotions.
Note: The version numbers may be different, those are based on the struts2 version you downloaded.

Components Needed to Build Struts2 Applications


<--Previous                                                                                      Next-->

1.       User Forms (view):
  1. Here the user form means jsps in our case as we use the jsps for to represent the data to the user.  We will write the presentation login in the jsps.  In the struts 2 framework jsps act as the view part of the MVC design pattern.
  2. These jsps contains the action to where this request should go. And by default every request will go the FilterDispatcher.

2.       Filter Dispatcher (Controller)
a.  The controller’s job is to map requests to actions. In a web application, the incoming HTTP requests can be thought of as commands that the user issues to the application.
b.  One of the fundamental tasks of a web application is routing these requests to the appropriate set of actions that should be taken within the application itself. This controller’s job is like that of a traffic cop or air traffic controller.
c.    The role of the controller is played by the Struts 2 FilterDispatcher. This important object is a servlet filter that inspects each incoming request to determine which Struts 2 action should handle the request.
d.  The framework handles all of the controller work for us. We just need to inform the framework which request URLs map to which of your actions. We can do this with XML-based configuration files or Java annotations. 
      3.       Action (Model):
a.  Action is the main component of the struts2 framework.  This will act as the Model component in the Struts2 framework.
b.  Each URL is mapped to some specific action, and that action is responsible to provide the processing logic for that particular request.
c.   It is the mediator between the view part and the database.
d.   The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.
e.   Optionally you can extend the ActionSupport class which implements six interfaces including Action interface.
Implementation of the Action interface defined as follows
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;
}
These are the main components of the struts2 framework.  But to make them work we need some more configurations.  Those are, configuring the FilterDispatcher as controller and configuration for mapping the requests to the Actions.
4.       Web.xml (Deployment descriptor):
As FilterDispatcher act as a controller and it is responsible to pick up every request from the view part.  So we need to configure this in the web.xml to use this as a front controller.  We can configure FilterDispatcher in the following ways.


If any request comes with the .do extension it will go to the FilterDispatcher.

< filter >
< filter-name >struts2 < /filter-name>
< filter-class > org.apache.struts2.dispatcher.FilterDispatcher
< /filter-class >
< /filter >

 In struts based web applications, we should send all the requests to the web application through the FilterDispatcher along with their path values. To achieve above requirement it is suggestible to use extension match method for defining url pattern for FilterDispatcher.

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*.do</url-pattern>
</filter-mapping>

If any request comes with the .do extension it will go to the FilterDispatcher.

5.       Struts.xml (Struts configuration file):


The struts.xml file contains the configuration information that you will be modifying as actions are developed. This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes.

?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="helloworld" extends="struts-default">
    
      <action name="hello"
            class="com.javaguide.struts2.HelloWorldAction"
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
      </action>
      <-- more actions can be listed here -->

   </package>
   <-- more packages can be listed here -->

</struts>


The first thing to note is the DOCTYPE. All struts configuration file need to have the correct doctype as shown in our little example. is the root tag element, under which we declare different packages using tags. Here allows separation and modularization of the configuration. This is very useful when you have a large project and project is divided into different modules.
Say, if your project has three domains - business_applicaiton, customer_application and staff_application, you could create three packages and store associated actions in the appropriate package. The package tag has the following attributes:

Attribute
Description
name (required)
The unique identifier for the package
Extends
Which package does this package extend from? By default, we use struts-default as the base package.
Abstract
If marked true, the package is not available for end user consumption.
Namespace
Unique namespace for the actions

The constant tag along with name and value attributes will be used to override any of the following properties defined in default.properties, like we just set struts.devMode property. Setting struts.devMode property allows us to see more debug messages in the log file.
We define action tags corresponds to every URL we want to access and we define a class with execute() method which will be accessed whenever we will access corresponding URL.
Results determine what gets returned to the browser after an action is executed. The string returned from the action should be the name of a result. Results are configured per-action as above, or as a "global" result, available to every action in a package. Results have optional name and type attributes. The default name value is "success".
Struts.xml file can grow big over time and so breaking it by packages is one way of modularizing it, but struts offers another way to modularize the struts.xml file. You could split the file into multiple xml files and import them in the following fashion.


<?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>
     <include file="my-struts1.xml"/>
     <include file="my-struts2.xml"/>
</struts>

Struts2 Framework


<--Previous                                                      Next-->

  1. The high-level design of Struts 2 follows the well-established Model-View-Controller design pattern.
  2. As Struts2 follows MVC design pattern it will provide the clear separation between the components.
  3. The MVC design pattern identifies three distinct concerns: model, view, and controller. In Struts 2, these are implemented by the action, result, and FilterDispatcher respectively as shown in the below figure.

Struts 2 framework features:
Here are some of the great features that may force you to consider Struts2
  1. POJO forms and POJO actions - Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class.
  2. Tag support - Struts2 has improved the form tags and the new tags allow the developers to write less code.
  3. AJAX support - Struts2 has recognized the takeover by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, that function very similar to the standard Struts2 tags.
  4. Easy Integration - Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2.
  5. Template Support - Support for generating views using templates.
  6. Plugin Support - The core Struts2 behavior can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2.
  7. Profiling - Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools.
  8. Easy to modify tags - Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags.
  9. Promote fewer configurations - Struts2 promotes fewer configurations with the help of using default values for various settings. You don't have to configure something unless it deviates from the default settings set by Struts2.
  10. View Technologies: - Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT)
The above are just the top ten features of Struts 2 that makes it an enterprise ready framework.

Struts 2 disadvantages:
Though Struts 2 comes with a list of great features but I would not forget to mention few negative points about Struts 2 and would need lots of improvements:
  1. Bigger learning curve - To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework.
  2. Poor documentation - Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized.
  3. Less transparent - With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework.

Struts 2

MVC Architecture and Frame work

                                                                                                            Next-->


To design web applications sunmicrosystems provided the following two standard architectures.
1.       Model-I architecture or Model-I web architecture or MVC-I architecture.
2.       Model-II architecture or Model-II web architecture or MVC-II architecture.

Model-I Architecture:
  1. In the Model-I web application architecture we should use some jsp components to pick up the request and process that request.
  2.  As jsps are processing all the requests, this architecture is also called Jsp Front or page centric architecture.
  3.  In this architecture jsp’s acts as the views and as controllers and java beans as the model.


Disadvantages:
  1.  Model-I architecture designed on the basis of 2-tier architecture which will provide tightly coupled design for web applications.
  2. In Model-I architecture there is no clear separation between the components which are used for presentation and business processing.
  3.  In Model-I architecture we should use the existed jsp features may not be sufficient.  There may be a requirement to provide java code inside jsp pages, which is against for jsp specification.


Model-II Architecture:
  1.  In Model-II architecture we will use Servlet as controller; some set of jsps as view part and java beans, ejb’s as model.
  2.  As we use servlet as controller, this is called Servlet Front or Servlet Centric architecture.
  3. This architecture will provide loosely coupled design and which will provide clear separation between the components which are used for presentation and business processing.
  4. In this we should send all the requests to controller only not to view part and model part.
  5. In this architecture there are no restrictions on number of jsp pages utilization but all the jsps should not contain any java code.
  6.  Here we should not have page to page navigation, but we should have page controller to page navigation.
  7. Controller may interact with the model part for storing user state not for the sake of getting the data.
  8. And view part will interact with the controller for the sake of getting the data, not for storing the data.





Frame Work and Need of Framework:
  1.  If we want to design any web application on the basis of MVC architecture then we should explicitly provide the controller Servlet, internationalization support, data validation and respective exception handling mechanism along with the application logic even though they are common for every web application.
  2. As above requirements are common for every application it is better to have them as a predefined support.
  3.  To fulfill the above requirements some third party vendors have provided their own procedure called as frameworks.

Definition 1:
                It is a pre-fabricated software component that programmer can reuse, extend, customize to design customized web applications in the easiest manner.
Definition 2:
                It is semi implemented, reusable, customizable, sharable application which will provide very good environment to design and execute applications in the easiest manner.
Definition 3:
                Framework is collection of tools, utilities which will provide very good environment to design and execute customized web application in the easiest manner in less time.
Advantages:
  1.  Framework will reduce the development time by allowing parallel design.
  2.  Framework will reduce development cost as it was provided 50% of the application development.
  3. Framework will improve the productivity.
  4.  Framework will provide some generic services like login, security and transaction support etc.
Framework will provide default flow of execution for the web application, by this there is no need to check the flow of the execution explicitly.