P. 1
Struts

Struts

|Views: 316|Likes:
Published by jajupreetam

More info:

Published by: jajupreetam on Jul 20, 2008
Copyright:Traditional Copyright: All rights reserved

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF or read online from Scribd
See more
See less

05/10/2011

Struts Technology

Designed By:

Design Pattern –Model 1
The Model 1 web application: A collection of JSP pages working largely independently of each other. Each page directly transfers control to the next page. There is no separate controller.

Model 1 - Main Problems
A simple change can result in a cascade of changes in many different pages with unpredictable consequences. Complexity grows fast as well, and what might originally look simple and straightforward can quickly turn into a big mess as you add more pieces.

Design Pattern - Model 2
Model 2 represents a framework based on the ModelView-Controller (MVC) system. Each page reports back to the controller, which decides what to do next.

The MVC view
The views within the web tier MVC pattern typically consist of HTML and JSP pages. HTML pages are used to serve static content, while JSP pages can be used to serve both static and dynamic content. Most dynamic content is generated in the web tier

The MVC controller
The controller portion of the web tier MVC design is generally a Java servlet. The controller in a web tier application performs the following duties:
Intercepts HTTP requests from a client. Translates the request into a specific business operation to perform. Either invokes the business operation itself or delegates to a handler. Helps to select the next view to display to the client. Returns the view to the client.

What is a Framework?
A framework is made up of multiple classes or components, each of which may provide an abstraction of some particular concept The framework defines how these abstractions work together to solve a problem The framework components are reusable. A good framework should provide generic behavior that can be utilized across many different types of applications.

Typically, a framework may include support programs code libraries and a scripting language amongst other software to help develop and glue together the different components of your project

Difference b/w an API and framework
framework is a set of classes which handles the flow necessary to perform a complex task, but which requires plug-in classes specific to your application (database, app server), and which allows for additional plug-in classes to extend the functionality.

Example
For example, you could have a framework which handles the general flow of an online store. This framework would handle tasks such as "put item in shopping cart", "generate order on checkout", etc. On the other hand, you would need to provide the classes which enable the framework to persist the shopping cart to the database of your choice, to connect to a credit-card processor, to send orders to a warehouse, among other things

Api
An API is really no more than a set of method signatures and other information necessary to use a class or set of classes. The API is totally distinct from the implementation. For example, a number of vendors have implemented the servlet API, each in a different way. The API by itself has no implementation. A class library would have an API, as would a framework.

High-level architecture view for a Struts application.

What is a container
There are many different types of containers. There are EJB Containers, Web Containers, servlet containers, and so on. In general, containers provide a hosting environment for software components to run in. Containers provide general services that can be used by the components within the environment, without the need or worry of being required by the component developer.

A web container
A Web Container allows servlets, JSP components, and other Java classes to be deployed and executed within the container. Services like JNDI, connection pooling, and transaction services, can be configured at the container level, and the component developers don’t have to worry about the management of these resources. similar to the way in which EJB containers manages security, transactions, and bean pooling.

The container architecture
a container is a runtime environment for application components

The container architecture
The architecture contains two elements, the container itself and the components that someone put in. The glue between the two is the so called "deployment descriptor". The deployment descriptor is application dependent and therefore the responsibility of the people that create and deploy the application component

The client tier
The Client tier provides a means for a user to interact with the application. This interaction may be through a web browser, or it could also be programmatic through a web services interface. Regardless of the type of client, the interaction includes submitting a request and receiving some type of response from the Middle tier In the case of the Struts framework, the most common type of client is a web browser. However, it is also possible to have clients like wireless devices and Java Applets.

The web-tier
The Web tier provides the ability for the client tier to communicate and interact with application logic that resides in other tiers. In more traditional web applications, it’s not uncommon for some or all of the application logic to reside in this tier. In larger,enterprise-scale applications, the Web tier acts as a translator and maps HTTP requests into service invocations on the Middle tier

