Hello World! – Struts Framework Tutorial

**adsense_4x1Block**
Introduction:


In this tutorial we will develop our Hello World java Web Application using Struts technology. The Apache Struts web framework is a free open-source solution for creating Java web applications using Model View Controller (MVC) design pattern.

Let’s get started with a very basic tutorial that will expose limited capabilities of Struts framework, but it will serve as a good starting point to explore Struts further by understanding the initial configurations required.

Tutorial’s Technology Stack:

Struts 2.2.3
Eclipse Helios (But you can do same steps with NetBeans as well)



Step 1: Creating Java Web Project in Eclipse IDE

This tutorial assumes you already know how to create new Java based Dynamic Web Project in Eclipse. If not, then you must first acquire some understanding using this basic JSP Tutorial

To continue we need a new Web Project, named ‘Tut-StrutsHelloWorld’ with index.jsp page added.



Step 2: Customizing JSP Page and Adding Navigation

Before diving into Struts let’s create a simple case of navigation to verify Struts working. Besides an index.jsp page in WebContent folder, add another jsp and name it ‘hello.jsp’

Refer this page from index.jsp, by pasting this line of code between body tags.

1
Index Page | <a href="hello">Struts</a>

Let’s add some custom text in ‘hello.jsp’ as well so that page is not rendered blank. Add following line of code in ‘hello.jsp’ between body tags:

1
<b>Hello World! Struts Application</b>

With this we are all set as far as our basic navigation is concerned.



Step 3: Adding Struts Capability to our project

Struts capability can be added in a project by simply adding its distributed jar files. Download latest Struts distribution from Apache Struts project site. This tutorial was written using Struts 2.2.3, so same or later can be downloaded.

Extract files from this distribution; some contained folders are described below:

apps: contain sample applications against tutorials on struts project website
docs: this folder contains, documentation for struts plugins, test pages, and whole Apache Struts project website, including tutorials, so that you can work on them offline as well.
lib: this folder contains struts jar files (containing struts implementation) and many other related jars, that you might need to use based on your project’s future needs. e.g. in case you plan to integrate it with Spring, then you’ll need related jar files.
src: since struts itself is an open source project maintained by Apache, that’s why its source code is included in the distribution itself.

Let’s now shop for our desired jar files from lib folder. Copy following jars from distribution lib folder, and paste them in:

Tut-StrutsHelloWorld\WebContent\WEB-INF\lib

  • struts2-core-2.2.3.jar
  • xwork-core-2.2.3.jar
  • commons-fileupload-1.2.2.jar
  • commons-io-2.0.1.jar
  • commons-lang-2.5.jar
  • freemarker-2.3.16.jar
  • javassist-3.11.0.GA.jar
  • ognl-3.0.1.jar

These are the minimal jars that you’ll need for Struts 2.2.3. Of course the version number may vary based on which distribution you have downloaded.

Are you wondering, there are so many jars in lib folder within Struts distribution, how on earth would I know which jars to pick up and which to leave? What I did was, at first added struts2-core-2.2.3.jar only, and Ran the application within Eclipse. There was an exception stating ‘class not found’ giving package name in which it looked for the class.

That package name helped me identify the jars required from lib folder, so I picked it and copied that jar to my project’s lib folder (Tut-StrutsHelloWorld/WebContent/WEB-INF/lib). I repeated this step unless there was no exception in Console. So it is up to you now, if you want you can go through this exploration step or you can simply pick the ones I have already listed.



Step 4: Telling Server we are using Struts

At this point if you will run your project on Server, nothing will happen. Since we just added some jars and they are sitting there doing nothing, unless we use some object from Struts implementation in these jars.

For enabling Struts 2 framework to work with our web application, we need to add a special Servlet, implemented by Struts called ‘StrutsPrepareAndExecuteFilter’, which is responsible for initializing Struts 2 for our project.

Since it is a Servlet, and from Hello World – Servlets Tutorial, we know that Servlets need to be loaded by Web Server (e.g. Tomcat) when application is deployed. And Web Server reads this information from entry point of our web project i.e. web.xml, the web application descriptor file.

So Add this code in web.xml between web-app tag.

1
2
3
4
5
6
7
8
9
<filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
 
<filter-mapping>
  <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

The Servlet that initializes Struts 2 is a special Servlet with filtering capabilities thus called Filter. A Filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters are actually an interface based on Servlets, thus they are basically Servlets.

Thus we added two nodes ‘filter’ and ‘filter-mapping’, rather than usual ‘servlet’ and ‘servlet-mapping’, since filter is a Servlet in effect, but just a little special.

