...
Examine the struts.xml configuration in the Hello World tutorial and you will find this:
Code Block |
---|
| htmlxmlhtml |
---|
| xml |
---|
title | struts.xml |
---|
borderStyle | solid |
---|
|
...
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
...
|
...
Add the following markup to index.jsp after the Hello Bruce Phillips link.
Code Block |
---|
| HTMLhtmlHTML |
---|
| html |
---|
title | Struts 2 Form |
---|
|
<p>Get your own personal hello by filling out and submitting this form.</p>
<s:form action="hello">
<s:textfield name="userName" label="Your name" />
<s:submit value="Submit" />
</s:form>
|
...
In the Hello World tutorial's example application on JSP HelloWorld.jsp was this code:
Code Block |
---|
| HTMLhtmlHTML |
---|
| html |
---|
title | Struts Property Tag |
---|
|
<s:property value="messageStore.message" />
|
...
One very useful feature of the Struts 2 property tag is that it will automatically convert the most common data types (int, double, boolean) to their String equivalents. To demonstrate this feature let's add a static int variable to class HelloWorldAction.
Code Block |
---|
| JAVAjavaJAVA |
---|
| java |
---|
title | Add Static Field |
---|
|
private static int helloCount = 0;
public int getHelloCount() {
return helloCount;
}
public void setHelloCount(int helloCount) {
HelloWorldAction.helloCount = helloCount;
}
|
Each time the execute method is called we'll increase helloCount by 1. So add this code to the execute method of class HelloWorldAction.
Code Block |
---|
| JAVAjavaJAVA |
---|
| java |
---|
title | Increase helloCount |
---|
|
helloCount++;
|
...
To include the value of the helloCount attribute in the HelloWorld.jsp we can use the Struts 2 property tag. Add the following to HelloWorld.jsp after the h2 tag.
Code Block |
---|
| HTMLhtmlHTML |
---|
| html |
---|
title | Use Property Tag To Display helloCount Value |
---|
|
<p>I've said hello <s:property value="helloCount" /> times!</p>
|
...
If the value returned by the get method is an object, then the property tag will cause Struts 2 to call the object's toString method. Of course, you should always override Class Object's toString method in your model classes. Add the following toString method to the MessageStore class:
Code Block |
---|
| JAVAjavaJAVA |
---|
| java |
---|
title | Add toString Method To Class MessageStore |
---|
|
public String toString() {
return message + " (from toString)";
}
|
Add the following to HelloWorld.jsp
Code Block |
---|
| HTMLhtmlHTML |
---|
| html |
---|
title | Using Property Tag to Call toString |
---|
|
<p><s:property value="messageStore" /></p>
|
...