Anda di halaman 1dari 36

Unit-iv

Struts Architecture
From a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-View
Controller pattern in Struts2 is implemented with the following five core components −

 Actions
 Interceptors
 Value Stack / OGNL
 Results / Result types
 View technologies

Struts 2 is slightly different from a traditional MVC framework, where the action takes the
role of the model rather than the controller, although there is some overlap.

The above diagram depicts the Model, View and Controller to the Struts2
high level architecture. The controller is implemented with a Struts2 dispatch
servlet filter as well as interceptors, this model is implemented with actions,
and the view is a combination of result types and results. The value stack and
OGNL provides common thread, linking and enabling integration between
the other components.
Apart from the above components, there will be a lot of information that
relates to configuration. Configuration for the web application, as well as
configuration for actions, interceptors, results, etc.

This is the architectural overview of the Struts 2 MVC pattern. We will go


through each component in more detail in the subsequent chapters.

Request Life Cycle


Based on the above diagram, you can understand the work flow through
user's request life cycle in Struts 2 as follows −

 User sends a request to the server for requesting for some resource (i.e.
pages).
 The Filter Dispatcher looks at the request and then determines the
appropriate Action.
 Configured interceptor functionalities applies such as validation, file
upload etc.
 Selected action is performed based on the requested operation.
 Again, configured interceptors are applied to do any post-processing if
required.
 Finally, the result is prepared by the view and returns the result to the
user.
 Struts Action Class
 What is Action Class?
 An Action class in the struts application extends Struts
'org.apache.struts.action.Action" Class. Action class acts as wrapper around
 the business logic and provides an inteface to the application's Model layer. It acts
as glue between the View and Model layer. It also
 transfers the data from the view layer to the specific business process layer and
finally returns the procssed data from business layer
 to the view layer.
 An Action works as an adapter between the contents of an incoming HTTP request
and the business logic that corresponds to it.
 Then the struts controller (ActionServlet) slects an appropriate Action and creates
an instance if necessary, and finally calls execute
 method.
 To use the Action, we need to Subclass and overwrite the execute() method. In the
Action Class don't add the business process logic,
 instead move the database and business process logic to the process or dao layer.
 The ActionServlet (commad) passes the parameterized class to Action Form using
the execute() method. The return type of the
 execute method is ActionForward which is used by the Struts Framework to
forward the request to the file as per the value of the
 returned ActionForward object.
 Developing our Action Class?
 Our Action class (TestAction.java) is simple class that only forwards the
TestAction.jsp. Our Action class returns the ActionForward
 called "testAction", which is defined in the struts-config.xml file (action mapping is
show later in this page). Here is code of our
 Action Class:
 TestAction.java
 package technicalstack.net;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.struts.action.Action;
 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.action.ActionMapping;
 public class TestAction extends Action
 {
 public ActionForward execute(
 ActionMapping mapping,
 ActionForm form,
 HttpServletRequest request,
 HttpServletResponse response) throws Exception{
 return mapping.findForward("testAction");
 }
 }
 Understanding Action Class
 Here is the signature of the Action Class.
 public ActionForward execute(ActionMapping mapping,
 ActionForm form,
 javax.servlet.http.HttpServletRequest request,
 javax.servlet.http.HttpServletResponse response)
 throws java.lang.Exception
 Action Class process the specified HTTP request, and create the corresponding
HTTP response (or forward to another web
 component that will create it), with provision for handling exceptions thrown by the
business logic. Return an ActionForward
 Output as PDF file has been powered by [
 Universal Post Manager
 ] plugin from www.ProfProjects.com
 | Page 1/2 |
 This page was exported from -
 TechnicalStack
 Export date: Tue Feb 27 4:19:56 2018 / +0000 GMT
 instance describing where and how control should be forwarded, or null if the
response has already been completed.
 Parameters:
 mapping - The ActionMapping used to select this instance
 form - The optional ActionForm bean for this request (if any)
 request - The HTTP request we are processing
 response - The HTTP response we are creating
 Throws:
 Action class throws java.lang.Exception - if the application business logic throws an
