A quick Hello World web app using Struts2 deployed on a Tomcat. The directory structure is that of a normal web app:
/Struts2-Example/
/index.jsp
/HelloWorld.jsp
/WEB-INF/
/web.xml
/classes/
/struts.xml
/networked/
/HelloWorld.class
/lib/
/commons-logging-1.1.jar
/freemarker-2.3.8.jar
/ognl-2.6.11.jar
/struts2-core-2.0.11.jar
/xwork-2.0.4.jar
Following three snippets provide the code for the three main components for the app.
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Name Collector</title></head>
<body>
<h4>Enter your name: </h4>
<s:form action="HelloWorld">
<s:textfield name="name" label="Your name"/>
<s:submit/>
</s:form>
</body>
</html>
The index.jsp file submits a name to the HelloWorld.java class:
package networked;
public class HelloWorld {
private static final String GREETING = "Hello ";
public String execute() {
setCustomGreeting(GREETING + getName());
return "SUCCESS";
}
private String name, customGreeting;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getCustomGreeting() {
return this.customGreeting;
}
public void setCustomGreeting(String customGreeting) {
this.customGreeting = customGreeting;
}
}
The HelloWorld.java class creates a custom message, which the following HelloWorld.jsp page picks up:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>HelloWorld</title></head>
<body>
<h3>Custom Greeting Page</h3>
<h4><s:property value="customGreeting"/></h4>
</body>
</html>
The deployment descriptor web.xml maps the FilterDispatcher to all the URLs:
Example 2
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
index.jsp
And, the struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
/HelloWorld.jsp