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:
- <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <display-name>Example 2</display-name>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
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">
- <struts>
- <constant name="struts.devMode" value="true"> </constant>
- <package name="default" extends="struts-default">
- <action name="HelloWorld" class="networked.HelloWorld">
- <result name="SUCCESS">/HelloWorld.jsp</result>
- </action>
- </package>
- </struts>