The previous article shows you how to configure a basic Struts 2 project in Maven.
Struts 2 – Setup a Struts 2 Web Application in Maven
Now, i continue the Struts 2 tutorial and build the first set of model, view and controller.
1. Create the MessageStore model
src/main/java/model/MessageStore.java
package model; public class MessageStore { private String message; public MessageStore() { setMessage("Hello Struts User"); } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } }
2. Create the HelloWorldAction controller
src/main/java/controller/HelloWorldAction.java
package controller; import model.MessageStore; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private static final long serialVersionUID = 1L; private MessageStore messageStore; public String execute() throws Exception { messageStore = new MessageStore(); return SUCCESS; } public MessageStore getMessageStore() { return this.messageStore; } public void setMessageStore(MessageStore messageStore) { this.messageStore = messageStore; } }
3. Create the HelloWorld view
src/main/webapp/views/HelloWorld.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Hello World!</title> </head> <body> <h2><s:property value="messageStore.message" /></h2> </body> </html>
4. Add a mapping in struts.xml for the hello action
src/main/resources/struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!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" /> <package name="basicstruts2" extends="struts-default"> <action name="index"> <result>/index.jsp</result> </action> <!-- Add a new mapping for hello action --> <action name="hello" class="controller.HelloWorldAction" method="execute"> <result name="success">/views/HelloWorld.jsp</result> </action> </package> </struts>
5. Add the URL link in index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!-- Add the Struts 2 tag --> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Basic Struts 2 Application - Welcome</title> </head> <body> <h1>Welcome To Struts 2!</h1> <!-- Add the URL Link to HelloWorld.jsp --> <p><a href="<s:url action='hello'/>">Hello World</a></p> </body> </html>
Done =)
Reference: Hello World Using Struts 2