Versions Compared

Key

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

...

In the Hello World lesson, there were three components: the Action class, the result page, and the action mapping. In this lesson, we will add a fourth component: a an input form.

Create a HTML input form

...

Code Block
xml
xml
titlestruts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <include file="struts-default.xml" />
    <package name="actions" extends="struts-default">

        <action name="HelloName" class="tutorial.HelloName">
            <result name="success">/HelloName>HelloName-success.jsp</result>
            <result name="error">HelloName-error.html</result>
        </action>

    </package>
</struts>

...

Code Block
html
html
titleHelloName-success.jsp
<%@ taglib uriprefix="/tagss" prefixuri="s/struts-tags" %>
<html>
<head>
    <title>Success Page</title>
</head>
<body>
    <p>
      Hello, <s:property value="name" />!
    </p>
</body>
</html>

...

If you are coding along, go ahead and try your form now. Open the input page (http://localhost:8080/tutorial/helloNameHelloName.html), and click the submit button to see what happens. Try it with and without entering a name.

...

Code Block
java
java
titleHelloName2.java
package tutorial;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ParameterAware;
import java.util.Map;

public class HelloName2 extends ActionSupport implements ParameterAware {

    public static String NAME = "name";

    public String execute() {
        String[] name = (String[]) parameters.get("name"NAME);
        if (name == null || name[0] == null || name[0].length() == 0)
            return ERROR;
        else
            return SUCCESS;
    }

    Map parameters;

    public Map getParameters() {
        return parameters;
    }

    public void setParameters(Map parameters) {
        this.parameters = parameters;
    }
}

...

Go ahead and try it now. Load (http://localhost:8080/tutorial/HelloName2.html), enter "Zaphod" in the text field, and click the form submit button. You should see HelloName2-success.jsp saying "Hello, Zaphod!"

...