Info |
---|
This tutorial assumes you've completed the Using Struts 2 Tags tutorial and have a working Using_Tags_Struts2_Ant (or Using_Tags_Struts2_Mvn) using_tags project. The example code for this tutorial, Coding_Actions_Struts2_Ant or Coding_Actions_Struts2_Mvn, is available on Google Code - http://code.google.com/p/struts2-examples/downloads/list. After downloading and unzipping the file, you'll have a folder named Coding_Actions_Struts2_Ant (or Coding_Actions_Struts2_Mvn). In that folder will be a README.txt file with instructions on now to build and run the example application.coding_action, is available for checkout from the Struts 2 GitHub repository: https://github.com/apache/struts-examples. |
Introduction
Coding a Struts 2 Action involves several parts:
...
In the previous tutorials we covered how to configure Struts to map a URL such as hello.action to a Action class such as HelloWorldAction (specifically the execute method).
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
|
...
In method execute is where we placed what we want this controller to do in response to the hello.action.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public String execute() throws Exception {
messageStore = new MessageStore() ;
helloCount++;
return SUCCESS;
}
|
...
In the Using Struts 2 Tags example application we added a Struts 2 form to index.jsp.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<s:form action="hello">
<s:textfield name="userName" label="Your name" />
<s:submit value="Submit" />
</s:form>
|
...
So for the HelloWorldAction class to automatically receive the userName value it must have a public method setUserName (note the JavaBean convention discussed in tutorial Hello World).
For the example application associated with this tutorial add the following Java code to class HelloWorldAction.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
|
To personalize the MessageStore message (recall that class MessageStore is storing the message to display) add the following Java code to the HelloWorldAction's execute method after the statement that instantiates the MessageStore object.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
if (userName != null) {
messageStore.setMessage( messageStore.getMessage() + " " + userName);
}
|
...