Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Create a class to store the welcome message (the model)
  2. Create a server page to present the message (the view)
  3. Create an Action class to control the interaction between the user, the model, and the view (the controller)
  4. Create a mapping (struts.xml) to couple the Action class and view
    Tip

    By creating these components, we are separating the work flow 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 model class, Action, server page, and mapping. If you like, fire up your Java IDE, and enter the code as we go.
    Info

    This tutorial assumes you've completed the How To Create A Struts 2 Web Application tutorial and have a working basic Struts project. The example code for this tutorial, hello_worldhelloworld, is available for checkout from the
    Struts 2 subversion sandbox at https://svn.apache.org/repos/asf/struts/sandbox/trunk. The example projects use Maven
    to manage the artifact dependencies and to build the .war files.

...

We need a mapping to tie the URL, the HelloWorldAction class (controller), and
the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user's action (the URL), which method of that class will be executed, and what view to render based on the String result that method returns.

Edit the struts.xml file (in the Ant project that file is in the src folder and in the Mvn project that file is in the src/main/resources folder) to add the action mapping. Place the action node (action name="hello") between the opening and closing package node, just after the action mapping with the name="index". Your complete struts.xml should look like:

...

Step 6 - Build the WAR File and Run The Application

If you're using the Ant version, execute ant archive to create the war file. If you're using the Mvn version execute Execute mvn clean package to create the war file.

Copy the war file to your Servlet container. After your Servlet container successfully deploys the war file go to this URL http://localhost:8080/Hello_World_Struts2_Ant/index.action (for the Ant project) or go to this URL http://localhost:8080/Hello_World_Struts2_Mvnhelloworld/index.action (for the Mvn project) where you should see the following:

...