ManagedCloud Servers

High performance handled and monitored by us 24/7/365. A complete solution to provide you with our in house expertise 24/7 tailored to your specific needs. We'll setup a bespoke server for your site using the latest tehnologies so you can get the most out of your hardware and get your website loading quickly and reliably. Find out more..

cPanelCloud Servers

Recommended - High performance cloud servers with no technical knowledge required. If you're hosting multiple websites already and you're looking to consolidate, or if you're looking to isolate yourself from the shared hosting environment but you don't have the time or knoweldge to manage a server, then the Managed cPanel Servers are for you. Find out more..

UnmanagedCloud Servers

Our unmanaged range gives you complete control at rock bottom prices and our cloud platform boasts super fast multipath 40Gb/s network, the latest Intel Xeon V3 CPUs and enterprise grade redundant SSDs. If you're a sysadmin look no further, we offer some of the best specification to price ratio servers available. Find out more..

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans

A Tutorial for Installing and Writing Struts Applications

Apache Struts was launched in May 2000 by Craig McClanahan, with version 1.0 officially released in July 2001. Struts2 is the next generation of Apache Struts. The goal of Struts2 is simple, to make web development easier for the developer. To achieve this goal Struts2 provides features to reduce XML configuration via intelligent defaults, utilizes annotations and provides conventions over configuration. Actions are now POJOs which increases testability and reduces coupling in the framework, and HTML form field data is converted to proper types for the action to use. Still further decreasing coupling is request processing has been made more modular by allowing a series of interceptors (custom or Struts2 provided) to provide pre-processing and post-processing functionality.

Modularity is a common theme a plug-in mechanism provides a way to augment the framework; key classes with the framework can be replaced with custom implementations to provide advanced features not provided out of the box; tags can utilize a variety of different rendering themes (including custom themes); and there are many different result types available for performing after-action execution tasks which include, but are not limited to, rendering JSPs, Velocity and Freemarker templates.

The Model View Controller Pattern

Struts 2 is a second-generation web application framework that implements the Model-View-Controller (MVC) design pattern. Unlike Struts 1, Struts 2 introduces several new architectural features that make the framework cleaner and more flexible. These new features include interceptors for layering cross-cutting concerns away from action logic; annotation-based configuration to reduce or eliminate XML configuration; a powerful expression language, Object-Graph Navigation Language (OGNL), that transverses the entire framework; and a mini-MVC based tag API that supports modifiable and reusable UI components. The MVC pattern is a way of taking an application and breaking it into three distinct parts:

  1. The mode
  2. The view,
  3. The controller.

In Struts 2 the model, view and controller are implemented by the action, result and FilterDispatcher respectively. The MVC pattern has three key components:

  • Model - Responsible for the business domain state knowledge(In Struts 2 the model is implemented by the Action component)
  • View - presentation component of the MVC Pattern(In Struts 2 the view is commonly implemented using JSP, Velocity Template, Freemaker or some other presentation-layer technology)
    • Controller - map the user request to appropriate action(In Struts 2 FilterDispatcher does the job of Controller)

Why Is Model-View-Controller So Important

Not only do patterns provide clean, proven designs, they also help the developers learning curve. Once you are familiar with the pattern, it is easy to apply its concepts to various projects.

The Model-View-Controller design pattern is a time-proven architecture for building software that manages interaction with users (using Views), implements business rules that are dependent on user input (using Controllers), and relies on data that exists in a remote database or system (accessed using Model components).

The advantage of using the MVC pattern is that there is no business or Model-specific processing within the presentation, or view, component itself. The opposite is also true; that is, there is no presentation logic in the model and business layers.

Installing Struts

There are two distribution methods for the Struts framework, source and binary.

The source distribution is for advanced users to suit the specific need (e.g. insert a modified class file into the build). We stick with the binary distribution. Download the latest binary release from here

The following steps need to be performed for a Struts application to work properly;

  • Copy all of the JAR files from the distribution's lib directory to the web application's WEB-INF/lib directory.
  • Create a web application deployment descriptor (web.xml) and copy it to the WEB-INF directory.
    • Create a struts.xml file and copy it to the WEB-INF/classes directory.