exception
 Adding the Action Mapping in the struts-config.xml
 To test the application we will add a link in the index.jsp
 <html:link page="/TestAction.do">Test the Action</html:link>
 Following code under the <action-mappings> tag is used to for mapping the
TestAction class.
 <action
 path="/TestAction"
 type="technicalstack.net.TestAction">
 <forward name="testAction" path="/pages/TestAction.jsp"/>
 </action>
 To test the new application click on Test the Action link on the index page. The
content of TestAction.jsp should be displayed on the
 user browser.
 In this lesson you learned how to create Action Class and add the mappings in the
struts-config.xml. Our Action Class returns the
 ActionForward mapping of the TestAction.jsp.
 Welcome.jsp
 <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
 <%@ taglib uri="/tags/struts-html" prefix="html" %>
 <html:html locale="true">
 <head>
 <title><bean:message key="welcome.title"/></title>
 <html:base/>
 </head>
 <body bgcolor="white">
 <h3><bean:message key="welcome.heading"/></h3>
 <p><bean:message key="welcome.message"/></p>
 </body>
 </html:html>
 Forwarding the Welcome.do request to Welcome.jsp
 The "Action Mapping Definitions" is the most important part in the struts-
config.xml. This section takes a form defined in the "Form
 Bean Definitions" section and maps it to an action class.
 Following code under the <action-mappings> tag is used to forward the request to
the Welcome.jsp.
 <action path="/Welcome"
 forward="/pages/Welcome.jsp"/>
 To call this Welcome.jsp file we will use the following code.
 <html:link page="/Welcome.do">First Request to the controller</html:link>
 Once the use clicks on on First Request to the controller link on the index page,
request (for Welcome.do) is sent to the Controller
 and the controller forwards the request to Welcome.jsp. The content of Welcome.jsp
is displayed to the user.

Struts - Actions

Actions are the core of the Struts2 framework, as they are for any MVC
(Model View Controller) framework. Each URL is mapped to a specific
action, which provides the processing logic which is necessary to service the
request from the user.

But the action also serves in two other important capacities. Firstly, the action
plays an important role in the transfer of data from the request through to the
view, whether its a JSP or other type of result. Secondly, the action must assist
the framework in determining which result should render the view that will
be returned in the response to the request.

Create Action

The only requirement for actions in Struts2 is that there must be one
noargument method that returns either a String or Result object and must be
a POJO. If the no-argument method is not specified, the default behavior is to
use the execute() method.

Optionally you can extend the ActionSupport class which implements six
interfaces including Action interface. The Action interface is as follows −

public interface Action {


public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public String execute() throws Exception;
}

Let us take a look at the action method in the Hello World example −

package com.tutorialspoint.struts2;

