slide1 l.
Skip this Video
Loading SlideShow in 5 Seconds..
Building Web Applications With The Struts Framework Session WE06 – 11/20/2002 – 10:00-11:00 Craig R. McClanahan Seni PowerPoint Presentation
Download Presentation
Building Web Applications With The Struts Framework Session WE06 – 11/20/2002 – 10:00-11:00 Craig R. McClanahan Seni

Loading in 2 Seconds...

play fullscreen
1 / 57

Building Web Applications With The Struts Framework Session WE06 – 11/20/2002 – 10:00-11:00 Craig R. McClanahan Seni - PowerPoint PPT Presentation

  • Uploaded on

Building Web Applications With The Struts Framework Session WE06 – 11/20/2002 – 10:00-11:00 Craig R. McClanahan Senior Staff Engineer Sun Microsystems, Inc. Session Outline. Web Applications Backgrounder The Model-View-Controller Architecture The Struts Framework

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Building Web Applications With The Struts Framework Session WE06 – 11/20/2002 – 10:00-11:00 Craig R. McClanahan Seni' - kacia

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Building Web Applications With The Struts Framework

Session WE06 – 11/20/2002 – 10:00-11:00

Craig R. McClanahan

Senior Staff Engineer

Sun Microsystems, Inc.

session outline
Session Outline
  • Web Applications Backgrounder
  • The Model-View-Controller Architecture
  • The Struts Framework
  • Building A Web Application With Struts
  • Resources
web applications backgrounder4
Web Applications Backgrounder
  • Web applications run over the HTTP protocol:
    • Request/response oriented
    • Stateless
  • Web applications use varied presentation (markup) languages, and talk to varied client hardware devices:
    • “Standard HTML” -- not!
    • Varying dynamic and JavaScript capabilities
    • Wireless devices vary in capabilities, language dialect, and input device support
simple solutions for simple problems
Simple Solutions ... for Simple Problems
  • For relatively simple applications, a simple architecture works fine
  • For each page in the user interface ...
    • Create a servlet, JSP page, or something similar
    • The page includes:
      • Logic to create the user interface
      • Logic to retrieve required information from the database
      • Logic to perform the appropriate business transaction
      • Logic to update the corresponding database information
    • And it's all mixed together in one source file
  • This works fine for a Guest Book app, but what about something bigger?
what about large scale applications
What About Large Scale Applications?
  • Disparate skill sets required:
    • Presentation Layer-- User interface design, visual appearance, interaction model
    • Application Layer – Functional business logic to perform required transactions
    • Persistence Layer – Databases, directory servers, messaging, Enterprise JavaBeansTM (EJBs)
    • Application Deployment – Networks, firewalls, public key infrastructures, load balancing, failover
  • We need a fundamental organizing principle:
    • The Model-View-Controller (MVC) architecture
the model view controller architecture
The Model-View-Controller Architecture
  • Divides the overall functionality of an application into three layers:
    • Model Layer – Contains the functional business logic of the application, as well as a representation of the persistently stored data backing the application
    • View Layer – Contains the user interface, including mechanisms to accept user input and render results
    • Controller Layer – Contains the logic that manages the flow of individual requests, dispatching to the appropriate business logic component
the model layer
The Model Layer
  • Functional business logic:
    • Should be modelled as JavaBeans or Session EJBs
    • Should be reusable in non-web environments
    • API exposes public methods for each logical unit of work (while hiding the details)
  • Persistent data storage:
    • Should manage permanent storage of application data
    • Typically shared across many applications
    • API should expose data retrieval and storage operations (while hiding the mechanisms)
the view layer
The View Layer
  • Creation of the user interface:
    • Typically in HTML or an XML-based dialect
    • Normally a combination of static and dynamic content
  • Actual content varies depending on:
    • Device or browser type
    • User preferences / personalization
    • Internationalization and localization requirements
    • Accessibility requirements
the controller layer
The Controller Layer
  • Incoming requests flow through a common path:
    • Received by common component
    • Standardized request pre-processing
    • Dispatch to request-specific model component (business logic)
    • Forward to business-logic-specified view component
    • Standardized request post-processing
  • Often called “Model 2 Design” in the JSP/Servlet community
  • In modern design pattern terminology, Struts implements the front controller pattern.