A Simple Struts Application

The goal of this section is to give you a general understanding of different parts of Struts framework and show how they work together to form a complete program. To accomplish that goal, we will develop a simple application that highlights each Struts component. Once you understand how this simple Struts application works, you will be able to easily understand other Struts programs because all share a common architecture.

Application Overview

The example that we will use is a common part of web applications, checking user login. It has three web pages, login.jsp, error and welcome.jsp. The login page prompt the user to input name and password. If the user input the correct password, they will see a welcome page saying: Welcome 'Name of the user'. If the wrong password is input it will take the user to the error.jsp page

Configuring Struts Applications

The goal of this section is to give you an overview of how to configure a struts application. Struts 2 configures applications in 2 ways:

  1. XML declarative architecture elements
        <action name="Login" class="manning.Login">
            <result>/AccountPage.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
        <action name="Registration" >
            <result>/Registration.jsp</result>
        </action>
            <action name="Register" class="manning.Register">
            <result>/RegistrationSuccess.jsp</result>
            <result name="input">/Registration.jsp</result>
        </action>
  1. Using annotations for declarative architecture
        @Results({
            @Result(name="input", value="/RegistrationSuccess.jsp" )
            @Result(value="/RegistrationSuccess.jsp" )
        })
        public class Login implements Action {
            public String execute() {
                //Business logic for login
            }
    } 

Note that the annotations are made on the Java classes that implement the actions.

XML declarative architecture elements

libs needed :
commons-fileupload-1.2.1.jar commons-io-1.3.2.jar commons-logging-1.1.jar freemarker-2.3.13.jar ognl-2.6.11.jar struts2-core-2.1.6.jar

xwork-2.1.2.jar

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="default" namespace="/" extends="struts-default">
                    <action name="Menu">
                    <result>/menu/Menu.jsp</result>
                </action>
            </package>
            <include file="Two.xml"/>
            <include file="Three.xml"/>
                . . .
            <include file="Eight.xml"/>
        </struts>

The struts element is the mandatory document root of all Struts 2 XML files and the package element is an important container element for organizing your actions, results, and other component elements.

        <package name="default" namespace="/" extends="struts-default">
            </package>

The mapping process is simple. The URL combines the servlet context with the package namespace and the action name. Note that the action name takes the .action extension.

                    <action name="Menu">
                    <result>/menu/Menu.jsp</result>
                    </action>

Use empty action components to forward to your results, even if they are simple JSPs that require no dynamic processing. This keeps the applications architecture consistent, prewires your workflow in anticipation of increases in complexity, and hides the real structure of your resources behind the logical namespace of the Struts 2 actions. While we could technically use a URL that hits the form JSP directly, a well-accepted best practice is to route these requests through actions regardless of their lack of actual processing. As you can see, such pass-through actions do not specify an implementation class. Include modularizes XML docs and are used to reduce congestion in the xml document in case of big applications.

            <include file="Two.xml"/>

JSP page

            <%@ 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>

Import struts tag-libs

        <%@ taglib prefix="s" uri="/struts-tags" %>

Struts 2 UI component tags

    <s:form action="HelloWorld">
    <s:textfield name="name" label="Your name"/>
    <s:submit/>
    </s:form>

Used to render html tags

Java class

    import com.opensymphony.xwork2.ActionSupport;
        public class Test extends ActionSupport{
            public String execute() throws Exception {
                //Methods and variables
            }
        }

ActionSupport provides default implementations of the Action interface and several other useful interfaces, giving us such things as data validation and localization of error messages. It provides default implementations of several important interfaces. If your actions extend this class, they automatically gain the use of these implementations.

    public class Test extends ActionSupport

The execute() method contains the business logic.

    public String execute()

