You are on page 1of 55

What is Struts?

An open source development framework for building web applications Based on Model-View-Controller (MVC) design paradigm Implementation of JSP Model 2 Architecture Created by Craig McClanahan and donated to Apache Software Foundation (ASF) in 2000

Struts Framework Features Model 2 -MVC Implementation Internationalization(I18N) Support Rich JSP Tag Libraries Based on JSP, Servlet, XML, and Java Supports Javas Write Once, Run Anywhere Philosophy Supports different model implmentations (JavaBeans, EJB, etc.) Supports different presentation implementations( JSP, XML/XSLT, etc)

MVC ARCHITECHTURE
Model : Represents the data objects. The Model is what is being manipulated and presented to the user

View : Serves as the screen representation of the model. It is the object that represents the current state of the data objects. Controller : Defines the way the user interface reacts to the users input. The controller component is the object that manipulates the model or data object.

MODEL
Model is an action class which provides the business logic written by the developer. The dispatch from the controller to the action class is based on the struts-config.Xml file. The model is an object that takes the request from the user and stores the results for the duration of the process. Usually a javabean passes along the information in the process. Model objects are typically application specific since they are basically the business logic of the application. Struts provide the actionform and action classes, which extends to model objects creation. It is in these model objects where form validation, or any type of preprocessing of request data that is necessary, usually takes place.

It's possible to have a one-to-one correlation between model objects and request pages, but it's not necessarily required. It's also quite possible to reuse a model object for multiple page requests. If there is no action necessary for a model object, the controller can send the request directly to the view object, as specified in the struts-config.Xml.

VIEW
View is a set of custom jsp tag libraries. This works in tandem with controller servlet and this facilitates fast and easy creation of html forms. The view object is often a jsp page. The struts framework doesn't actually provide the jsp, but it does provide a number of Tag libraries that easily allow jsp integration into the struts framework. The interaction of struts with jsp allows for storing Data of an input form in a form bean; that is the actionform. The actionform is, then, used by the Action class for doing field validation..

This is a servlet(normally) which dispatches incoming requests to the appropriate action class. The controller is really the traffic cop of the framework and determines when things happen. The controller servlet is responsible for packaging and routing http request to the appropriate object in the framework. This is either a jsp page Or an action class. The controller is in the web.Xml file as an instance of org.Apache.Struts.Action.Actionservlet. When the control is initialized, it reads a configuration file (struts-config.Xml) that specifies action mappings for the application

CONTROLLER

The controller then uses these action mappings to determine where to send the HTTP request. The application action then takes over and performs whatever business logic is necessary. An important aspect to note is that Action objects have access to the servlet's methods.
This is a powerful feature, because when the Action object forwards control to another object, one or more shared objects can be forwarded as well by adding them to one of the standard collections shared by Java servlets.

STRUTS ARCHITECTURE

The Controller Components

Controller Components
ActionServlet(Framework provided) RequestProcessor(Framework provided) ActionClasses (You have to build these)

ActionServlet and RequestProcessor Receive the HttpServletRequest Automatically populate a JavaBean from the request parameters Handle Locale and Content Type Issues Determine which Action to invoke based on URI Provide extension points

ActionServlet Facts Extends javax.servlet.http.HttpServlet Receives all framework requests Selects proper application module Delegates request handling to the RequestProcessor instance One ActionServlet instance per web application Default implementation provided by framework (can extend if necessary)

The RequestProcessor Class One instance per application module Processes all requests for module Invokes proper Action instance Default implementation provided by framework (can extend if necessary)

ActionServlet and RequestProcessor Diagram

What is an ActionForm?
Java class that extends the org.apache.struts.action.ActionForm Captures user data from the Http request Stores the data temporarily Acts as a firewall between the presentation tier and the application Provides the ability to validate the user input

ActionForm Sequence Diagram

Whats an ActionClass? Extends org.apache.struts.action.Action Overrides the execute()method Acts as a bridge between user-invoked URI and a business method (Command pattern) Returns information about which view should be rendered next Part of the Controller, not the Model

Action Class Diagram

Struts-config.xml
The struts-config.xml file is really the glue of the entire framework. While web.xml defines where a request should go upon arriving, struts-config.xml determines exactly what will happen to it. It's the heart of the Struts framework; nothing happens without its okay and knowledge. This is where the mappings of actions are defined. As with the growing number of XML configuration files, the advantage of using one is in keeping a system modular and easy to maintain. It prevents the hard coding of objects to be called within a component. Changes can be made on the fly by changing the configuration files without having to re-deploy applications.

Usage of Custom Tags