the struts framework model layer
The Struts Framework – Model Layer
  • Struts does not restrict implementation techniques for model layer
    • JDBC-accessed databases
    • Enterprise JavaBeans
    • O-R mapping tools
  • Optional JDBC connection pool available
  • Common design pattern:
    • Action acquires information from persistence tier
    • Exposes information as request/session attributes
    • View layer pulls data from attributes for display
the struts framework view layer
The Struts Framework – View Layer
  • Form Bean maintains state of form input fields across requests:
    • ActionForm – Standard JavaBean design pattern
    • DynaActionForm – Property names and types defined in Struts configuration file
  • In addition to properties, form beans define two standard methods:
    • reset() -- Reset form properties to initial state
    • validate() -- Perform field-level validations
  • Form bean properties are typically Strings
    • Allows redisplay of invalid input
the struts framework view layer16
The Struts Framework – View Layer
  • Internationalization Support enables locale-specific applications
    • Locale – Standard Java class representing a choice of language and/or country
    • MessageFormat – Standard Java class representing an individual message with replaceable parameters:
      • “{0} is not a valid credit rating”
    • MessageResources – Struts abstraction around sets of messages for supported locales
    • ActionErrors / ActionMessages – Struts collections of localized messages
the struts framework view layer17
The Struts Framework – View Layer
  • JSP Custom Tag Libraries – If you are using JSP pages for your presentation
    • struts-bean.tld – Fundamental bean manipulation and internationalization
    • struts-html.tld – “Smart” HTML elements
    • struts-logic.tld – Basic conditionals and iteration
    • struts-template.tld – Basic layout management
the struts framework view layer18
The Struts Framework – View Layer
  • Standard tag libraries added in Struts 1.1:
    • struts-nested.tld -- “Nested” variants of standard tags that resolve relative references against beans
    • struts-tiles.tld – Full features layout management library
  • Contributed libraries added in Struts 1.1:
    • struts-xxx-el.tld – Versions of standard Struts tag libraries that support the expression language syntax of JSP Standard Tag Library
the struts framework view layer19
The Struts Framework – View Layer
  • Validation Framework
    • No-code-required field level validations
    • Configured in an XML document included in the web application
    • Optionally generates client side JavaScript to enforce validation rules
    • Extensible architecture
the struts framework controller layer
The Struts Framework – Controller Layer
  • ActionServlet – Standard implementation of controller
  • At application startup, reads configuration file and initializes resources
    • [Struts 1.1] PlugIn – General start/stop hook
  • On each request, implements the standard Struts request processing lifecycle (in Struts 1.1, implemented in RequestProcessor)
  • Specialization / customization via subclassing
  • [Struts 1.1] Sub-application modules support
the struts framework controller layer21
The Struts Framework – Controller Layer
  • Action – Standard base class for business logic components and adapters:
    • Mapped to logical names by request processor
    • Single instance per application (must be thread safe)
    • Instantiated as needed, like servlets
  • Implements the “Command Pattern”
    • execute() -- Invoked for each request
    • Can (but typically does not) create response content directly
    • Typically returns ActionForward to select resource to prepare response
the struts framework controller layer22
The Struts Framework – Controller Layer
  • Standard Request Processing Lifecycle 1:
    • processLocale() -- Record user's locale preference (if not already present)
    • processPreprocess() -- general purpose pre-processing hook
    • processMapping() -- select Action to be utilized
    • processRoles() -- perform security role-based restrictions on action execution
    • processActionForm() -- Create or acquire an appropriate ActionForm instance
the struts framework controller layer23
The Struts Framework – Controller Layer
  • Standard Request Processing Lifecycle 2:
    • processPopulate() -- Copy the request parameters into the form bean properties
    • processValidate() -- Call form bean's validate() method
    • processActionCreate() -- Create or acquire an appropriate Action instance
    • processActionPerform() -- Call action's execute() method
    • processActionForward() -- Process returned ActionForward instance (if any)
the struts framework controller layer24
The Struts Framework – Controller Layer
  • XML Configuration Document (/WEB-INF/struts-config.xml)
    • Standard place to configure all aspects of the application's behavior
    • DTD included for optional (but recommended) validation
    • Logical-to-physical mappings for Actions, ActionForms, and ActionForwards
    • General configuration settings
  • [Struts 1.1] Configuration Document per module if more than one