Also note that, url-pattern node value is /* meaning the Struts 2 filter will be applied to all URLs for this web application. Thus it acts as a front filter and controls what should be done with each request to our web project’s internal resources. Hence acting as a Controller, making C part of MVC.



Step 5: Configuring our Struts 2 Implementation

The Filter Servlet we created above, needs a configuration file to know, what it should filter and how to behave with incoming requests (i.e. when new page is requested by the user). This configuration is actually what customizes Struts 2 for our web application.

So create a new file named ‘struts.xml’ , and place it in Tut-StrutsHelloWorld/src folder (struts.xml must be on the web application’s root class path)

Add these lines of code in src\struts.xml file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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>
      <!— Makes struts to output more error information in console in devMode  -->
	<constant name="struts.devMode" value="true" />
 
	<!— has nothing to do with java packages, simply used to group actions (below).
    	    name attribute can have any value. Extend it from struts-default -->
	<package name="hello" extends="struts-default">
 
		<!—  action for index.jsp page -->
		<action name="index">
			<result>/index.jsp</result>
		</action>
 
		<!-- action for hello.jsp -->
		<action name="hello">
			<result>/hello.jsp</result>
		</action>		
	</package>
</struts>

Note: Struts 2 can use either an XML configuration file or annotations (or both) to specify the relationship between a URL, a Java class, and a view page (such as index.jsp). For our basic Struts 2 application, we’ll use a minimal xml configuration.



Step 6: Understanding Basic Flow of Struts Application

Very important to understand what these lines of configurations will tell our StrutsPrepareAndExecuteFilter and what is happening in the background.

Within the Package named “hello” we have grouped two Actions. Actions are Fundamental component of Struts framework. From Apache’s website:

“An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request”

meaning, when our application launches, web server reads the web.xml. it finds welcome-file-list tag, and in that it tries all welcome-files including index.jsp, to launch default request to our application’s index page.

Remember? the Servlet filter we have configured in web.xml has a filter-mapping defined so that it will listen to every request (/* )coming to our application. So it will kick in, as soon as web server launches a request to find our index page. Now what Struts filter will do is, first of all it will remove all the unnecessary strings from the Request URL. e.g. in case of this URL:

http://localhost:8080/Tut-StrutsHelloWorld/index.jsp

Filter will remove the host and project name, and also the .jsp extension. Taking only ‘index’. That’s how Struts is implemented.

Now it will take that request (whatever is left of it) and scan through struts.xml, in top down sequence, and try to find an Action that has exact same name as this sub-string.

Yes it will find it since we have defined an Action with name attribute set as ‘index’. So now what.

Once matching Action configuration is found by the Filter, it will call the java Class associated with that Action. What? Which class, there is no class association in configuration. Yes, for hello world struts tutorial, I have kept it simply, and to the defaults. So when the class attribute in an action mapping is not defined, the com.opensymphony.xwork2.ActionSupport class is used as a default.

Had there been a class defined, filter would pass the execution to ‘execute’ method defined by our custom class. By default since ActionSupport class is used, so it’s execute method returns a string “success” by default.

what will we do with this string “success”? actually < result > tag within Action will do. By default result tag listens and responds to “success” message. So when it received the success message from ActionSupport by default, it redirected our browser to page named /index.jsp.

Now when index.jsp page is rendered, it has a link to “hello”. Clicking on will generate a request to webserver, which it will redirect to filter listening to all requests within our application. Filter will go through the above process once again, this time matching the Action named “hello” instead and showing the result “hello.jsp” page this time.



Step 7: Running our first Struts based Web Application

So now with this understanding, we are good to build and deploy our first Struts based web application on web server. Provided web server is configured with Eclipse IDE, right click on project name and select Run As > Run on Server. Built in browser will be launched with first showing the index.jsp page, and clicking on Struts link will navigate to “hello.jsp” after going through the background Struts Actions mapping mechanism.



Hello World Struts - rendered index page

Hello World Struts - rendered index page



Clicking on Struts link will navigate to hello.jsp.



Hello World Struts - rendered hello strutspage

Hello World Struts - rendered hello strutspage



Exercise

  • Rename the Action’s name attribute for hello, to something else. Where else do you need to change the action name?

    Hint: compare the code snippets above and see where that name matches.

  • Add a link on index page for a third page and call it mystruts.jsp. Add required configurations in struts.xml to make this new navigation work. (Hint: you need to add an Action)
  • Go through the Configuration Elements Documentation and read about different elements.