Learn Java for Web Development

(Tina Meador) #1

180 CHAPTER 4: Building a Web Application Using Struts 2


6.
7.
8.<package name="basicstruts2" extends="struts-default"
9.namespace="/">
10.
11.
12./index.jsp
13.

14.
15.<action name="hello" class="com.apress.helloworld.action.HelloWorldAction"
16.method="execute">
17./hello.jsp
18.
19.
20.


   Line 15: This line declares the action mapping for
HelloWorldAction. HelloWorldAction is mapped to the action name hello.
 Line 16: This line declares that the execute() method of the action is to
be executed.
 Line 17: This line declares that hello.jsp is designated as a success page and
will be rendered as the response.

We need an Action class to act as the controller. The Action class responds to a user action
of submitting the form and sending the hello action to the container. Listing 4-21 illustrates
HelloWorldAction.


Listing 4-21. HelloWorldAction.java


1.package com.apress.helloworld.action;
2.
3.public class HelloWorldAction {
4.private String name;
5.
6.public String execute() throws Exception {
7.return "success";
8.}
9.
10.public String getName() {
11.return name;
12.}
13.
14.public void setName(String name) {
15.this.name = name;
16.}
17.}
18.


   Lines 6 to 7: The Struts 2 framework will create an object of the HelloWorldAction
class and call the execute method in response to a user’s action. And the execute
method returns the success string, which is mapped to hello.jsp in struts.xml.
Free download pdf