Вы находитесь на странице: 1из 33

BB: Struts

ATS Application Programming: Java


Programming

© Accenture 2005 All Rights Reserved Course Code #Z16325


Objectives
This review session will cover Struts.
Included in this review:

 What is Struts
 Struts Framework Features
 Struts Architecture
 Struts Model Component
 Struts View Component
 Struts Control Component
 Struts Tag Libraries (HTML, Bean, Logic)
 ActionForm
 ActionServlet
 Action ©2005 Accenture All Rights Reserved. 2
© AccentureActionMapping

2005 All Rights Reserved
Overview
Detailed in this
review:

 The Framework of the


Struts
 How It is Implemented

©2005 Accenture All Rights Reserved. 3


© Accenture 2005 All Rights Reserved
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
 2nd Release candidate of version 1.1 released
 Consists of 8 Top-Level Packages
 Approx 250 Classes and Interfaces

©2005 Accenture All Rights Reserved. 4


© Accenture 2005 All Rights Reserved
 Struts Framework Features
Model 2 - MVC Implementation
 Internationalization (I18N) Support
 Rich JSP Tag Libraries
 Based on JSP, Servlet, XML, and Java
 Supports Java’s Write Once, Run Anywhere Philosophy
 Supports different model implementations (JavaBeans, EJB, etc.)
 Supports different presentation implementations (JSP, XML/XSLT,
etc.)

©2005 Accenture All Rights Reserved. 5


© Accenture 2005 All Rights Reserved
Struts Architecture

©2005 Accenture All Rights Reserved. 6


© Accenture 2005 All Rights Reserved
Struts Architecture

©2005 Accenture All Rights Reserved. 7


© Accenture 2005 All Rights Reserved
Struts Architecture
 Central controller mediates application flow
and delegates to appropriate handler.
 Handlers are tied to model components.
 Model encapsulates business logic.
 Control forwarded back through the Controller
to the appropriate View.
 The forwarding can be determined by
consulting a set of mappings in configuration
file, which provides a loose coupling between 8
©2005 Accenture All Rights Reserved.

the View and Model.


© Accenture 2005 All Rights Reserved
Struts “Model” Components
 No built-in support for the model.
 No model components provided.
 Framework supports any component model.
(JavaBeans, EJB, Corba, etc.)
 Should always decouple the application from a
specific model implementation.

©2005 Accenture All Rights Reserved. 9


© Accenture 2005 All Rights Reserved
Struts “View” Components
 JavaServer Pages
 HTML
 JavaScript and Stylesheets
 Multimedia Files
 Resource Bundles
 JavaBeans (Part of model used by views)
 JSP Custom Tags
 ActionForms
©2005 Accenture All Rights Reserved. 10
© Accenture 2005 All Rights Reserved
Struts “Control” Components
 ActionServlet
- Extends javax.servlet.http.HttpServlet
- Receives all framework requests
- One ActionServlet instance per web application
 RequestProcessor
- One instance per application module
- Processes all requests for module
- Invokes properAction instance
- Default implementation provided by
framework (can extend if necessary)
 ActionClasses
- 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
©2005 Accenture All Rights Reserved. 11
© Accenture 2005 All Rights Reserved
Struts Tag Libraries
 THE HTML TAG LIBRARY
- Tags used to create Struts input forms
- Examples include (checkbox, image, link, submit, text, textarea)
<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>

©2005 Accenture All Rights Reserved. 12


© Accenture 2005 All Rights Reserved
HTML Tags (cont.)
 Acts as a bridge between JSP view and other
components.
 Input forms are important for gathering data.
 Most of the actions of the HTML taglib
involve HTML forms.
 Error messages, hyperlinking,
internationalization.
 HTML tags must be nested within a form tag.
– Inform handler which
©2005 bean
Accenture to use
All Rights for initializing
Reserved. 13
displayed values.
© Accenture 2005 All Rights Reserved
Struts Tag Libraries
 THE BEAN TAG LIBRARY
- Tags used for accessing JavaBeans and their properties
- Examples include (define, message, write)

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

©2005 Accenture All Rights Reserved. 14


© Accenture 2005 All Rights Reserved
Bean Tags (cont.)
 Tags for accessing beans and their properties
 Enhancements to <jsp:useBean>
 Convenient mechanisms to create new beans
based on the value of:
– Cookies
– Request Headers
– Parameters

©2005 Accenture All Rights Reserved. 15


© Accenture 2005 All Rights Reserved
Struts Tag Libraries
 THE LOGIC TAG LIBRARY