public class HelloWorldAction {


private String name;

public String execute() throws Exception {


return "success";
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

To illustrate the point that the action method controls the view, let us make
the following change to the execute method and extend the class
ActionSupport as follows −

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {


private String name;

public String execute() throws Exception {


if ("SECRET".equals(name)) {
return SUCCESS;
} else {
return ERROR;
}
}
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}
}

In this example, we have some logic in the execute method to look at the name
attribute. If the attribute equals to the string "SECRET", we return
SUCCESS as the result otherwise we return ERROR as the result. Because we
have extended ActionSupport, so we can use String constants SUCCESS and
ERROR. Now, let us modify our struts.xml file as follows −

<?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 = "helloworld" extends = "struts-
default">
<action name = "hello"
class =
"com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name =
"success">/HelloWorld.jsp</result>
<result name =
"error">/AccessDenied.jsp</result>
</action>
</package>
</struts>

ServletActionContext class

1. ServletActionContext class
2. Methods of ServletActionContext class

The ServletActionContext class provides methods to get HttpServletRequest,


HttpServletResponse, ServletContext and HttpSession objects.

It is a convenient class and prefered than ActionContext class.

Methods of ServletActionContext class

The commonly used methods provided by ServletActionContext class are as follows:

1. public static HttpServletRequest getRequest() returns the instance of HttpServletRequest.


2. public static HttpServletResponse getResponse() returns the instance of HttpServletResponse.
3. public static ServletContext getServletContext() returns the instance of ServletContext.

How to obtain instance of HttpSession ?

If we have the instance of HttpServletRequest class, we can call the getSession() method of
HttpServletRequest interface to get the instance of HttpSession. For example:

1. HttpServletRequest request=ServletActionContext.getRequest();
2. HttpSession session=request.getSession();

OR

1. HttpSession session=ServletActionContext.getRequest().getSession();

ActionForm Class

In this lesson you will learn about the ActionForm in detail. I will show you a good example
of ActionForm. This example will help you understand Struts in detail. We will create user
interface to accept the address details and then validate the details on server side. On the
successful validation of data, the data will be sent to model (the action class). In the Action
class we can add the business processing logic but in this case we are just forwarding it to
the sucess.jsp.

What is ActionForm?
An ActionForm is a JavaBean that extends
org.apache.struts.action.ActionForm. ActionForm maintains the session state
for web application and the ActionForm object is automatically populated on the server
side with data entered from a form on the client side.
We will first create the class AddressForm which extends the ActionForm class. Here is the
code of the class:

AddressForm.java

package roseindia.net;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

/**
* Form bean for the Address Entry Screen.
*ss
*/
public class AddressForm extends ActionForm
{
private String name=null;
private String address=null;
private String emailAddress=null;

public void setName(String name){


this.name=name;
}

public String getName(){


return this.name;
}

public void setAddress(String address){


this.address=address;
}

public String getAddress(){


return this.address;
}

public void setEmailAddress(String emailAddress){


this.emailAddress=emailAddress;
}

public String getEmailAddress(){


return this.emailAddress;
}

/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name=null;
this.address=null;
this.emailAddress=null;
}

/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
* @return errors
*/
public ActionErrors validate(
ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();

if( getName() == null || getName().length() < 1 ) {


errors.add("name",new ActionMessage("error.name.required"));
}
if( getAddress() == null || getAddress().length() < 1 ) {
errors.add("address",new ActionMessage("error.address.required"));
}
if( getEmailAddress() == null || getEmailAddress().length() < 1 ) {
errors.add("emailaddress",new ActionMessage("error.emailaddress.required"));
}

return errors;
}

}
The above class populates the Address Form data and validates it. The validate() method is
used to validate the inputs. If any or all of the fields on the form are blank, error messages
are added to the ActionMapping object. Note that we are using ActionMessage class,
ActionError is now deprecated and will be removed in next version.

Now we will create the Action class which is the model part of the application. Our action
class simply forwards the request the Success.jsp. Here is the code of the AddressAction
class:

AddressAction.java

package roseindia.net;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AddressAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("success");
}
}

Now we have to create an entry for form bean in the struts-config.xml. Add the following
lines in the struts-config.xml file:

<form-bean
name="AddressForm"
type="roseindia.net.AddressForm"/>

Add the following line in the struts-config.xml file for handling the action "/Address.do":

<action
path="/Address"
type="roseindia.net.AddressAction"
name="AddressForm"
scope="request"
validate="true"
input="/pages/Address.jsp">
<forward name="success" path="/pages/success.jsp"/>
</action>

Now create Address.jsp, which is our form for entering the address details. Code for
Address.jsp is as follows:

Address.jsp

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


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

<html:html locale="true">

<head>

<title><bean:message key="welcome.title"/></title>

<html:base/>

</head>

<body bgcolor="white">

<html:form action="/Address">

<html:errors/>

<table>

<tr>

<td align="center" colspan="2">


<font size="4">Please Enter the Following
Details</font>
</tr>
<tr>
<td align="right">
Name
</td>
<td align="left">
<html:text property="name" size="30"
maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
Address
</td>
<td align="left">
<html:text property="address" size="30"
maxlength="30"/>
</td>
</tr>

<tr>
<td align="right">
E-mail address
</td>
<td align="left">
<html:text property="emailAddress" size="30"
maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
<html:submit>Save</html:submit>
</td>
<td align="left">
<html:cancel>Cancel</html:cancel>
</td>
</tr>
</table>
</html:form>
</body>
</html:html>