The web-tier..
The Web tier communicates with either a database, or in the case of an enterprise application, an application server. The Web Tier is the glue that binds client applications to the core backend business systems. The components that reside in the Web tier allow developers to extend the basic functionality of a web service. In the case of Struts, it does this by utilizing framework components that run in a servlet container.

The middle-tier
The Middle tier is often referred as the “application tier” or “server”. This is due in part to the fact that there is often an application server within this tier. Not all Struts applications have an application tier.

Main purpose of an application server
One of the main purposes of using an application tier is to separate the responsibilities of presentation from that of the model and the business rules for the application. Today, many web applications are using EJB servers for their application tier. They may not be utilizing all aspects of the J2EE architecture, like EJBs, but there are other benefits that can be leveraged from a J2EE server.

The J2EE application server

Struts
What is Struts Classes and the MVC paradigm Configuring Struts Features

What is struts?
An open source Jakarta Apache project An Implementation of a MVC Paradigm A framework written in Java A web-tier layer built on Servlets, JSP, and XML.

An open source Jakarta Apache project

Struts is part of the Apache Jakarta Project, sponsored by the Apache Software Foundation. http://jakarta.apache.org/struts/index.html

An Implementation of a MVC Paradigm
Struts is an implementation of the Model-ViewController (MVC) pattern: This is considered a Model 2 architecture. (Model 1 architecture combines the roles of the view and controller components.) The model component handles the business domain state and data The view component handles the presentation of the business domain. The controller component processes the user input to direct the flow and manage user state.

Model View Controller Components

Struts designed for J2EE
Struts is an application development framework that is designed for and used with the popular J2EE (Java 2, Enterprise Edition) platform. It cuts time out of the development process and makes developers more productive by providing them a series of tools and components to build applications with. It is non-proprietary and works with virtually any J2EEcompliant application server. Struts falls under the Jakarta subproject of the Apache Software Foundation and comes with an Open Source license (meaning it has no cost and its users have free access to all its internal source code).

Where does Struts Fit In?

Struts applications are hosted by a web container and can make use of services provided by the container, like handling requests via the HTTP and HTTPS protocol. This frees developers up to focus on building applications that solve a business problem.

A framework written in Java
Some of the classes in the frame work are
ActionServlet RequestProcessor ActionMapping Action ActionForm ActionForward The Struts framework is made up of approximately 200 Java classes, divided into 15 Java packages.

Struts implementation of MVC in ePurchasing Architecture

Now how does this whole thing work
-

-

-

Now how does this whole thing work…when a request is made from a previously displayed View… The request is received by the ActionServlet, which acts as the Controller, and the ActionServlet looks up the requested URI in an XML file (the struts-config) and determines the name of the Action class that will call the necessary business logic. The Action class calls a Model Components associated with the task which will do data manipulation and return the data to the action class.

-

-

-

Once the Action has completed its processing, it returns control to the ActionServlet. As part of the return, the Action class provides a key that indicates the results of its processing. The ActionServlet uses this key to determine where the results should be forwarded for presentation. The request is completed when the ActionServlet responds by forwarding the request to the View that was linked to the returned key, and this View presents the results of the Action.

Servlet as controller
JSP Model 2 architecture, on which Struts was fashioned the controller was implemented by a Java servlet. This servlet becomes the centralized point of control for the web application. The controller servlet maps user actions into business operations and then helps to select the view to return to the client based on the request and other state information

Controller : Components
ActionServlet RequestProcessor Action Classes

Struts Controller Components
The controller portion of Struts is the meat of the framework. The ActionServlet is the controller. This servlet is registered via the web.xml file to handle all the requests for Struts (usually via a url mapping). The controller does the following:
process the user request determine the action the user is requesting invoke the corresponding model forward the necessary data from the model to the correct view

ActionServlet

The Struts ActionServlet class extends the javax.servlet.http.HttpServlet class and is responsible for packaging and routing HTTP traffic to the appropriate handler. This servlet takes on administering the behavior of the “Controller”. Like any other Java servlet, the Struts ActionServlet must be configured in the deployment descriptor for the web application. The ActionServlet is configured in the deployment descriptor to accept a pattern of URLs such as *.do.