the struts framework commons libraries
The Struts Framework – Commons Libraries
  • Non-Struts Specific Logic Factored Out:
    • commons-beanutils – Generic bean property manipulation
    • commons-collections – Extensions to standard Java2 collections classes
    • commons-dbcp – Optional JDBC connection pool
    • commons-digester – XML parsing for configuration files
    • commons-fileupload – Support library for HTML file uploads
the struts framework commons libraries26
The Struts Framework – Commons Libraries
  • Non-Struts Specific Logic Factored Out:
    • commons-logging – Application logging wrapper
    • commons-pool – Object pooling library
    • commons-resources – Message resources support library
    • Commons-validator – Field validation framework
building web applications with struts28
Building Web Applications With Struts
  • Now that we understand the architecture of Struts, let's look at parts of an example app that is built with it
  • Struts includes a canonical example that is useful in determining whether you have installed things correctly
    • struts-example.war
  • Application models (part of) an email portal site that lets you maintain multiple subscriptions
sample application model layer persistence tier
Sample Application – Model Layer (Persistence Tier)
  • Modelled via a Data Access Object (DAO)
    • org.apache.struts.webapp.example.UserDatabase

public interface UserDatabase {

public User createUser(String username);

public void close() throws Exception;

public User findUser(String username);

public User[] findUsers();

public void open() throws Exception;

public void removeUser(User user);

public void save() throws Exception;


sample application model layer persistence tier30
Sample Application – Model Layer (Persistence Tier)
  • Default implementation based on loading an XML document into memory:
    • o.a.s.e.memory.MemoryUserDatabase
  • JDBC-based (or LDAP-based) implementation is easy to imagine, and would be transparent to the business logic
  • Implementation selection implemented via a PlugIn ... see configuration file example later
sample application model layer business logic
Sample Application – Model Layer (Business Logic)
  • Two common Struts design patterns illustrated
  • View --> View --> Action
    • Welcome Page has link to logon page:
      • <html:link page=”/logon.jsp”>...</html:link>
    • Logon page instantiates LogonForm bean
    • Form submit goes to “/logon” action
  • View --> Action --> View --> Action
    • Setup action “/editRegistration?action=Edit” pulls data from “database” and populates form bean
    • Registration page “/registration.jsp” displays current data
    • Form submit goes to “/saveRegistration” action
sample application view layer logon jsp
Sample Application – View Layer (logon.jsp)

<%@ page contentType=”text/html;charset=”UTF-8” %>

<%@ taglib uri=”/WEB-INF/struts-bean.tld”

prefix=”bean” %>

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

prefix=”html” %>

<html:html locale=”true”>



<bean:message key=”logon.title”/>




sample application view layer logon jsp33
Sample Application – View Layer (logon.jsp)

<body bgcolor=”white”>


<html:form action=”/logon” focus=”username”

onsubmit=”return validateLogonForm(this);”>

<table border=”0” width=”100%”>


<th align=”right”> <bean:message key=”prompt.username”/>


<td align=”left”>

<html:text property=”username” size=”16”/>



sample application view layer logon jsp34
Sample Application – View Layer (logon.jsp)


<th align=”right”> <bean:message key=”prompt.password”/>


<td align=”left”>

<html:password property=”password”





<html:javascript formName=”logonForm”



<script language=”Javascript” .../>


sample application controller layer
Sample Application – Controller Layer
  • No application logic required – Struts does everything for you :-)
  • Controller functionality is configured via XML-based files:
    • struts-config.xml – Struts controller configuration
    • validation.xml – Validator framework configuration
    • web.xml – Web application configuration
sample application struts configuration struts config xml
Sample Application – Struts Configuration (struts-config.xml)




<form-bean name=”logonForm”


<form-property name=”username”


<form-property name=”password”



<form-bean name=”registrationForm”




sample application struts configuration struts config xml37
Sample Application – Struts Configuration (struts-config.xml)


<forward name=”logoff” path=”/”/>

<forward name=”logon” path=”/”/>

<forward name=”registration”


<forward name=”success”



sample application struts configuration struts config xml38
Sample Application – Struts Configuration (struts-config.xml)


<action path=”/editRegistration”



scope=”request” validate=”false”>

<forward name=”success”



<action path=”/saveRegistration”



scope=”request” validate=”true”


sample application struts configuration struts config xml39
Sample Application – Struts Configuration (struts-config.xml)