User enter the values in the form and click on the submit form. Form validation is done on
the server side and error message is displays on the jsp page. To display the error on the
jsp page <html:errors/> tag is used. The <html:errors/> tag displays all the errors in one
go. To create text box <html:text .../> is used in jsp page.

e.g.

<html:text property="address" size="30" maxlength="30"/>

Above tag creates text box for entering the address. The address is retrieved from and later
stored in the property named address in the form-bean. The tag
<html:submit>Save</html:submit> creates the submit button and the tag
<html:cancel>Cancel</html:cancel> is used to create the Cancel button.

Add the following line in the index.jsp to create a link for testing the Address.jsp form:
<html:link page="/pages/Address.jsp">Test the Address Form</html:link>

Build the application and click on the Test the Address Form link on the index page to test
the newly created screen. You should see the following screen.

Action Form

In this example we will see how to create a login application using ActionForm. The
following files are required for the login application.

 login.jsp
 success.jsp
 failure.jsp
 web.xml
 struts-config.xml
 LoginAction.java
 LoginForm.java
 ApplicationResource.properties

web.xml

The first page that will be called in the login application is the login.jsp page. This
configuration should be done in web.xml as shown below.

<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

login.jsp

We use Struts HTML Tags to create login page. The form has one text field to get the user
name and one password field to get the password. The form also has one submit button,
which when clicked calls the login action. <html:errors /> tag is used to display the error
messages to the user.
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginForm"
property="userName" />
Password :<html:password name="LoginForm"
property="password" />
<html:submit value="Login" />
</html:form>
</body>
</html>

The user enters the user name and password and clicks the login button. The login action is
invoked.

Action servlet:
Servlet is Java technology for writing the server side applications. It is the core
technology used for developing any Java server applications. Any other Java
frameworks created are internally using the servlet for hiding the complex part
of how servlet handles the web application request and renders the response.
However, knowing the internals of servlet technology is more important to
understand the Java web frameworks. This post updated with comprehensive
list of servet tutorials for the beginners and advanced developers.

Understanding Struts Action Class


extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around
the business logic and provides an inteface to the application's Model layer. It acts as glue
between the View and Model layer. It also transfers the data from the view layer to the
specific business process layer and finally returns the procssed data from business layer to
the view layer.

An Action works as an adapter between the contents of an incoming HTTP request and the
business logic that corresponds to it. Then the struts controller (ActionServlet) slects an
appropriate Action and creates an instance if necessary, and finally calls execute method.
To use the Action, we need to Subclass and overwrite the execute() method. In the Action
Class don't add the business process logic, instead move the database and business process
logic to the process or dao layer.

The ActionServlet (commad) passes the parameterized class to Action Form using the
execute() method. The return type of the execute method is ActionForward which is used by
the Struts Framework to forward the request to the file as per the value of the returned
ActionForward object.

Developing our Action Class?

Our Action class (TestAction.java) is simple class that only forwards the TestAction.jsp.
Our Action class returns the ActionForward called "testAction", which is defined in the
struts-config.xml file (action mapping is show later in this page). Here is code of our Action
Class:

TestAction.java

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

Understanding Action Class


Here is the signature of the Action Class.

public ActionForward execute(ActionMapping mapping,


ActionForm form,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)
throws java.lang.Exception

Action Class process the specified HTTP request, and create the corresponding HTTP
response (or forward to another web component that will create it), with provision for
handling exceptions thrown by the business logic. Return an ActionForward instance
describing where and how control should be forwarded, or null if the response has already
been completed.

Parameters:

mapping - The ActionMapping used to select this instance


form - The optional ActionForm bean for this request (if any)
request - The HTTP request we are processing
response - The HTTP response we are creating
Throws:
Action class throws java.lang.Exception - if the application business
logic throws an exception

Adding the Action Mapping in the struts-config.xml


To test the application we will add a link in the index.jsp
<html:link page="/TestAction.do">Test the Action</html:link>

Following code under the <action-mappings> tag is used to for mapping the TestAction
class.

<action
path="/TestAction"
type="roseindia.net.TestAction">
<forward name="testAction"
path="/pages/TestAction.jsp"/>
</action>