struts-html tag library - used for creating dynamic HTML user interfaces and forms. struts-bean tag library - provides substantial enhancements to the basic capability provided by<jsp:useBean>. n struts-logic tag library - can manage conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

struts-template tag library - contains tags that are useful in creating dynamic JSP templates for pages which share a common format. Additionally, the custom tags in the Struts framework use the internationalization features built into the Java platform by using resource files. To provide messages for another language, simply add another resource file.

Bean Tags
Cookie Define a scripting variable based on the value(s) of the specified request cookie. Define Define a scripting variable based on the value(s) of the specified bean property. Header Define a scripting variable based on the value(s) of the specified request header. Include Load the response from a dynamic application request and make it available as a bean. Message Render an internationalized message string to the response. Page Expose a specified item from the page context as a bean. Parameter Define a scripting variable based on the value(s) of the specified request parameter.

Resource Load a web application resource and make it available as a bean. Size Define a bean containing the number of elements in a Collection or Map. Struts Expose a named Struts internal configuration object as a bean. Write Render the value of the specified bean property to the current JspWriter.

Bean Tag Library Example


<b> <bean:write name="UserContainer" property="cart.size scope="session"/> </b> <br>Current Total: <b> $<bean:write name="UserContainer" format="#,##0.00" property="cart.totalPrice scope="session"/> </b>

Bean Tag Example

HTML TAGS
Base Render an HTML <base> Element Button Render A Button Input Field Cancel Render a Cancel Button Checkbox Render A Checkbox Input Field Errors Conditionally display a set of accumulated error messages. file Render A File Select Input Field Form Define An Input Form Hidden Render A Hidden Field HtmlRender an HTML <html> Element Image Render an input tag of type "image" img Render an HTML img tag link Render an HTML anchor or hyperlink Multibox Render A Checkbox Input Field Option Render A Select Option Options Render a Collection of Select Options

Password Render A Password Input Field Radio Render A Radio Button Input Field Reset Render A Reset Button Input Field Rewrite Render an URI Select Render A Select Element Submit Render A Submit Button text Render An Input Field of Type text Textarea Render A Textarea

HTML Tag Example


<table> <tr><b>Shipping Address</b></tr> <tr><td>Address:</td> <td><html:text name="checkoutForm" property="shippingAddress"/> </td></tr> <tr><td>City:</td> <td><html:text name="checkoutForm" property="shippingCity"/> </td></tr> <tr><td>State:</td> <td><html:text name="checkoutForm" property="shippingState"/> </td></tr> <tr><td>Postal:</td> <td><html:text name="checkoutForm" property="shippingPostal"/> </td></tr> </table>

HTML Tag Example

Error Messages <trclass="RED"> <td></td> <td> <html:messages id="error"> <li><bean:write name="error"/></li> </html:messages> </td> </tr>

LOGIC TAGS
equal Evaluate the nested body content of this tag if the requested variable is equal to the specified value. forward Forward control to the page specified by the specified ActionForward entry. greaterEqual Evaluate the nested body content of this tag if the requested variable is greater than or equal to the specified value. greaterThan Evaluate the nested body content of this tag if the requested variable is greater than the specified value. iterate Repeat the nested body content of this tag over a specified collection

lessEqual Evaluate the nested body content of this tag if the requested variable is greater than or equal to the specified value. lessThan Evaluate the nested body content of this tag if the requested variable is less than the specified value. match Evaluate the nested body content of this tag if the specified value is an appropriate substring of the requested variable. notEqual Evaluate the nested body content of this tag if the requested variable is not equal to the specified value. notMatch Evaluate the nested body content of this tag if the specified value is not an appropriate substring of the requested variable. notPresent Generate the nested body content of this tag if the specified value is not present in this request. present Generate the nested body content of this tag if the specified value is present in this request. redirect Render an HTTP Redirect

Logic Tag Library Example


<logic:iterate id="cartItem" scope="session" name="UserContainer" property="cart.items"> <html:link page="/action/viewitemdetail?method=viewItem" paramName="cartItem" paramId="id" paramProperty="id"> <bean:write name="cartItem" property="name"/> </html:link> </logic:iterate>

Logic Tag Library Example

TEMPLATE TAGS
insert Inserts (includes, actually) a template. Templates are JSP pages that include parameterized content. That content comes from put tags that are children of insert tags. putPuts content into request scope. getGets the content from request scope that was put there by a put tag.

INTERNATIONALIZATION (I18N)
Two Components are packaged with the struts framework. 1. Message Class 2. JSP Custom tag , <bean:message>

