Pages

Tuesday, December 13, 2011

How Struts Works?

Struts has a filter dispatcher similar to that in Hello World! application. Its fully qualified name is org.apache.struts2.dispatcher.FilterDispatcher. To use it, register it in the deployment descriptor (WEB.XML file) using this filter and filter-mapping elements.
                                                                                                      
<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>
                                                                                                     

There's a lot that a filter dispatcher in a Model 2 application has to do and Struts' filter dispatcher is by no means an exception. Since Struts has more, actually much more, features to support, its filter dispatcher could grow infinitely in complexity. However, Struts approaches this by splitting task processing in its filter dispatcher into subcomponents called interceptors. The first interceptor you'll notice is the one that populates the action object with request parameters.

In a Struts application the action method is executed after the action's properties are populated. An action method can have any name as long as it is a valid Java method name.

FilterDispatcher finds that if any action require to execute at the initial phase, if require it will invoke the action, otherwise, it will move control to index page of the application.

The first things that a filter dispatcher does is verify the request URI and determine what action to invoke and which Java action class to instantiate. The filter dispatcher in Hello World! did this by using a string manipulation method. However, this is impractical since during development the URI may change several times and you will have to recompile the filter each time the URI or something else changes.


For matching URIs with action classes, Struts uses a configuration file named struts.xml.
Basically, you need to create a struts.xml file and place it under WEB-INF/classes. You define all actions in the application in this file. Each action has a name that directly corresponds to the URI used to invoke the action. Each action declaration may specify the
fully qualified name of an action class, if any. You may also specify the action method name unless its name is execute, the default method name Struts will assume in the absence of an explicit one.
An action class must have at least one result to tell Struts what to do after it executes the action method. There may be multiple results if the action method may return different results depending on, say, user inputs.


The struts.xml file is read when Struts starts. In development mode, Struts checks the timestamp of this file every time it processes a request and will reload it if it has changed since the last time it was loaded. As a result, if you are in development mode and you change the struts.xml file, you don't need to restart your web container. Saving you time. Configuration file loading will fail if you don't comply with the rules that govern the struts.xml file. If, or should I say when, this happens, Struts will fail to start and you must restart your container. Sometimes it's hard to decipher what you've done wrong due to unclear error messages. If this happens, try commenting out actions that you suspect are causing it, until you isolate and fix the one that is impending development.









 

Monday, December 12, 2011

Hello World! Application



Welcome to the world of struts 2 framework. In this article you'll get how to develop basic Hello World! Application using struts 2 in Netbeans 7. As operating system I am using Linux Ubuntu but, it does not matter which OS you use, the only thing matter is Struts 2.

Softwares you'll need.
These are the sites from where you can download all needed softwares and file.
  1. JDK 1.5 or above. (Download)
  2. Netbeans 7 (Download)
    There is option for the particular platform supported version in both above software.
  3. Apache struts 2 jar file. (Download)
You do not need to install server separately, with Netbeans set-up you can install two servers, Glassfish and Apache tomcat. You can use either at once for deploy and running the application.




Lets do it!
Create web application from the File -> New Project, from Netbeans.


Give your project name and set physical path of the project.
 

Select the server from the list and the Java EE version. You can set your context path.
 [Note : It is preferable to select Java EE 5.]


 Directory Structure

After completion of start up process you'll get the directory structure of the project like this.

Now first thing you have to do is add some struts 2 JAR file. Just add below mentioned JAR files from the Struts 2 you have downloaded.
  • commons-logging-1.0.4.jar
  • freemarker-2.3.8.jar
  • ognl-2.6.11.jar
  • struts2-core-2.0.12.jar
  • xwork-2.0.6.jar
Struts 2 is combine of many jar files. This jar file version may differ with the version of the Struts 2.
Note : We'll study each JAR files in future articles.

The above directory structure represent the basic structure. You have to take care about the files you are going to create.
  1. All the JSP files should kept in Web Pages folder.
  2. Keep you STRUTS.XML and Property file in WEB-INF -> classes(You can choose your name here)
  3. Keep your action class files in Source Packages folder.
Take a look at below directory structure of this program for reference.

  • HelloStruts
    • Web Pages
      • META-INF
        • context.xml
      • WEB-INF
        • classes
          • ApplicationResources.Properties
          • struts.xml
        • WEB.XML
      • index.jsp
      • welcome.jsp
    • Source Packages
      • javabysm.struts2
        • HelloStruts.java
    • Libraries
      • common-logging-1.0.4.jar
      • freemarker-2.3.8.jar
      • ognl-2.6.11.jar
      • struts2-core-2.0.14.jar
      • xwork-2.0.7.jar
      • JDK 1.6 (Note: JDK version is what you have installed)
      • Apache Tomcat 7.0.11 (Note: Apache Tomcat version is what you have installed)
    • Configuration Files
Make sure you follow the structure coz it may create problem if file are not at there places.


WEB.XML

WEB.XML is the deployment descriptor which leads the execution of the project. You can say this is the entrance of the project execution. In this application we are using FilterDispatcher. This filter executes actions by consulting the ActionMapper and determining if the requested URL should invoke an action. If the mapper indicates it should, the rest of the filter chain is stopped and the action is invoked. This is important, as it means that filters like the SiteMesh filter must be placed before this filter or they will not be able to decorate the output of actions.

 
Index.jsp