To test the new application click on Test the Action link on the index page. The content of
TestAction.jsp should be displayed on the user browser.
ActionForward
java.lang.Object
|
+--org.apache.struts.config.ForwardConfig
|
+--org.apache.struts.action.ActionForward
All Implemented Interfaces:

java.io.Serializable

Direct Known Subclasses:

ForwardingActionForward, RedirectingActionForward

public class ActionForward

extends ForwardConfig

An ActionForward represents a destination to which the controller servlet,


ActionServlet, might be directed to perform a RequestDispatcher.forward()
or HttpServletResponse.sendRedirect() to, as a result of processing activities of
an Action class. Instances of this class may be created dynamically as necessary, or
configured in association with an ActionMapping instance for named lookup of
potentially multiple destinations for a particular mapping instance.

An ActionForward has the following minimal set of properties. Additional properties


can be provided as needed by subclassses.

 contextRelative - Should the path value be interpreted as context-relative (instead


of module-relative, if it starts with a '/' character? [false]
 name - Logical name by which this instance may be looked up in relationship to a
particular ActionMapping.
 path - Module-relative or context-relative URI to which control should be forwarded,
or an absolute or relative URI to which control should be redirected.
 redirect - Set to true if the controller servlet should call
HttpServletResponse.sendRedirect() on the associated path; otherwise
false. [false]

Since Struts 1.1 this class extends ForwardConfig and inherits the contextRelative
property.

NOTE - This class would have been deprecated and replaced by


org.apache.struts.config.ForwardConfig except for the fact that it is part of
the public API that existing applications are using.

Version:

$Revision: 1.1 $ $Date$

Author:

Craig R. McClanahan

See Also:

Serialized Form

Field Summary

Fields inherited from class org.apache.struts.config.ForwardConfig


configured, contextRelative, name, path, redirect

Constructor Summary

ActionForward()
Construct a new instance with default values.

ActionForward(java.lang.String path)
Construct a new instance with the specified path.

ActionForward(java.lang.String path, boolean redirect)


Construct a new instance with the specified path and redirect flag.

ActionForward(java.lang.String name, java.lang.String path,


boolean redirect)
Construct a new instance with the specified path and redirect flag.

ActionForward(java.lang.String name, java.lang.String path,


boolean redirect, boolean contextRelative)
Construct a new instance with the specified values.

Methods inherited from class org.apache.struts.config.ForwardConfig

freeze, getContextRelative, getName, getPath, getRedirect,


setContextRelative, setName, setPath, setRedirect, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll,


wait, wait, wait
Constructor Detail

ActionForward
public ActionForward()
Construct a new instance with default values.

ActionForward
public ActionForward(java.lang.String path)
Construct a new instance with the specified path.

Parameters:

path - Path for this instance

ActionForward
public ActionForward(java.lang.String path,
boolean redirect)
Construct a new instance with the specified path and redirect flag.

Parameters:

path - Path for this instance

redirect - Redirect flag for this instance

ActionForward
public ActionForward(java.lang.String name,
java.lang.String path,
boolean redirect)
Construct a new instance with the specified path and redirect flag.

Parameters:

name - Name of this instance

path - Path for this instance

redirect - Redirect flag for this instance


ActionForward
public ActionForward(java.lang.String name,
java.lang.String path,
boolean redirect,
boolean contextRelative)
Construct a new instance with the specified values.

Parameters:

name - Name of this instance

path - Path for this instance

redirect - Redirect flag for this instance

contextRelative - Context relative flag for this instance

config xml
This chapter will take you through basic configuration required for a Struts 2 application.
Here we will see what will be configured in few important configuration files : web.xml,
struts.xml, struts-config.xml and struts.propertiesThe struts application contains two main
configuration files struts.xml file and struts.properties file.
The struts.properties file is used to override the default values of default.xml file provided
by struts framework. So it is not mandatory. Mostly, you will not use struts.properties file.

The web.xml file:


The web.xml configuration file is a J2EE configuration file that determines how elements of
the HTTP request are processed by the servlet container. It is not strictly a Struts2
configuration file, but it is a file that needs to be configured for Struts2 to work.

As discussed earlier, this file provides an entry point for any web application. The entry
point of Struts2 application will be a filter defined in deployment descriptor (web.xml).
Hence we will define an entry of FilterDispatcher class in web.xml. The web.xml file needs
to be created under the folder WebRoot/WEB-INF.

This is the first configuration file you will need to configure if you are starting without the
aid of a template or tool that generates it (such as Eclipse or Maven2). Following is the
content of web.xml file which we used in our last example.

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts2MyFirstApp</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>

The struts.xml file:


Here, we are going to learn all about struts.xml file. First of all let us see the simple example
of struts.xml file. Let us have a look at the struts.xml file we created in the Hello World
example explained in previous chapter.

The struts.xml file contains the configuration information that you will be modifying as
actions are developed. This file can be used to override default settings for an application,
for example struts.devMode = false and other settings which are defined in property file.
This file can be created under the folder WEB-INF/classes.

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.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="myapp" />

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


<action name="login" class="com.dineshonjava.struts2.login.LoginAction">
<result name="success">Welcome.jsp</result>
<result name="error">Login.jsp</result>
</action>
</package>
</struts>

The first thing to note is the DOCTYPE. All struts configuration file need to have the
correct doctype as shown in our little example. <struts> is the root tag element, under
which we declare different packages using <package> tags.

Multi Configuration File-


Here <package> allows separation and modularization of the configuration. This is very
useful when you have a large project and project is divided into different modules.

<?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>
<include file="my-struts1.xml"/>
<include file="my-struts2.xml"/>
</struts>

Struts 2 Multiple Namespace Example-


We can define multiple namespaces in struts.xml file by the namespace attribute of
package element. As we know, default namespace is / (root).

Let’s see the simple example to define multiple namespaces in struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?>


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

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


<action name="hello" class="com.dineshonjava.struts2.login.LoginAction">
<result>welcome.jsp</result>
</action>
</package>

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


<action name="hello" class="com.dineshonjava.struts2.login.LoginAction">
<result>welcome.jsp</result>
</action>
</package>

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


<action name="hello" class="com.dineshonjava.struts2.login.LoginAction">
<result>welcome.jsp</result>
</action>
</package>

</struts>

1) package element-

