In my previous posts, I have written many examples and tutorials on JAX-RS RESTEasy, Spring 3, Hibernate and other java frameworks e.g. maven or junit 4. I also wrote on post related to Struts 2 hello world with xml configuration. In this post, I am updating previous example to use annotations to configure struts 2 application.
For information, struts annotations are part of struts convention plugin.
Sections in this post: Create maven web project Struts 2 dependencies web.xml changes Writing first action class Composing view files Testing the application Sourcecode download
Create maven web project
I will not eat much space here. You can read more details on how to create maven eclipse web project. In short, following commands are used.
mvn archetype:generate -DgroupId=com.howtodoinjava.struts2.example -DartifactIad=struts2example -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false cd struts2example mvn eclipse:eclipse -Dwtpversion=2.0
Struts 2 dependencies
I am using maven to import struts 2 runtime dependencies. It’s advantage is that you don’t need to remember and hunt for required dependencies manually and you get everything in one shot.
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.15.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.3.15.1</version> </dependency> </dependencies>
web.xml changes
Struts somehow needs to be plugged into your web application. It means that incoming requests to application should be handed over to struts for processing. This is done by adding a filter definition in web.xml file. This filter essentially redirect all incoming requests to StrutsPrepareAndExecuteFilter which then use configurations to handle that request.
Additionally, I am passing “actionPackages” init parameter so that this package can be scanned for required annotated classes.
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>com.howtodoinjava.struts2.example.web</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Writing first action class
This is important step because you will write the actual application logic here. Struts 2 actions usually extend ActionSupport class which provide some methods to override and change the application flow and inject your business logic in between.
@Namespace("/default") @ResultPath(value="/") @Results({ @Result(name="success", location="WEB-INF/jsp/success.jsp"), @Result(name="input", location="WEB-INF/jsp/index.jsp") }) public class TestAction extends ActionSupport { private static final long serialVersionUID = 1L; private String name; private Date nowDate; @Override public void validate(){ if (name==null || name.length()==0) addActionError(getText("error.enter.message")); } @Actions({ @Action("/"), @Action("/test") }) @Override public String execute() throws Exception { nowDate = new Date(); return ActionSupport.SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getNowDate() { return nowDate; } }
Note: Struts 2 actions looks like POJO classes because they have to act as action forms also which were separate entity in struts 1.
Composing view files
This is general step and involve writing view layer e.g. in our case we are writing jsp files. You can use the message resource to get messages from a property file which help in i18n later.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Struts 2 hello world example</title> <s:head/> </head> <body> <h1><s:text name="welcome" /></h1> <s:if test="hasActionErrors()"> <div id="fieldErrors"> <s:actionerror/> </div> </s:if> <s:form action="test" namespace="/" method="post" name="myForm" theme="xhtml"> <s:textfield name="name" size="40" maxlength="40" key="your.message-label"/> <s:submit key="submit" /> </s:form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Success Screen !!</title> </head> <body> <h2>Thank you for running this demo on <s:property value="nowDate" /></h2> <p> Your name recorded was: <h3><s:property value="name" /></h3> </p> </body> </html>
The message resource file, I am using is:
TestAction.properties
submit=Submit your.message-label=Your Name welcome=Welcome to Struts 2! error.enter.message=Please enter your name !!
Testing the application
We are good to run our hello world application now. Lets hit the browser.
Type http://localhost:8080/struts2example/ and hit Enter
Press Submit without entering anything
Enter your name and press Submit
File/Folder tree for project
That’s all friends for this struts 2 hello world application with annotations. If you want to download the source code of this tutorial, follow below given download link.
Happy Learning !!
Leave a Reply