Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to Struts Framework

In this article we will talk about the Struts Framework in Java applications.

Introduction to Struts

The struts framework is an open source framework for creating well-structured web based applications. The struts framework is based on the Model View Controller (MVC) paradigm which distinctly separates all the three layers - Model (state of the application), View (presentation) and Controller (controlling the application flow). This makes struts different from conventional JSP applications where sometimes logic, flow and UI are mingled in a Java Server Page.

The struts framework is a complete web framework as it provides complete web form components, validators, error handling, internationalization, tiles and more. Struts framework provides its own Controller component. It integrates with other technologies for both Model and View components. Struts can integrate well with Java Server Pages (JSP), Java Server Faces (JSF), JSTL, Velocity templates and many other presentation technologies for View. For Model, Struts works great with data access technologies like JDBC, Hibernate, EJB and many more.

How Struts Works

When the framework’s controller receives a request, it uses the configuration file, struts-config.xml to find out the correct routing information. Based on the information configured in the configuration file, it internally invokes an Action class. The Action class interacts with the Model (also called the business layer) to access or update the underlying data in database/ file. The framework includes ActionForm classes to transfer data between Model and View.

Creating a Hello World Application using Struts:

For the purposes of this tutorial, we will be using the following tools and software.

  1. Eclipse Juno - download from this link for EE version
  2. Apache Tomcat version 6x or greater
  3. JDK version 6 or greater

Step 1:

Install all required tools and software.

Step 2:

Go to Java EE perspective in eclipse and create a new Dynamic Web Application.

Go to File >> New >> Dynamic Web Project

Creating Project

Figure 1: Creating Project

In the dialog that appears, enter the name of the Struts project you would like to create. The name here is “StrutsHelloWorld”.

Give the name StrutsHelloWorld to the project

Figure 2: Give the name StrutsHelloWorld to the project

Select the target runtime. If there are no target runtimes available already, then click “New Runtime…” button. The following dialog will appear.

Select Apache Tomcat

Figure 3: Select Apache Tomcat

Select a runtime available in the computer. In this tutorial, we select Apache Tomcat v7.0 and click the next button. The following dialog will appear.

Select Apache Tomcat v7.0

Figure 4: Select Apache Tomcat v7.0

Select the tomcat installation directory and JRE and click finish.

The Dynamic Web Project Dialog should now look like the following:

Click finish

Figure 5: Click finish

Click Finish.

The project will now appear on the “Project Explorer” window.

Project Explorer

Figure 6: Project Explorer

Step 3:

Add the required struts library files. These libraries are important to run the application, thus all the libraries should be included..

antlr.jar
apache-commons.jar
commons-chain-1.2.jar
commons-digester-2.1.jar
commons-logging-api-1.1.1.jar
commons-validator-1.1.3.jar
slf4j-api-1.7.2.jar
struts-1.2.9.jar
struts-taglib-1.3.5.jar

Step 4:

Next comes the most important part of in creating the application, writing the code.

As with any web application, a deployment descriptor is required for this struts application. Here is the sample web.xml for the StrutsHelloWorld project..

Web.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appid="struts-hello-world"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>Struts Hello World</display-name>
	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>/WEB-INF/struts-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

The above configuration has two main details specific to this struts application.

  1. The first one is the servlet and servlet mapping configuration. This will be the only servlet configuration for most Struts based applications. org.apache.struts.action.ActionServlet is the framework provided controller that acts as a bridge between the Model and View. The URL pattern in the servlet-mapping signifies that any URL request with a .do will be taken to the ActionServlet controller.
  2. The second most important details is the initialization parameter “config” that caries the location of the struts-config.xml file. The struts-config.xml file will carry all the configurations required for the ActionServlet to effectively route requests and responses back and forth from the model and view.

struts-config.xml

The struts-config.xml is like the blue print for the request response flow. Without this, the ActionServlet will not be able to route the requests and responses. The following is the configuration for our simple Hello World struts application.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

<form-beans>
	<form-bean name="helloWorldForm" type="com.src.strutshelloworld.form.HelloWorldForm"/>
</form-beans>

	<global-forwards>
<forward name="strutsHelloWorld" path="/helloWorld.do"/>
</global-forwards>

<action-mappings>
<action path="/helloWorld" type="com.src.strutshelloworld.action.HelloWorldAction" name="helloWorldForm">
	<forward name="success" path="/helloWorld.jsp" />