We can easily divide our struts application into sub modules. The package element specifies
a module. You can have or or more packages in the struts.xml file. Say, if your project has
three domains – business_applicaiton, customer_application and staff_application, you
could create three packages and store associated actions in the appropriate package.

Attributes of package elements:

 name name is must for defining any package.


 namespace It is an optional attribute of package. If namespace is not present, / is
assumed as the default namespace. In such case, to invoke the action class, you need
this URI:
 /actionName.action

If you specify any namespace, you need this URI:

/namespacename/actionName.action

 extends The package element mostly extends the struts-default package where
interceptors and result types are defined. If you extend struts-default, all the actions
of this package can use the interceptors and result-types defined in the struts-
default.xml file.

2) action element:

The action is the sub-element of package and represents an action.


Attributes of action element-

 name name is must for defining any action.


 class class is the optional attribute of action. If you omit the class attribute,
ActionSupport will be considered as the default action. A simple action may be as:
 <action name="login">
 method It is an optional attribute. If you don’t specify method attribute, execute
method will be considered as the method of action class. So this code:
 <action name="login" class="com.dineshonjava.struts2.login.LoginAction">

will be same as:

<action name="login" class="com.dineshonjava.struts2.login.LoginAction"


method="execute">

If you want to invoke a particular method of the action, you need to use method
attribute.

It is the sub element of action that specifies where to forward the request for this action.
Attributes of result element-

 name is the optional attribute. If you omit the name attribute, success is assumed as
the default result name.
 type is the optional attribute. If you omit the type attribute, dispatcher is assumed as
the default result type

Understanding Action Mappings


Action mapping is a streamlined process to design training in the business
world. Its goal is to help designers:

 Commit to measurably improving the performance of the business


 Identify the best solution to the performance problem
 When training is necessary, create challenging simulations, not
information presentations

I created the process in May 2008, when I was designing custom elearning for
corporate clients (here’s the first blog post about it).