As you can see in the above image of INDEX.JSP there are few tags belong to struts 2 framework.
First of all the tag <%@taglib ... %> need to include and use struts 2 tags.

Next one is <s:actionerror/> The actionerror tag is a UI tag that renders action errors (in the jsp pages.) if they exists while the actionmessage tag renders action messages if they exists. We have created an action class that uses methods addActionMessage(String) and addActionError(String) within the execute() method. The addActionMessage(String) will print the passed string on the success jsp page while the addActionError(String) will print the passed string on the error jsp page.

<s:form> is same as we have in JSP, the difference is JSP form tag directly calls the servlet where as in struts 2 action refers to the action mentioned in the struts.xml file.

On the click of submit button the respective action in the struts.xml file will call.


Welcome.jsp

Above image represent the welcome.jsp file. Same as index.jsp we have included the struts tag library.
We have used <s:property > tag to display the value of the class attribute. The property tag is a generic tag that is used to get the property of a value, which will default to the top of the stack if none is specified.

HelloStruts.java

Above is the action or we can say class which have the business logic. Above action class has one String attribute named USERNAME. As execute() method which a default method for any struts 2 action class.
Method execute() return success if user have inserted something in the textbox in the index.jsp, else it return error. In addition it sets the ActionError with the value of property name error.login. The valu of error.login will reflect in the tag <s:actionerror> in the index.jsp page.
At the end of the execute() method control will move to struts.xml file and respective result tag will execute. If it returns success then Welcome.jsp will call, otherwise Index.jsp.


STRUTS.XML


The Struts 2 Framework uses a configuration file (struts.xml) to initialize its own resources. These resources include:
  • Interceptors that can pre-process and post-process 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
Note that in above configuration file, we have defined hellostruts action of our application. Two result paths are mapped with hellostruts depending on the outcome of execute() method. If execute() method returns success, user will be redirected to Welcome.jsp else to Index.jsp.
Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify the resource bundle file that we created in struts.xml. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).
Our HelloStruts(POJO) contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, like call(); then we should specify the method name in
<action name="hellostruts" method=”call” class="javabysm.struts2.HelloStruts">
ApplicationResources.Properties

Resource Bundle:
Resource Bundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password or Invalid Username/Password.
We have defined an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled.
Struts.xml map this value for us in the JSP file as we use <constant> tag in it.

e.g. <constant name="struts.custom.i18n.resources" value="ApplicationResources" />

The value attribute of above tag represent name of the Properities file. With use of this functionality we can use constants of the properties file in out JSP file.

e.g. <s:textfield name="username" key="label.username" size="20" />

The attribute KEY assigned a value label.username which is nothing but a constant in properties file. The value of the particular constant will assign here.

That's it!
All you need to do now is run the application. You'll get something like below.

 
You'll get error if you keep text box empty and press the submit button.




Thursday, December 8, 2011

Model 2 Overview

Model 2 is based on the Model-View-Controller (MVC) design pattern, the main concept behind the Smalltalk-80 user interface. Because the term "Design Pattern" was not in exist at that time, the named was MVC paradigm.
An application implementing the MVC pattern consists of three modules: model, view, and controller.

View takes care of display or client side of the application.
Model is nothing but the application data and business logic encapsulated.
Controller is responsible for receive/ response client request and forward client request to particular model.

In Model 2, POJOs are act as model both in struts 2 and struts 2, where as, servlet and filters act as controller. Struts 1 employs servlet controller and struts 2 uses filter. Finally JSP act as a view in both struts version.  There are some more technologies we can use instead of JSP.
Freemarker, is well-supported but there are a few issues when using some of the S2 tags because of the way FreeMarker works.
Velocity's support is there, but has somewhat tapered off. 

It recommended that either to use JSP or freemarker.
 



Wednesday, December 7, 2011

Why struts 2?

Struts 2 is the combination of struts 2 action framework and webwork.

There are some key features in struts 2 as explained below.

1. Simplified design : Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent. Struts 2 Action classes are framework independent and are simplified to look as simple POJOs(Plain Old Java Classes). Framework components are tried to keep loosely coupled. 

2. Simplified actions : Actions are simple POJOs. Any java class with execute() method can be used as an Action class. Even we don't need to implement interfaces always. 

3. No more ActionForms  : ActionForms feature is no more known to the struts2 framework. Simple Java-bean flavoured actions are used to put properties directly. No need to use all String properties.

4. Simplified testability : Struts 2 Actions are HTTP independent and framework neutral. This enables to test struts applications very easily without resorting to mock objects.

5. Plumbing code : "Plumbing code" contained within the Struts framework. Mapping HTTP request parameters to Java objects is handled by Struts, for example. You don't have to do it. This allows you to focus more on the domain problem instead of building infrastructure.


 

Sunday, December 4, 2011

Struts 2

Struts 2 is a framework provided by apache for web development.

1. Struts 2 is based on the OpenSymphony Web Works Framework.
2. Struts 2 framework implements the Model-View-Controller (MVC) design 
     pattern.
3. In Struts 2 the model, view and controller are implemented by the action,
    result and FilterDispatcher respectively.