- Create a server page to present the messages
- Create an Action class to create the message
- 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.
How the Code Works
- 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.
- 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.
- 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.
- 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.
- A pure HMTL response is sent back to the browser.
Testing Actions
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())); } }