INTERNATIONALIZATION (I18N)
Defining Resource Bundles This is a file with the key / value pair for the default language of the application. For English : ApplicationResources.properties

For Italian : ApplicationResources_it.properties


The entries in this file will be made as app.symbol = smbl

we can get the two letter ISO language codes in www-old.ics.uci.edu/pub/ietf/http/related/iso639.txt

INTERNATIONALIZATION (I18N)
The ApplicationResources.properties files are loaded upon application startup. If we make changes to this file ,then the application must be reloaded. This file is placed in the application classpath ie
/WEB-INF/classes/package/ ApplicationResources.properties

In the struts-config file we have to make an entry


<message-resources parameter=package.ApplicationResources/>

INTERNATIONALIZATION (I18N)
<bean:message> tag Has three main attributes

key :
The key attribute is the unique value that is used to retrieve a message from the resource bundle.

Bundle :
This attribute is the name of the bean under which messages are stored. This bean is stored under the ServletContext.if the bundle is not included the default value of Action.MESSAGES_KEY is used.

Locale :
This attribute names the session bean that references the requesting clients Locale. If the bundle is not included the default value of Action.LOCALE_KEY is used.

Dynamic ActionForms
Define ActionForms declaratively Behave like regular Action Forms throughout the application No need to define ActionForm classes

DynaActionFormExample
<form-bean name="checkoutForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="shippingAddress" type="java.lang.String"/> <form-property name="shippingCity" type="java.lang.String"/> <form-property name="shippingState" type="java.lang.String"/> <form-property name="shippingPostal" type="java.lang.String"/> </form-bean>

DynaActionForm Example
<table> <tr><b>Shipping Address</b></tr> <tr> <td>Address:</td> <td><html:text name="checkoutForm" property="shippingAddress"/> </td></tr> <tr><td>City:</td> <td><html:text name="checkoutForm" property="shippingCity"/> </td></tr> <tr><td>State:</td> <td><html:text name="checkoutForm" property="shippingState"/> </td></tr> <tr><td>Postal:</td> <td><html:text name="checkoutForm" property="shippingPostal"/> </td></tr> </table>

Validation Framework Features


Allows for regular expressions to be used Comes with many pre-built validation routines Supports Client-Side (JavaScript) and Server-Side (Java)

Validator configuration Files


validator-rules.xml validation.xml

Validator-rules.xml File
<validatorname="required" classname="org.apache.struts.util.StrutsValidator" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required">

Validator.xml File
<form name="checkoutForm"> <field property="shippingAddress" depends="required,mask"> <arg0 key="label.address"/> <var> <var-name>mask</var-name> <var-value>^\w+$</var-value> </var> </field>

Message Bundle
errors.required={0} is required. errors.minlength={0} can not be less than {1} characters. errors.maxlength={0} can not be greater than {1} characters. errors.invalid={0} is invalid. errors.byte={0} must be an byte. errors.short={0} must be an short. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.float={0} must be an float. errors.double={0} must be an double. errors.date={0} is not a date.

Struts Plug-in Capabilities


Declarative means for Startup Classes Can declare multiple Plug-ins per sub-application Just need to implement the PlugIn interface Framework will call init() on startup and destroy() on shutdown

Plug-in Example
<plug-in className="com.cavaness.beer4all.service.ServiceFactory"> <set-property property="serviceClassName" value="com.cavaness.beer4all.service.Beer4AllOBJService"/> </plug-in>

Tiles Library Features


Advanced templating mechanism Set of JSP Tags Supports the idea of Layouts (known as Tiles) Layouts based on Locale/Channel Tiles can be reused Created by Cedric Dumoulin(while working at S1 coincidently)

Layout Tile
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%> <%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%> <%@taglib uri="/WEB-INF/tiles.tld" prefix="tiles"%> <html:html> <head><title><bean:message key="global.title"/></title> </head> <bodytopmargin="0"leftmargin="0"bgcolor="#FFFFFF"> <tiles:insert attribute="header" /> <tiles:insert attribute=banner"/> <tiles:insert attribute="body-content"/> <tiles:insert attribute="copyright"/> </body> </html:html>

Tiles XML Definition


<!DOCTYPE tiles-definitions PUBLIC -//Apache Software Foundation//DTD Tiles Configuration//EN" http://jakarta.apache.org/struts/dtds/tiles-config.dtd"> <tiles-definitions> <definition name=beer4All.default" path="/layouts/beer4allDefaultLayout.jsp"> <put name="header" value="/common/header.jsp" /> <put name=banner" value="/common/banner.jsp" /> <put name="copyright" value="/common/copyright.jsp" /> </definition> </tiles-definitions>

You might also like