</action>
</action-mappings>

</struts-config>

The <form-beans> tag contains bean configurations. This application has HelloWorldForm class which can be configured here. The tag global-forwards contain routing configurations that can be called upon by any request and isn’t directly tied to a specific action. The index.jsp in our sample will call this global forward to direct us to the HelloWorld.jsp

<action-mappings> tags help map the request URL to an Action class. In the action tag, specify the URL and the corresponding Action class (HelloWorldAction) that will process the request. The action can be tied to a specific form-bean by configuring the form-bean name (helloWorldForm). An action can also have one or more forwards. In this example, the HelloWorldAction has one forward by the name “success”. Whenever the Action does a actionMapping.findForward() on the keyword success, the request will be forwarded to the path specified in the forward tag, in this case, /helloWorld.jsp.

There are many more elements to the struts-config.xml but the above configured tags form the basics.

Index.jsp

In the deployment descriptor the welcome file is configured as index.jsp. Here is the code that goes into the index.jsp.

<%@ tagliburi="http://struts.apache.org/tags-logic" prefix="logic"%>
<logic:redirectforward="strutsHelloWorld"/>

The above jsp code uses struts logic redirect tag. The redirect tag internally performs a HttpServletResponse.sendRedirect() call to the hyperlink specified. In this case we have specified sayhelloworld which is configured in the struts-config.xml as /sayhello.do. logic:redirect tag applies URL rewriting automatically, in order to maintain the session state when cookies are disabled at the client.

Note: The index.jsp file will not compile unless struts-taglib jar is configured in the project build path.

HelloWorldForm.java

This serves as the ActionForm bean for our Hello world application. An application may have any number ActionForm beans. An ActionForm bean is a simple POJO class that extends the class org.apache.struts.action.ActionForm. Following is the simple ActionForm created for the Hello World application.

packagecom.src.strutshelloworld.form;

importorg.apache.struts.action.ActionForm;

public class HelloWorldForm extends ActionForm {
	
	private static final long serialVersionUID = 5858534904862697411L;
	
	private String greetingMessage;

	public String getGreetingMessage() {

		returngreetingMessage;

	}

	public void setGreetingMessage(String greetingMessage) {

		this.greetingMessage = greetingMessage;

	}
}

The above code just has one property - “greetingMessage” and it’s corresponding getters and setters. The class extends org.apache.struts.action.ActionForm, thereby making it a Struts ActionForm class. This ActionForm class is configured in struts-config.xml (see above) as HelloWorldForm under the form-beans tag section.

HelloWorldAction.java

The HelloWorldAction.java acts as the Model for this application. Every struts Action class must inherit com.src.strutshelloworld.action.Action class found in the struts-xxx.jar. The Action class must implement the execute() method which would be invoked by the controller. Here is the Action class code for the Hello World application.

packagecom.src.strutshelloworld.action;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;

importcom.src.strutshelloworld.form.HelloWorldForm;
public class HelloWorldAction extends Action{
	publicActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HelloWorldFormhelloWorldForm = (HelloWorldForm)form;
		helloWorldForm.setGreetingMessage("Hello World!!! I am using Struts");
		returnmapping.findForward("success");
	}
}

In the above code, the execute() method sets the message to be displayed into the ActionForm instance helloWorldForm. The last line forwards the request with the keyword “success”. In the struts-config.xml, the forward “success” can be found under the action mapping for HelloWorldAction class and corresponds to the URL “/helloWorld.jsp” (refer the struts-config.xml section)

helloWorld.jsp

The last step is to display the greeting message on screen. The JSP helloWorld.jsp takes care of that.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<bean:write name="helloWorldForm" property="greetingMessage"/>
</body></html>

The greeting message is printed here using the <bean:write> tag. The tag requires the name of the struts ActionForm bean and the property that holds the display string, in this case the only property available in our HelloWorldForm - greetingMessage. The tag renders the value contained in the ActionForm property, thereby rendering the hello world message we set in our Action class (HelloWorldAction.java).

Step 5 - Run the application:

The application is all set to be executed. Right click on the project and click Run As >> Run on Server. This will allow you to choose the runtime server you have already configured. Click finish. Following is how the web page will look like:

Result

Figure 7: Result

This is all for today’s article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login