Controller

Controller (cont…) the deployment descriptor

Controller (cont…)

RequestProcessor(later)
In version 1.1, a new class called org.apache.struts.action.RequestProc essor has been introduced to process the request for the controller. The main reason for decoupling the request processing from the ActionServlet is to provide you with the flexibility to subclass the RequestProcessor with your own version and modify how the request is processed.

Controller : RequestProcessor
One instance per web application module Processes all request for module Invokes proper Action instance Default implementation provided by framework

Next?-Action
Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation that is associated with the requested action. In the Struts framework, this helper class is a descendant of the org.apache.struts.action.Action class.

Controller : Action Classes
Extends <org.apache.struts.action.Action> In Struts 1.0 overrides the perform() method In Struts 1.1 overrides the execute() method Acts as a bridge between user-invoked URI and a business method Provides information about which view should be rendered and returned

Signature of execute

The Struts Action class contains several methods, but the most important is the execute() method. Here is the method signature: public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;

Example of Action Class
public class NewReqAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Check if user logged in // (can be implemented by extending RequestProcessor) HttpSession session = request.getSession(false); LoginModel loginModel = new LoginModel(); if (!loginModel.isLoggedIn(session)) { ActionForward login = mapping.findForward("login"); login.setRedirect(true); return login; }…

Example of Action Class (cont.)
… // Get User’s information String userID = (String) session.getAttribute("userID"); UserBean userBean = UserModel.getUserInfo(userID); userBean.setFirstName((String) session.getAttribute("firstName")); userBean.setLastName((String) session.getAttribute("lastName")); userBean.setMiddleInitial((String) session.getAttribute("middleInitial")); ReqModel reqModel ReqBean reqBean VndrBean vndrBean reqBean = = = = new ReqModel(); new ReqBean(); new VndrBean(); (ReqBean) reqModel.init(userBean, vndrBean, reqBean);

request.setAttribute("reqBean", reqBean); return (mapping.findForward("success")); } // perform() } // eof: NewReqAction

An action class-more of a controller
An org.apache.struts.action.Action class in the Struts framework is an extension of the controller component. It acts as an Adaptor between a user action and a business operation. The Action class decouples the client request from the business model. This decoupling allows for more than a one-to-one mapping between the user request and an Action class. The Action class can perform other functions, such as authorization, logging, and session validation, before invoking the business operation.

The action class
The action class is the heart of the framework. It’s the bridge between client request and a business operation Each Action class typically is designed to perform a single business operation on behalf of a client. A single business operation ideally is related to one business operation. For instance, you shouldn’t create an Action that performs shopping-cart functionality as well as handling login and logout responsibilities. These areas of the applications are not closely related and shouldn’t be combined.

execute() method
The execute() method is called on an instance of an Action class by the controller when a request is received from a client. The controller will create an instance of the Action class if one doesn’t already exist. The Struts framework will only create a single instance of each Action class in your application. Since there is only one instance for all users, you must ensure that all of your Action classes operate properly in a multithreaded environment.

example
Login Logout getAccountInformation…

Mapping the actions
“How does the controller know which Action instance to invoke when it receives a request?” The answer is by inspecting the request information and utilizing a set of action mappings.

Action Mapping
Action Mapping Configuration For mapping a request URL to a particular Action class, the ActionServlet class is to be provided with suitable information using ActionMapping interface. Struts provides a declarative way in the form of XML configuration file to pass this information to the controller servlet. The controller servlet parses this file and gets the required information to handle the incoming request.

Config.xml
The configuration file usually named as strutsconfig.xml file should be defined and placed in the WEB-INF folder of the application Web Archive (WAR file). The controller servlet knows the configuration file from the web.xml where it is declared as follows :