The following slideshow gives a simplified, very high-level overview. It uses


lighthearted stock photos from 2008 of a guy dressed in a ninja outfit. No
political statement is intended.

Because I was designing elearning at the time, I presented action mapping as


an elearning design model, but it works for all types of business training, as I
show in my workshops.

The addition of a flowchart


In May 2013, I deepened step 2 to include the use of a flowchart that helps identify lean, in-
the-workflow solutions, such as job aids or process improvements. Training is rarely the
best or only solution to a problem.

Some advantages of action mapping

Action mapping is being used by businesses and governmental organizations around the
world. Happy action mappers have told me that the main advantages are:

 The stakeholders “get it” right away — it’s an intuitive process and the benefits are
easy to see.
 Subject matter experts who are included in the process are less likely to add extraneous
information.
 The resulting training is likely to be rich with scenarios, which learners often prefer
over information presentations.

Possible benefits to the field of training design

One of my goals in creating the model was to address some weakness I saw in our
profession, including:

 We’re not held accountable for what we do because almost nothing we do is measured.
As a result, our work isn’t seen as vital to the organization. By putting a measurable
business goal — a high-level evaluation — first and making it the center of everything
we do, we publicly commit to improving our organization’s performance and
demonstrate our value.
 Almost everyone has been taught through a lifetime of traditional schooling that
“teaching” means “presenting information.” We needed a strong, graphic model to help
us see a different approach.
 Many projects have multiple stakeholders who want to toss in their favorite
information. We needed a way to set boundaries and define what was truly necessary.

Corrections to some common misunderstandings


Action mapping is increasingly being presented at conferences or taught within big
organizations. A few misunderstandings or misrepresentations have come up. Below are
some clarifications.

It’s a collaborative process — the designer doesn’t create the map on their
own. Action mapping works far better if the client and subject matter expert are included
from the very beginning. Both should definitely be included when setting the goal, and the
SME at least should be included in identifying what people need to do and why they aren’t
doing it. No designer should create a design in isolation.
You should make sure training is really part of the solution. People were skipping
this aspect of step 2, which is why I added the handy flowchart. Action mapping includes
needs analysis; it’s not just a way to organize content. Unfortunately, some people have
presented the system as a way to design activities based on content from the client, skipping
the analysis.

Action mapping isn’t intended for use in academia. I created action mapping for
the corporate world, where it’s relatively easy to set a measurable goal and to analyze what
people need to do on the job to reach that goal. The process focuses on observable,
measurable behaviors, not knowledge, and it assumes that you have people currently doing
the job who you can talk to and observe.

It’s usually not a super-simple diagram. The map gets as complicated as you need it
to get. For example, it’s common to list major actions you want people to take on the job
and then break them down into sub-action that branch off the major ones. The map shown
here is the one I used to design my scenario design course.
It’s not a mind map. You don’t just add stuff as you think of it. An action map looks like a
mind map, but the links between each item create dependencies. Everything on the map
has to justify its existence by linking directly to the business goal. The purpose of the map
is to prevent the casual adding of content.

Struts flow with an example application.


In this example we will see how to create a login application using
ActionForm. The following files are required for the login application.
 login.jsp
 success.jsp
 failure.jsp
 web.xml
 struts-config.xml
 LoginAction.java
 LoginForm.java
 ApplicationResource.properties

web.xml

The first page that will be called in the login application is the
login.jsp page. This configuration should be done in web.xml as
shown below.
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

login.jsp
We use Struts HTML Tags to create login page. The form has one text field to get the user
name and one password field to get the password. The form also has one submit button,
which when clicked calls the login action.

<html:errors /> tag is used to display the error messages to the user.

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"


%>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginForm"
property="userName" />
Password :<html:password name="LoginForm" property="password"
/>
<html:submit value="Login" />
</html:form>
</body>
</html>

The user enters the user name and password and clicks the login button. The
login action is invoked.

struts-config.xml
The validate method in the LoginForm class is called when the Form is submitted. If any
errors are found then the control is returned back to the input page where the errors are
displayed to the user. The input page is configured in the action tag of strut-config file.
<html:errors /> tag is used to display the errors in the jsp page.