– Managing conditional generation of output text
– Looping over object collections for repetitive generation of output text
– Application flow management.
– Examples include (empty, lessThan, greaterThan, redirect, iterate)

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>

©2005 Accenture All Rights Reserved. 16


© Accenture 2005 All Rights Reserved
Logic Tags (cont.)
 Provides presentation logic tags for:
 Value comparisons
– Include: = != <= >= < >
 Substring matching
– match, notmatch
 Presentation logic
– forward, redirect
 Collections
– iterate
©2005 Accenture All Rights Reserved. 17
© Accenture 2005 All Rights Reserved
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.

©2005 Accenture All Rights Reserved. 18


© Accenture 2005 All Rights Reserved
ActionForm (cont.)
 Provided by developer
 Define an ActionForm bean (that is, a Java class
extending the ActionForm class) for the input form
 Extend Struts-provided ActionForm class
 Define it in servlet-config.xml file
– <form-bean>
– name attribute of <Action> class
 Contains only property getter and property
setter methods for each field - no business
logic ©2005 Accenture All Rights Reserved. 19
© Accenture 2005 All Rights Reserved
Example
ActionForm (cont.)
package com.jds.apps.hr.employee.form;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

public class EmployeeInfoForm extends AbstractEmployeeForm {

public ActionErrors validate(ActionMapping mapping,


HttpServletRequest request) {

ActionErrors errors = new ActionErrors();


// Last Name: if it's empty, has a special character, or exceeds it's maximum length
if( objectIsNull.validate(this.getLastName() ) ||
stringIsEmpty.validate( this.getLastName() ) ){
errors.add("lastName", new ActionError("field.null","Last Name"));
}
else if( !stringIsValidD.validate( this.getLastName() ) ){
errors.add("lastName", new
ActionError("field.invalid.specialcharacter", "Last Name", allowedCharactersD));
©2005 Accenture All Rights Reserved. 20
}
© Accenture 2005 All Rights Reserved
else if( !stringLengthIsValidFifty.validate( this.getLastName() ) ){
ActionServlet
What Does ActionServlet Do?

 Performs the role of Controller


– Process user requests
– Determine what the user is trying to achieve
according to the request
– Pull data from the model (if necessary) to be given
to the appropriate view, and
– Select the proper view to respond to the user
©2005 Accenture All Rights Reserved. 21
 Delegates most of this grunt work to Action
© Accenture 2005 All Rights Reserved
Action Class
Focus on control flow
 Process client request by calling other objects
(BusinessLogic beans) inside its execute() method
 Returns an ActionForward object that identifies
where control should be forwarded
– JSP
– Tile definition
– Velocity template
– Another Action

©2005 Accenture All Rights Reserved. 22


© Accenture 2005 All Rights Reserved
Action Class (cont.)
What is Action Class?
 Java class that does the “work” of your

application
– Handle request
– Perform business logic
 Can be simple or sophisticated
– Simple action class does handle business logic by
itself
– Sophisticated ones invoke Model components
©2005 Accenture All Rights Reserved. 23
 Action class functions as a Facade pattern in this case
© Accenture 2005 All Rights Reserved
Example
Action Class (cont.)
package com.jds.apps.hr.employee.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class EmployeeAddAction extends AbstractAction {

public ActionForward execute(ActionMapping actionMapping,


ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {

EmployeeInfoForm viewForm = (EmployeeInfoForm) form;

// Determine action, if edit or view mode


©2005 Accenture All Rights Reserved.
UserBean userBean = this.getUserBean(request); 24
String
© Accenture 2005userType
All Rights = userBean.getUserType();
Reserved
ActionMapping
 An ActionMapping object describes an Action
instance to the ActionServlet.
 It represents the information that uniquely
defines an instance of a particular action class.
 Provides useful information to both the
Action.execute() and the
ActionForm.validate() methods, enabling a
developer to alter its behavior based upon the
values describing this particular Action.
©2005 Accenture All Rights Reserved. 25
© Accenture 2005 All Rights Reserved
Configuring Applications
Struts Configuration File

 Use configuration elements in developing


Struts Application.
 These "static" configuration elements are:
– <form-bean>
– <action-mapping>

– <controller>

– <message-resources>
©2005 Accenture All Rights Reserved. 26
– <plug-in>
© Accenture 2005 All Rights Reserved
Configuring Applications
HRS struts-config.xml file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
<!-- ========== Data Source Configuration =============================== -->
<!--
<data-sources>
<data-source>
<set-property property="autoCommit"
value="false"/>
<set-property property="description"
value="Example Data Source Configuration"/>
<set-property property="driverClass"
value="org.postgresql.Driver"/>
<set-property property="maxCount"
value="4"/>
<set-property property="minCount"
value="2"/>
©2005 Accenture All Rights Reserved.
<set-property property="password" 27
value="mypassword"/>
© Accenture 2005 All Rights Reserved
Configuring Applications
HRS struts-config.xml file (cont.)
<!-- ========== Form Bean Definitions =================================== -->
<form-beans type="org.apache.struts.action.ActionFormBean">
<form-bean name="LoginForm" type="com.jds.architecture.authenticate.LoginForm">
</form-bean>
<form-bean name="EmployeeInfoForm"
type="com.jds.apps.hr.employee.form.EmployeeInfoForm">
</form-bean>
<form-bean name="EmployeeSearchForm"
type="com.jds.apps.hr.employee.form.EmployeeSearchForm">
</form-bean>
<form-bean name="ApproversSearchForm"
type="com.jds.apps.hr.approver.form.ApproversSearchForm">
</form-bean>
<form-bean name="BlankForm" type="com.jds.architecture.beans.BlankFormBean">
</form-bean>
….

<form-bean name="SearchProjectForm"
type="com.jds.apps.hr.project.form.SearchProjectForm">
</form-bean>
<form-bean name="ProjectForm" type="com.jds.apps.hr.project.form.ProjectForm">
</form-bean> ©2005 Accenture All Rights Reserved. 28
<form-bean
© Accenture name="EmpProjectListContainForm"
2005 All Rights Reserved
Configuring Applications
HRS struts-config.xml file (cont.)
<!-- ========== Action Mapping Definitions ============================== -->
<global-forwards>
<forward name="login" path="/login.do">
</forward>
<forward name="logoff" path="/logoff.do">
</forward>
<forward name="systemError" path="/error/errorPage.jsp">
</forward>
</global-forwards>

<action-mappings>

<!-- login action -->


<action path="/login"
name="LoginForm"
scope="request"
type="com.jds.architecture.authenticate.LoginAction"
validate="false"
input="login">
<forward name="HR" path="/hrDashboard.jsp"/>
<forward name="staff" ©2005 Accenture All Rights Reserved.
path="/staffDashboard.jsp"/> 29
<forward
© Accenture 2005 Allname="approver"
Rights Reserved path="/approverssearch.do?viewtype=init"/>
Configuring Applications
HRS struts-config.xml file (cont.)
<action path="/categoryview"
type="com.jds.apps.hr.skill.category.action.CategoryViewAction"
input="/category/search.jsp" name="CategoryForm" scope="request" validate="false">
<forward name="view" path="/category/categoryview.jsp">
</forward>
<forward name="editCategory" path="/category/categoryedit.jsp">
</forward>
</action>
<action path="/categorysearch"
type="com.jds.apps.hr.skill.category.action.CategorySearchAction"
name="SearchCategoryForm" scope="request" input="/category/search.jsp"
validate="false">
<forward name="success" path="/category/search.jsp">
</forward>
</action>
<action path="/categorysave"
type="com.jds.apps.hr.skill.category.action.CategorySaveAction" name="CategoryForm"
scope="request" validate="false" input="/category/category.jsp">
<forward name="success" path="/category/search.jsp">
</forward>
</action>
<action path="/categoryadd" ©2005 Accenture All Rights Reserved. 30
type="com.jds.apps.hr.skill.category.action.CategoryAddAction"
name="SearchCategoryForm"
© Accenture 2005 All Rights Reserved scope="request" validate="false">
Configuring Applications
HRS struts-config.xml file (cont.)

<!-- ========== Controller Configuration ================================ -->

<controller>
<!-- The "input" parameter on "action" elements is the name of a
local or global "forward" rather than a module-relative path -->
<set-property property="inputForward" value="true"/>
</controller>

<!-- ========== Message Resources Definitions =========================== -->

<!-- ========== Plug Ins Configuration ================================== -->


<message-resources parameter="com.jds.architecture.util.messages"/>

</struts-config>

©2005 Accenture All Rights Reserved. 31


© Accenture 2005 All Rights Reserved
Resources
 http://java.sun.com/webservices/docs/1.0/tutorial/d
 http://struts.apache.org/userGuide/building_model.
 http://struts.apache.org/userGuide/building_view.h
 http://struts.apache.org/userGuide/building_control
http://struts.apache.org/userGuide/building_contro
 http://jakarta.apache.org/struts/

©2005 Accenture All Rights Reserved. 32


© Accenture 2005 All Rights Reserved
Questions & Comments
.

©2005 Accenture All Rights Reserved. 33


© Accenture 2005 All Rights Reserved

Вам также может понравиться