Example of ActionMapping
<!-- Initial requisition form with user defaults --> <struts-config> … <action-mappings type="org.apache.struts.action.ActionMapping"> … <!-- Initial requisition form with user defaults --> <action path="/newReqInit" type="edu.hawaii.purchasing.NewReqInitAction" name="reqForm" scope="request" attribute="reqForm"> <forward name="success" path="/jsp/reqForm.jsp" /> </action> … </action-mappings> </struts-config>

In the web.xml
<servlet> .... <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml </param-value> </init-param> </servlet>

Model

Model : Facts
No model components provided Struts supports any model component - EJB, Corba, JavaBeans, etc Decouple model implementation from the framework

Example of Model Class
public class UserModel { private static Category logger = Category.getInstance(UserModel.class.getName()); public static UserBean getUserInfo(String userID) throws IOException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection( PropertiesLoader.getProperty("oracle.datasource")); stmt = conn.createStatement();

Example of Model Class (cont.)
// SQL Statement String colNames = "dept, deliv_addr_1, deliv_addr_2, deliv_addr_3, " + “deliv_addr_4, deliv_city, deliv_st, deliv_zip, …”; String tableName = "fmis_user "; String sqlStmt = "select " + colNames + "from " + tableName + "where user_id = '" + userID + "'"; rs = stmt.executeQuery(sqlStmt); UserBean user = new UserBean(); while (rs.next()) { user.setDelivDept(rs.getString("dept")); user.setDelivAddr1(rs.getString("deliv_addr_1")); user.setDelivAddr2(rs.getString("deliv_addr_2")); … } return user; } … //catch exception and finally close ResultSet, Statement, Connection

View

View : Components
Java Server Pages HTMLs JavaScripts and StyleSheets Resources Bundles JavaBeans extending ActionForms Custom Tags - HTML, Bean, Logic

Struts View
The view components typically employed in a struts application are HTML Data Transfer Objects Struts ActionForms JavaServer pages Custom tags Java resource bundles

Struts ActionForm
Struts ActionForm objects are used to pass client input data back and forth between the user and the business layer. The framework automatically collects the input from the request and passes this data to an Action using a form bean, which is then passed to the business layer.

View (cont…)

MVC Drawbacks
A complex framework must be set up first. Building a page now becomes a multi-step process that requires extra planning and forethought.

Summary
In a complex Web application, using Struts will reduce code repetition, increase control flexibility, and reduce coupling between unrelated components. With Struts, the number of classes and pages is initially larger because various components are split, but as you define more pages, consolidation and software re-use will occur.

Closing Thought
A good scientist is a person with original ideas. A good engineer is a person who makes a design that works with as few original ideas as possible. --- Freeman Dyson

Acknowledgements
Parts or Portions of this presentation are taken from the following sources: http://jakarta.apache.org/struts/userGuide http://www.jspinsider.com/tutorials/jsp/struts/strutsintro.view http://www.javaworld.com/javaworld/jw-11-2000/jw-1103presentation_p.html Professional Java Server Programming J2EE 1.3 Edition Proposed Description of the Integrated Microarray Database System Chuck Cooper

Getting Started with Struts

Struts provides the controller in the form of an ActionServlet class. The framework uses this class for handling all the requests. To enable your application to use this controller servlet, include the following in the deployment descriptor i.e. web.xml
<servlet> <servlet-name>action</servlet-name> <servletclass>org.apache.struts.action.ActionServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/*.do</URL-pattern> </servlet-mapping>

In web.xml, we also need to specify the mapping of application URLs to this servlet. In the above code any URL with .do extension calls the ActionServlet to handle the request. To carry out an appropriate action for a particular request, the ActionServlet is configured using Action Mappings in the struts-config.xml file. An Action Mapping specifies a fully qualified Action class name that should be invoked when a URL matching its path is requested. Following is a sample action mapping :
<action path="/Register" type="RegisterAction" scope="request" name="registerForm"> <forward name="success" path="/pages/Message.jsp"/> <forward name="failure" path="/pages/Register.jsp"/> </action>

When a URL for the application ending with Register.do is called, the ActionServlet searches for a mapping with path as /Register. It then instantiates the class defined by the type attribute to perform the required action. Any form parameters in the request object are passed to the Action class using the form bean defined by the name attribute. The name attribute defines a logical name for the form bean, the mapping for which done is using <form-bean> tag in sturts-config.xml file as shown below:
<form-beans> <form-bean name="registerForm" type="RegisterForm"/> </form-beans>

Using this input the Action class performs operations to serve the request. Depending on the result of operation, the user is directed to the next view using the ActionForward object (which represents the <forward> tag in Action Mappings).

Writing an Action Class

An Action class is an adapter between an incoming HTTP request and the corresponding business logic that should be executed to process this request. It should define a perform method which will be automatically invoked to serve the request. For each request, the controller ( ActionServlet class) will select an appropriate Action class, create an instance (if one does not exist), and call the perform method. The perform method should be implemented to execute the business logic for serving the request, handle errors and navigate to appropriate view based on outcome of the action. Usually it is a good practice to delegate the business logic part of implementation to Enterprise Java Beans(EJB) or simple vanilla Java Beans. Here is a sample implementation of action class
... //class imports .... public class RegisterAction extends Action { /** * function: execute() * @param mapping The ActionMapping used to select * this instance * @param actionForm The optional ActionForm bean * for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @throws IOException if an input/output error occurs * @throws ServletException if a servlet exception occurs * @return where control will be forwarded to after * this request is processed * @description :This is the main action called from * the struts framework. */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // define variable to forward control to next view ActionForward actionForward=null; ...... // execute business logic ...... //on success forward the control to main jsp page actionForward = mapping.findForward("success"); mapping.findForward("failure"); return actionForward; }

Many times it is required to use the same action class for related a set of operations, say, for example, retrieving the user's profile from the database and then updating it after modification. In such cases, the action class should extend org.apache.struts.actions.DispatchAction class. Different methods are defined for each action with methods having the same signature as the perform method above. For invoking a particular method, the name of method is passed as the value of parameter with the invoking URL. The name of this parameter is defined in Action Mapping for the URL. For example, a URL to invoke update function in action class with parameter name as method in Action Mapping would look as follows :
http://localhost:8080/GetProfile?method=update
Action Mapping Configuration

For mapping a request URL to a particular Action class, the ActionServlet class is to be provided with suitable information using ActionMapping interface. Struts provides a declarative way in the form of XML configuration file to pass this information to the controller servlet. The controller servlet parses this file and gets the required information to handle the incoming request. The configuration file usually named as struts-config.xml file should be defined and placed in the WEB-INF folder of the application Web Archive (WAR file). The controller servlet knows the configuration file from the web.xml where it is declared as follows :
<servlet> .... <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> </servlet>

Following are the important elements of struts-config.xml file :
<struts-config> <form-beans> <form-bean name="registerForm" type="RegisterForm"/> </form-beans> <global-forwards> <forward name="Login" path="/Login"/> </global-forwards>

<action-mappings> <action path="/Profile" type=" ProfileAction" scope="request" name="registerForm" validate="true" parameter="method" > <forward name="success" path="/pages/Profile.jsp"/>

<forward name="failure" path="/ pages/Login.jsp"/> </action> </action-mappings> </struts-config>

<form-beans> : Contains definition of the beans used by the application. A <form-bean> describes an instance of ActionForm class that will be used to pass the form data to the action class. Important attributes of <form-bean> are as follows:
name type : A unique identifier for the bean that will be used as reference in action mappings. : Fully qualified class name of the ActionForm subclass used to defined this bean.

<global-forwards>: This elements define the forwards that can be used by all action mappings. A Forward is an instance of ActionForward class that maps a resource name to the actual resource in the application. These forward names are used in application to forward the control to the next view based on the outcome of execution of a request. Important attributes of a <forward> element are as follows : name : The logical name of the forward. This will be used in the application to forward the request to the resource referenced by this forward. path : The relative path to the resource (typically jsp page). redirect : true or false. If true, a redirect is carried out to the resource instead of forward.

<action-mappings>: This element is used for defining mapping for various actions using <action> tags. An <action> tag is used to map a request URL to a particular action and pass associated information. Here are important attributes of <action> element : : The application context-relative path to the action e.g. /SignUp type : Fully qualified name of Java class that will be used to execute this action. name : The logical name of form bean used to pass the form data to action class. parameter : The name of parameter whose values is used to call a particular method in action class. validate : Set to true if the validate() method of the action associated with this mapping should be called. forward : The request URI to which the control should be passed for this action mapping. path

Handling Form Data

Your form may contain lot of information as an input from the user when a request is made. This data can be passed as an instance of ActionForm class to the serving Action class for processing. The ActionForm class is subclassed to create a Java bean that defines getter and setter method for the fields defined in the input form. The action mapping for a particular request defines which ActionForm class is to be used to pass the form data to Action class. Here is a simple definition of a class used when the user tries to register with the Web application import org.apache.struts.action.ActionForm;

public class RegisterForm extends ActionForm { private String firstName = null; private String lastName = null;

/** * Get the first name */ public String getFirstName(){ return (firstName); } /** * Set the last name */ public void setfirstName(String firstName ){ this.firstName =firstName ; } /** * Get the last name */ public String getLastName(){ return (lastName); } /** * Set the last name */ public void setLastName(String lastName ) { this.lastName =lastName ; } } The ActionForm subclass follows standard Java Beans convention to name the methods for a property. This mechanism of Struts proves to be a better alternative to <jsp: useBean> tag to capture form data. It helps to avoid calling Java Beans in the JSP page(the view) avoiding tight coupling between the two and provides a declarative way to do the same.

ActionForward Configuration

A forward is defined using <global-forward> or a <forward> element in the <action> tag as explained earlier. A forward maps a resource to a logical name which can be referenced in the Action class to forward the control of the application as and when required. Struts provides a convenient method viz. ActionForward.findForward(forwardName) to locate a forward using logical name defined in the config file. This instance of ActionForward is returned to the RequestProcessor which forward the control to the next view identified by the selected forward. Global forward defined in the config file using <global-forward> tag can be used by all the action classes to forward the control. For example an application that requires a user to login before performing any operations, can define a global forward to direct the user to a login page when he/she requests any URL of the application. In addition, an action mapping can define forward specific to its requirements using a <forward> tag in the action mapping. ActionForward provides a convenient way to declare the forward path without having to hard code it in the Action class. The path is referred by a logical name in the code and hence can be changed anytime in the config file based on the requirement without modifying the code.
Handling Exceptions

Exceptions thrown by perform method in the Action class can be handled by defining an exception handler class derived from org.org.apache.struts.action.ExceptionHandler . The execute method in this class should be overridden to contain the code that should be executed in case of exception. This method should return an ActionForward class instance defining an appropriate forward to the next view. The exception handler class is configured in the config file using <global-exception> tag or by using <exception> tag specific to an action mapping as follows :

<global-exceptions> <exception key="exception.key" type="java.lang.NullPointerException" handler="app.mypackage.ExceptionHandler"/> </global-exceptions> <action path=/Profile ... <exception key="exception.key" type="java.lang.NullPointerException" handler="app.mypackage.ExceptionHandler"/> </action>

When the above configuration is done, the execute method of ExceptionHandler is invoked whenever a NullPointerException is thrown during processing of corresponding request. The execute method can forward control to a page displaying the message defined by the key attribute in message resource properties. Instead of a handler attribute, you could directly give a path attribute to redirect the user to a page specified by the path in case no operation needs to be performed on exception. Such a configuration will look as follows :
<action path=/Profile ... <exception key="exception.key" type="java.lang.NullPointerException" path="/root/Message.jsp"/> </action>

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->