<action path=”/logon”








<set-property property=”inputForward”





sample application struts configuration struts config xml40
Sample Application – Struts Configuration (struts-config.xml)

<plug-in className=”org.apache.struts.webapp.example.memory.MemoryDatabasePlugIn”>

<set-property property=”pathname”



<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>

<set-property property=”pathnames”





sample application struts configuration validation xml
Sample Application – Struts Configuration (validation.xml)



<form name=”logonForm”>

<field property=”username”


<arg0 key=”prompt.username”/>

<arg1 key=”${var:minlength}”












sample application webapp configuration web xml
Sample Application – Webapp Configuration (web.xml)













<load-on-startup> 1 </load-on-startup>


sample application webapp configuration web xml43
Sample Application – Webapp Configuration (web.xml)



<url-pattern> *.do </url-pattern>




struts 1 1 release
Struts 1.1 Release
  • When? “Real Soon Now”
  • What new features?
    • Apache Commons Libraries
    • DynaActionForm
    • Declarative Exception Handling
    • Nested Tag Library
    • PlugIn API
    • Sub-Application Module Support
    • (Contributed) STRUTS-EL Tag Libraries
struts and jstl
Struts and JSTL
  • JSP Standard Tag Library (JSTL) 1.0:
    • Expression language (“${customer.address[“mailing”].city”)
    • General purpose actions (out, set, remove, catch)
    • Conditional actions (if, choose, when, otherwise)
    • Iterator actions (forEach, forTokens)
    • URL actions (import, url, redirect, param)
    • Internationalization actions (message, setLocale, bundle, setBundle, message, param, requestEncoding)
    • Formatting actions (timeZone, setTimeZone, formatNumber, parseNumber, formatDate, parseDate)
struts and jstl47
Struts and JSTL
  • JSP Standard Tag Library (JSTL) 1.0, continued:
    • SQL actions (not relevant in an MVC framework environment)
    • XML core actions (parse, out, set)
    • XML flow control actions (if, choose, when, otherwise, forEach)
    • XML transform actions (transform, param)
  • The struts-xxx-el libraries are a bridge for Struts developers who want to leverage JSTL tags, and expression language syntax, now
struts and jsf
Struts and JSF
  • JavaServer Faces (currently under development in JSR-127)
  • Goals:
    • Standard GUI component framework for web applications
    • RenderKits for different rendering environments (browser vs. wireless device, different locales, etc.)
  • Struts will provide an integration library:
    • Requires changes to view layer and struts-config.xml file only!
    • Plugs in to RequestProcessor APIs
this presentation online
This Presentation Online
  • StarOffice 6.0:
  • Powerpoint:
internet technologies
Internet Technologies
  • Hypertext Markup Language (HTML) 4.01:
  • Hypertext Transfer Protocol (HTTP) 1.1:
  • Uniform Resource Identifiers (URI):
model layer standard java apis
Model Layer – Standard Java APIs
  • JavaBeans:
  • Java Database Connectivity (JDBC):
  • Java Data Objects:
  • Java Naming and Directory Interface:
  • Enterprise JavaBeans (EJB):
model layer persistence frameworks
Model Layer – Persistence Frameworks
  • Castor:
  • Java Data Objects:
  • Object/Relational Bridge:
  • Torque:
view layer standard java apis
View Layer – Standard Java APIs
  • Servlets:
  • JavaServer Pages (JSP):
  • JSP Standard Tag Library (JSTL):
  • JavaServer Faces:
struts resources
Struts Resources
  • The Struts and Commons Web Sites:
  • Recent Books About Struts:
    • Cavaness, Chuck; Programming Jakarta Struts; O'Reilly
    • Goodwill, James; Mastering Jakarta Struts; John Wiley
    • Husted, Ted; Java Web Development With Struts; Manning
    • Spielman, Sue; The Struts Framework: Practical Guide for Programmers; Morgan Kaufman
    • Turner, James; Struts Kick Start; Sams
design patterns resources
Design Patterns Resources
  • The Java Blueprints Web Site:
  • Design Patterns Books:
    • Gamma, Erich (et. al.); Design Patterns: Elements of Reusable Object-Oriented Software; Addison-Wesley
    • Alur, Deepak (et. al.); Core J2EE Patterns: Best Practices and Design Strategies; Prentice Hall