<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.vaannila.LoginForm"/>
</form-beans>

<action-mappings>
<action input="/login.jsp" name="LoginForm" path="/Login" scope="session"
type="com.vaannila.LoginAction">
<forward name="success" path="/success.jsp" />
<forward name="failure" path="/failure.jsp" />
</action>
</action-mappings>
</struts-config>

Here the action is "/Login" , the input page is "login.jsp" and the corresponding action
class is LoginAction.java. Now the validate method in the LoginForm class will be invoked.

LoginForm.java
Inside the validate method, we check whether the user name and password is entered. If
not the corresponding error message is displayed to the user. The error messages are
configured in the ApplicationResource.properties file.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {


ActionErrors errors = new ActionErrors();
if (userName == null || userName.length() < 1) {
errors.add("userName", new ActionMessage("error.userName.required"));
}
if (password == null || password.length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));
}
return errors;
}

ApplicationResource.properties
The ApplicationResource.properties file contains the error messages. The key
"error.userName.required" is used in the validate function to add a new error. Since the
error messages are configured in a seperate properties file they can be changed anytime
without making any changes to the java files or the jsp pages.

error.userName.required = User Name is required.


error.password.required = Password is required.

If either user name or password is not entered then the corresponding error message will
be added to the ActionErrors. If any errors are found then the control is returned back to
the input jsp page, where the error messages are displayed using the <html:errors /> tag.
The validate method is used to perform the client-side validations. Once when the input
data is valid the execute method in the LoginAction class is called.

LoginAction.java
The execute method contains the business logic of the application. Here first we typecast
the ActionForm object to LoginForm, so that we can access the form variables using the
getter and setter methods. If the user name and password is same then we forward the user
to the success page else we forward to the failure page.

public class LoginAction extends org.apache.struts.action.Action {

private final static String SUCCESS = "success";


private final static String FAILURE = "failure";
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LoginForm loginForm = (LoginForm) form;
if (loginForm.getUserName().equals(loginForm.getPassword())) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
Lets enter the user names and password as "Eswar". Since the user name and password is
same the execute method will return an ActionForward "success". The corresponding
result associated with the name "success" will be shown to the user. This configuration is
done in struts-config.xml file.

<action-mappings>
<action input="/login.jsp" name="LoginForm" path="/Login" scope="session"
type="com.vaannila.LoginAction">
<forward name="success" path="/success.jsp" />
<forward name="failure" path="/failure.jsp" />
</action>
</action-mappings>

So according to the configuration in struts-config.xml the user will be forwarded to


success.jsp page.

If the user name and password did not match the user will be forwarded to the failure
page. Lets try entering "Joe" as the user name and "Eswar" as the password, the following
page will be displayed to the user.

You can download the source code of the Struts Login Application example by clicking on
the Download link below

Struts 2 Features
1. Struts 2 Features

Struts 2 provides many features that were not in struts 1. The important
features of struts 2 framework are as follows:

1. Configurable MVC components


2. POJO based actions
3. AJAX support
4. Integration support
5. Various Result Types
6. Various Tag support
7. Theme and Template support
1) Configurable MVC components

In struts 2 framework, we provide all the components (view components and


action) information in struts.xml file. If we need to change any information,
we can simply change it in the xml file.

2) POJO based actions

In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java
class. Here, you are not forced to implement any interface or inherit any class.

3) AJAX support

Struts 2 provides support to ajax technology. It is used to make asynchronous


request i.e. it doesn't block the user. It sends only required field data to the
server side not all. So it makes the performance fast.

4) Integration Support

We can simply integrate the struts 2 application with hibernate, spring, tiles
etc. frameworks.

5) Various Result Types

We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.

6) Various Tag support

Struts 2 provides various types of tags such as UI tags, Data tags, control tags
etc to ease the development of struts 2 application.

7) Theme and Template support

Struts 2 provides three types of theme support: xhtml, simple and css_xhtml.
The xhtml is default theme of struts 2. Themes and templates can be used for
common look and feel.

Anda mungkin juga menyukai