Deprecated: Assigning the return value of new by reference is deprecated in /home/adiodomcom/domains/adiodom.com/public_html/WEB-INF/classes/apps/article/ArticleServlet.class.php on line 83

Deprecated: Function split() is deprecated in /home/adiodomcom/domains/adiodom.com/public_html/WEB-INF/lib/apps/AbstractApp.class.php on line 103
Struts 2 examples - AdioDom.com

Struts 2 examples

 

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. 

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.

Suppose you want to create a simple "Hello World" example that displays a welcome message use the blank web application in the distribution's apps directory is meant as a template. We can make a copy of the "blank.war", deploy it to our container, and use the exploded copy as the basis for our application. There is even a simple batch file in the source code directory that we can use to recompile the application in place.

When you submit a HTML form to the framework, the input is not sent to another server page, but to a Java class that you provide. These classes are called Actions. After the Action fires, a Result selects a resource to render the response. The resource is generally a server page, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window.

  1. Create a server page to present the messages
  2. Create an Action class to create the message
  3. Create a mapping to couple the action and page
    •  
    By creating these components, we are separating the workflow into three well-known concerns: the View, the Model, and the Controller. Separating concerns makes it easier to manage applications as they become more complex.

    Let's look at an example Action, server page, and mapping. If you like, fire up your IDE, and enter the code as we go.

The Code

First, we need a server page to present the message.

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

<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h2><s:property value="message" /></h2>

    </body>
</html>

Second, we need an Action class to create the message.

HelloWorld.java
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {

    public static final String MESSAGE = "Struts is up and running ...";

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

Third, we need a mapping to tie it all together.

Edit the struts.xml file to add the HelloWorld mapping.

struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="tutorial" extends="struts-default">

        <action name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
        <!-- Add your actions here -->

    </package>
</struts>

Go ahead and try it now! Deploy the application and open http://localhost:8080/tutorial/HelloWorld.action and see what happens! You should see a page with the title "Hello World!" and the message "Struts is up and running!".

  •  
Don't forget

Compile your Action to WEB-INF/classes and restart your container if necessary. If you are using maven, you can just run:

> mvn jetty:run

How the Code Works

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

  1. The container receives from the web server a request for the resource HelloWorld.action. According to the settings loaded from the web.xml, the container finds that all requests are being routed to org.apache.struts2.dispatcher.FilterDispatcher, including the *.action requests. The FilterDispatcher is the entry point into the framework.

  2. The framework looks for an action mapping named "HelloWorld", and it finds that this mapping corresponds to the class "HelloWorld". The framework instantiates the Action and calls the Action's execute method.
  3. The execute method sets the message and returns SUCCESS. The framework checks the action mapping to see what page to load if SUCCESS is returned. The framework tells the container to render as the response to the request, the resource HelloWorld.jsp.
  4. As the page HelloWorld.jsp is being processed, the <s:property value="message" /> tag calls the getter getMessage of the HelloWorld Action, and the tag merges into the response the value of the message.
  5. A pure HMTL response is sent back to the browser.

Testing Actions

Testing an Action is easy. Here's a test for our Hello World Action.

HelloWorldTest.java
package tutorial;
import junit.framework.TestCase;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;


public class HelloWorldTest extends TestCase {
  public void testHelloWorld() throws Exception {

    HelloWorld hello_world = new HelloWorld();
    String result = hello_world.execute();

    assertTrue("Expected a success result!",
      ActionSupport.SUCCESS.equals(result));

    assertTrue("Expected the default message!",
      HelloWorld.MESSAGE.equals(hello_world.getMessage()));

    }
}

What to Remember

The framework uses Actions to process HTML forms and other requests. The Action class returns a result-name such as SUCCESS, ERROR, or INPUT. Based on the mappings loaded from the struts.xml, a given result-name may select a page (as in this example), another action, or some other web resource (image, PDF).

When a server page is rendered, most often it will include dynamic data provided by the Action. To make it easy to display dynamic data, the framework provides a set of tags that can be used along with HTML markup to create a server page.

: :