Struts 2 actions don’t have to implement the Action interface. Any object can informally honor the contract with the framework by simply implementing an execute() method that returns a control string.The Action interface also provides some useful String constants that can be used as return values for selecting the appropriate result. The constants defined by the Action interface are:

        public static final String ERROR "error"
        public static final String INPUT "input"
        public static final String LOGIN "login"
        public static final String NONE "none"
        public static final String SUCCESS "success"

These constants can conveniently be used as the control string values returned by your execute() method.

web.xml

            <?xml version="1.0" encoding="UTF-8"?>
            <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
                xmlns:xsi="http://www.w3.org/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>JacksonLOGIN
            </display-name>
            <filter>
                <filter-name>struts2</filter-name>
                <filter-class>org.apache.struts2.dispatcher.FilterDispatcher
            </filter-class>
            <init-param>
                <param-name>actionPackages</param-name>
                <param-value>manning</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <servlet>
            <servlet-name>anotherServlet</servlet-name>
            <servlet-class>com.jackson.AnotherServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>anotherServlet</servlet-name>
            <url-pattern>/anotherServlet</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
        </web-app>

The most important elements in this deployment descriptor are the filter and filter-mapping elements that set up the Struts 2 Filter-Dispatcher. This filter will examine all the incoming requests looking for requests that target Struts 2 actions. Note the URL pattern to which this filter is mapped: "/*."

            <url-pattern>/*</url-pattern>

This means the filter will inspect all requests. The other important thing about the configuration of the Filter-Dispatcher is the initialization parameter that we pass in. The actionPackages parameter is necessary if you’re going to use annotations in your application. It tells the framework which packages to scan for annotations.

Struts Controller Components

CONTROLLER FILTERDISPATCHER

The controller's job is to map requests to actions. In a web application, the incoming HTTP requests can be thought of as commands that the user issues to the application. One of the fundamental tasks of a web application is routing these requests to the appropriate set of actions that should be taken within the application itself.

The role of the controller is played by the Struts 2 FilterDispatcher. This important object is a servlet filter that inspects each incoming request to determine which Struts 2 action should handle the request. The framework handles all of the controller work for you. You just need to inform the framework which request URLs map to which of your actions. You can do this with XML-based configuration files or Java annotations.

XML Based:
            <?xml version="1.0" encoding="UTF-8"?>
            <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
                xmlns:xsi="http://www.w3.org/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>JacksobLOGIN
            </display-name>
            <filter>
                <filter-name>struts2</filter-name>
                <filter-class>org.apache.struts2.dispatcher.FilterDispatcher
            </filter-class>
            <init-param>
                <param-name>actionPackages</param-name>
                <param-value>manning</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <servlet>
            <servlet-name>anotherServlet</servlet-name>
            <servlet-class>com.jjpeople.AnotherServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>anotherServlet</servlet-name>
            <url-pattern>/anotherServlet</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
        </web-app>
Java Annotation
            import org.apache.struts2.convention.annotation.Action;
            import org.apache.struts2.convention.annotation.Result;
            public class WelcomeUserAction {
                private String userName;
                private String message;
                @Action(value="/welcome",results={
                    @Result(name="success",location="sucessPage.jsp")
                    })
                public String execute() {
                    message = "Welcome " + userName + " !";
                    return "success";
            }
            public void setUserName(String userName) {
                this.userName = userName;
            }
            public void setMessage(String message) {
                this.message = message;
            }
            public String getUserName() {
                return userName;
            }
            public String getMessage() {
                return message;
            }
        }

FilterDispatcher handles four distinct responsibilities: * Executing actions * Cleaning up the ActionContext * Serving static content * Kicking off XWork's interceptor chain for the request lifecycle

            <filter>
                <filter-name>struts2</filter-name>
                <filter-class>org.apache.struts2.dispatcher.FilterDispatcher
            </filter-class>
            <init-param>
                <param-name>actionPackages</param-name>
                <param-value>manning</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

Struts Model Components

This section provides an overview of Struts Model Components

MODEL ACTION

The model is the internal state of the application. This state is composed of both the data model and the business logic. From the high-level black box view, the data and the business logic merge together into the monolithic state of the application. For instance, if you are logging in to an application, both business logic and data from the database will be involved in the authentication process.Most likely, the business logic will provide an authentication method that will take the username and password and verify them against some persisted data from the database. In this case, the data and the business logic combine to form one of two states, "authenticated" or "unauthenticated." Neither the data on its own, nor the business logic on its own, can produce these states. A Struts 2 action serves two roles. First, an action is an encapsulation of the calls to business logic into a single unit of work. Second, the action serves as a locus of data transfer. The controller, after receiving the request, must consult its mappings and determine which of these actions should handle the request.Once it finds the appropriate action, the controller hands over control of the request processing to the action by invoking it. This invocation process, conducted by the framework, will both prepare the necessary data and execute the action's business logic. When the action completes its work, it'll be time to render a view back to the user who submitted the request. Toward this end, an action, upon completing its work, will forward the result to the Struts 2 view component.

Struts View Components

Basically the View layer is the conduit for getting data in and out of the application. It does not contain business logic. Also does not contain any code for persisting data to or retrieving data from a data source. Rather, it is the Model layer that manages business logic and data access. The View layer simply concentrates on the interface. JSP is the typical View technology used for Java-based Web applications. Including the following major components: * JSP pages * Form Beans * JSP tag libraries * Resource bundles

JSP Pages

JSPs are the centerpiece of the Struts View layer. They contain the static HTML and JSP library tags that generate dynamic HTML.

Form Beans

Form Beans provide the conduit for transferring data between the View and Controller layers of Struts applications. Form Beans are simple data containers. They either contain data from an HTML form that is headed to the Model via the Controller or contain data from the Model headed to the View via the Controller. When HTML forms are submitted to a Struts application, Struts takes the incoming form data and uses it to populate the form's corresponding Form Bean. The Struts Controller layer then uses the Form Beans to access data that must be sent to the Model layer. On the other side, the Controller layer populates Form Beans with Model layer data so that it can be displayed with the View layer. The view is the presentation component of the MVC pattern. The result returns the page to the web browser. This page is the user interface that presents a representation of the application’s state to the user

Struts Tag Libraries

Struts 2 has combined its tags into one library. This simplifies figuring out which taglib directive to include in your web pages. Migrating your Struts 1 web pages to Struts 2 will require replacing the Struts 1 tag directives with the single <%@ taglib prefix="s" uri="/struts-tags"%>. The Struts 2 tag libraries are divided into four groups: Data tags, control-flow tags, UI component tags, and miscellaneous tags.

DATA TAGS

Data tags let you get data out of the ValueStack or place variables and objects onto the ValueStack. Data tags are classified into: 1. The property tag The current user is <s:property value="user.username"/> 2. The set tag <s:set name="username" value="user.username"/> Hello, <s:property value="#username"/>. How are you? 3. The push tag <s:push value="user"> This is the "<s:property value="portfolioName"/>" portfolio, created by none other than <s:property value="username"/> </s:push> 4. The bean tag <s:bean name="com.jjpeople.JokeBean" > <s:param name="jokeType">knockknock</s:param> <s:property value="startAJoke()"/> </s:bean> 5. The action tag <s:action name="TargetAction" executeResult="true"/>

CONTROL TAGS

Control-flow tags give you the tools to conditionally alter the flow of the rendering process; they can even test values on the ValueStack. Classified into: 1. The iterator tag <s:iterator value="users" status="itStatus"> <li> <s:property value="#itStatus.count" /> <s:property value="portfolioName"/> </li> </s:iterator> 2. The if and else tags <s:if test="user.age > 35">This user is too old.</s:if> <s:elseif test="user.age < 35">This user is too young</s:elseif> <s:else>This user is just right</s:else>

UI COMPONENT TAGS
        <%@ 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">
        <%@taglib uri="/struts-tags" prefix="s"%>
        <html>
                <head>
                    <meta http-equiv="Content-Type" content="text/html; 
                        charset=ISO-8859-1">
                    <title>Register Page</title>
                </head>
            <body>
                <s:form action="Register">
                    <s:textfield name="userName" label="User Name" />
                    <s:password name="password" label="Password" />
                    <s:radio name="gender" label="Gender" 
                            list="{'Male','Female'}" />
            <s:select name="country" list="countryList" 
                            listKey="countryId"                                                              listValue="countryName" 
                    headerKey="0" headerValue="Country" 
                    label="Select a country" />
                    <s:textarea name="about" label="About You" />
                    <s:checkboxlist list="communityList" 
                    name="community" label="Community" />
                    <s:checkbox name="mailingList"
                    label="Would you like to join our mailing list?" />
                    <s:submit />
                </s:form>
            </body>
        </html>

The UI component tags not only generate HTML form fields, but wrap those fields in layers of functionality that tap into all of the framework`s various features. 1. GENERATING THE HTML MARKUP Struts 2 textfield tag: html <s:textfield name="userName" label="User Name" /> As you can see, the only attributes that we set are name and label, but the output, shown in the following snippet, deduces a lot of information from these two attributes:

        <td class="tdLabel">
        <label for="Register_username" class="label">User Name:</label>
        </td>
        <td>
        <input type="text" name="username" value=""/>
        </td>
  1. BINDING FORM FIELDS TO VALUESTACK PROPERTIES
        <s:form action="UserLogin">
            <s:textfield name="username" label="Username" readonly="true"/>
            <s:password name="password" label="Password"/>
            <s:submit/>
        </s:form>

The name attribute is what binds each component to the properties exposed on the ValueStack, thus allowing data from the current stack to flow into the form fields during the page rendering prepopulation stage, and also allowing data from this form’s eventual submission to flow from that request onto the receiving action’s ValueStack properties. This is what we mean when we say that a UI component binds the form field to Java-side properties on the ValueStack.

Integrating with Type Conversion, Validation and Internationalization

For type conversion and validation, the UI components automatically handle error messages when there`s a problem. Struts UI Tags are of two types; Form Tags and Non - Form tags Form Tags are as follows: * autocompleter * checkbox html <s:checkbox name="mailingList" label="Would you like to join our mailing list?" /> * checkboxlist html <s:checkboxlist list="communityList" name="community" label="Community" /> * combobox * datetimepicker * doubleselect * head * file * form <s:form action="Register"> * hidden * label * optiontransferselect * optgroup * password <s:password name="password" label="Password" /> * radio <s:radio name="gender" label="Gender" list="{'Male','Female'}" /> * reset * select * submit * textarea <s:textarea name="about" label="About You" /> * textfield <s:textfield name="userName" label="User Name" /> * token * updownselect

Non-Form UI Tags are: * actionerror * actionmessage * component * div * fielderror * table * tabbedPanel * tree * treenode

MISCELLANEOUS TAGS

The miscellaneous tags are a set of tags that don’t quite fit into the other categories eg 1. The include tag <jsp:include> 2. The URL tag <s:url value="Login.action"/> 3. The i18n and text tags <s:i18n name="myResourceBundle"> In <s:text name="language"/>, <s:text name="girl" var="foreignWord"/> </s:i18n> 4. The param tag <bean:parameter id="param1" name="param1" />

Struts Validator

  1. ActionClass.java validation. Basic validation is done using the validate() method.
            public class Register extends ActionSupport{
                public String execute(){
                    //Make user and persist it.
                    return SUCCESS;
                }
                private String username;
                private String password;
            // Getters and setters omitted
            public void validate(){
                if ( getPassword().length() == 0 ){
                addFieldError( "password", getText("password.required"));
                }
                if ( getUsername().length() == 0 ){
                addFieldError( "username", getText("username.required"));
                }
                . . .
            }
        }
  1. Declaring your validation metadata with ActionClass-validations.xml
            <!DOCTYPE validators PUBLIC 
            "-//OpenSymphony Group//XWork Validator 1.0.2//
            EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
            <validators>
                <field name="password">
                <field-validator type="requiredstring">
                <message>You must enter a value for password.</message>
                </field-validator>
                </field>
                <field name="username">
                <field-validator type="stringlength">
                    <param name="maxLength">8</param>
                    <param name="minLength">5</param>
                    <message>While ${username} is a nice name, a valid username must be between ${minLength} and ${maxLength} characters long.
                    </message>
                </field-validator>
            </field>
            <validator type="expression">
                <param name="expression">username != password</param>
            <message>Username and password can't be the same.</message>
            </validator>
        </validators>

The naming convention of the XML validation metadata file is ActionClass-validations.xml. This file is then placed in the package directory structure next to the action class itself. The line <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2// EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> must be included in all of your validation xml files. Validators element <validators> .................... </validators> contains all of the declarations of individual validators that should be run when this action is invoked. There are two types of validators you can declare: 1. Field Field validators are validators that operate on an individual field <field name="password"> ................................... </field> Once we declare a field element for our data, we just need to put field-validator elements inside that field element to declare which validators should validate this piece of data.

  1. Non-field Apply to the whole action and often contain checks that involve more than one of the field values. <validator type="expression"> .......................... </validator> The message element is used to specify the message that the user should see in the event of a validation error <message>While ${username} is a nice name, a valid username must be between ${minLength} and ${maxLength} characters long. </message>

Struts JDBC Connection Pool

Struts 2 does not have a DataSource utility. The recommended method for getting a DataSource in any Java EE application is to set up a JNDI DataSource in the application server and use a JNDI lookup in your code to retrieve it.

Packaging a Struts Application

What Is Packaging

Packaging a Struts application involves gathering all the files and resources that are part of the application and bundling them together in a logical structure. Many different types of resources are usually included in a Struts application, and all of these need to be bundled with the application. Some of the more common types of resources that can be packaged with a Struts application are: * HTML and/or XML files * Images, audio, and video files * Stylesheets * JavaServer Pages * Properties files * Configuration files * Java classes * Third-party JARs

What Is Deployment

Deployment and packaging are closely related, but involve different tasks. While packaging determines where the resource files will reside in the package structure and how those resources will be bundled, deployment deals with how the bundled application will be installed and configured inside a target web container. The common approach for deploying is to deploy the web application in a web archive (WAR) file. Most web containers install a WAR file and make it available for users, often without even requiring a restart of the container. This approach is convenient because once the WAR file is properly built, the rest of the work is handled by the container.

Precompiling JavaServer Pages

You may not want to make the JSP source available in a deployment package. This is an issue of both security and licensing. You can precompile the JSP pages and not provide the JSP source code to customers. You'll have to distribute only the compiled bytecode, making it harder for the source code to be seen.

Packaging the Application as a WAR File

The first step is to create a root directory. In most cases, this directory will have the same name as your web application. After deciding how your JSP and HTML pages will be placed within your application, place them underneath the root directory in their appropriate subdirectories. Once all of the resources for the web application are accounted for and are inside the appropriate directories, you need to use Java's archiving tool jar to package the directories and files. From a command line use the jar utility like this (Suppose the jname is the root directory): jar cvf jname.war

Building Your Struts Applications with Ant

Although there are several different mechanisms to compile and deploy your Struts application, by far the most popular and most flexible is the Ant build tool. Ant is a platform-independent build tool that can be configured to compile your Java source code files, build your deployment JAR and WAR files, unit-test your code, and create your project's JavaDoc documentation. It also has many other uses and can be expanded to perform new tasks of your own creation. The Ant war task builds the web archive. The war target used to build the web archive is like this:

<target name="war" depends="compile">
  <echo>building war...</echo>
  <war warfile="${dist.dir}/lib/jjolt.war"
       webxml="${web.dir}/WEB-INF/web.xml">
    <fileset dir="${web.dir}"/>
    <classes dir="${build.dir}"/>
    <classes dir="${lib.dir}">
      <include name="*.properties"/>
    </classes>
    <lib dir="${lib.dir}">
      <include name="*.jar"/>
    </lib>
  </war>
</target>

Conclusion

This guide is sufficient enough to make a developer familiar with installing, writing, deploy, compile and build struts applications. This will make web development more easier for a web developer.

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans