0% found this document useful (0 votes)
266 views190 pages

Web Tier Programming

Web tier programming technologies and best practices presented by Carol McDonald, staff engineer / Technology Evangelist at Sun microsystems.

Uploaded by

api-3772730
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
266 views190 pages

Web Tier Programming

Web tier programming technologies and best practices presented by Carol McDonald, staff engineer / Technology Evangelist at Sun microsystems.

Uploaded by

api-3772730
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 190




In 

 

Depth Session:
 

Web Tier Programming


Technologies and Best Practices
Carol McDonald
Staff Engineer/Technology Evangelist
[email protected]

Sun™ Tech Days



 

 

Speaker’s 

Qualifications 

 Carol McDonald
 Technology Evangelist at Sun Microsystems
 Develop and deliver Code Camps for
J2EE, Java™ performance tuning, J2ME and
web services technologies for Sun
Microsystems
 Speak around the world concerning
Sun™ technologies
 Tri-lingual: English, French, German

 

 

Presentation 

Agenda 

 Web tier programming overview


 Frameworks
 Struts
 JavaServer™ Faces
 Frameworks comparison/relationship
 JSP/Servlets best practices
 Summary and resources

 

 
 
 

 

 



Web Tier
  Programming


 
 
 and Web 

Services
Servlets JDBC / WebRowSet
Browser on JSP
…desktop JSTL
…cell phone JSF DB

Portlets
Presentation
Audio on phone Content
Channels
JAX-RPC
SVG on desktop
J2EE

Client WS using EJBs


… J2SE
… Java™ Web Start
…J2SE
WS WS
… dot.NET
JAX-RPC

JAX-RPC

 

 

Server-Side 
 Technology
Java™ 

 Servlets
 Early JSP™
 Struts and MVC
 Sun™ One Application Framework
 JSTL specification 1.0, JSP™
specification 2.0
 <c:forEach var="item"
values="${cart}">
 JavaServer™ Faces (JSF) specification
1.0

 
How

 

They 

Fit Together 

JSF Struts
JSTL
S1AF
JSP™
java bean, expression
lang.,custom tag lib

Servlet
session tracking, filtering, listener
Sun ONE
  Application


 
 
 Framework




(JATO)
 A J2EE application framework
 Primarily focused on Web tier
 Leverage Sun Java Center J2EE Patterns
 Provide a robust, scalable application
foundation
 Reusable components
 Full-featured event model and high-level tag library
 Leveraged through Sun ONE Studio Wizard-
based visual interfaces

Sun ONE
  Application


 
 
 Framework 

(Sun ONE Studio 5)



 
How

 

They 

Fit Together 

JSF Struts
JSTL
S1AF
JSP™
java bean, expression
lang.,custom tag lib

Servlet
session tracking, filtering, listener

 

 
 
 

  


 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo

 

 

Model 

View Controller 

 Separate control
 From model data
Request Servlet  From presentation of view
Controller

Forward Business
Response Event Event
Model
Business
JSP Bean
View Model
Data

Client Web EJB Tier

MVC Pattern

 

 

Jakarta Struts 
 

 Struts is an open source framework


developed by the Apache Jakarta project
http://jakarta.apache.org/struts/
 Struts 1.1 is in final (Servlet 2.2/JSP 1.1)
 Struts 2.0 is in plan (Servlet 2.4/JSP 2.0, JSTL,
JSF)
 Struts Framework:
 Provides JSP/Servlet developers with a MVC
skeleton which you can extend
 Configure navigation and objects using XML
configuration files

 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code
 
 

 

 
 
 

Form Bean Action


View 1 3
1
2
4
Action
ActionServlet
Model
(Controller)
5
Action
View 2

Struts-config.xml
........
Action
........
........

 

 

Struts: MVC Pattern
 Implemented 

Controller

Request Action
Action
Servlet
Mapping Action Model
(xml)

Client
Uses

Response
Action Action
JSP View
Forward Form

Model Data
View

 

 

Struts Components 
 and Feature 

 The View - a JSP or HTML page


 The Model - a Java™ object
( called an ActionForm)
 Central controller – ActionServlet
 URI to Action Mapping(Action class)
located in struts-config.xml file
 Action classes
 Adaptors between business
layer and web tier
 Validation, internationalization, custom
tags for creating HTML

 

 
 

Model-View-Controller (MVC) 

 Model – The persistent data


(typically in a database) and
business logic functionality
 View – The user interface, JSP
 Controller – dispatch requests to the
corresponding business logic, and
trigger the display of the appropriate
next page

 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo
  
 

 
 






 

 

Example: Account 

Services Form 



 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code

 

 
 

Controller 

 The controller is the switch board of MVC


 Directs the user to the appropriate views by
providing the view with the correct model
 The task of directing users to appropriate
views through “mapping”

 

 

Controller: 

ActionServlet 

 The controller is the switch board of MVC


 Struts framework provides a base object
called org.apache.struts.action.ActionServlet
 Controller:
 Receives HTTP request
 Populates a form bean with values from
request parameters
 Calls validate() method on the form bean,
and redisplays the previous page if there
were any errors
 Dispatches to an Action to process the
validated form bean

 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code

 

 

Action Form 
 

 By extending the Struts ActionForm class,


Struts will:
 Ensure your form bean is created
 Update your form bean with input values
 Call validate() on form bean
 Pass the form bean to your action class

 

 
 

Example 

ActionForm
Binding by name JSP
Tag Attribute and the
Address
JavaBean Property-
Name CustomerForm
name
address
validate()
<html:form action="updateCustomer">
<TABLE border="0">
<TBODY>
<TR>
<TD>Name</TD> Binding between the
<TD><html:text property="name" /></TD> Action
</TR>
...
updateCustomer
</TBODY> and the class
</TABLE> CustomerForm is in
<html:submit value="ok" />
</html:form> ViewCustomer.jsp struts-config.xml

 

 
 

Struts-config.xml: ActionMapping 

1 <form-beans>
2 <form-bean name="customerForm"
3 type="packagex.CustomerForm"/>
4 </form-beans>
5
6 <action-mappings>
7 <action path="/updateCustomer"
8 type="UpdateCustomerAction"
9 name="customerForm"
10 scope="request"
11 input="/logon.jsp">
12 </action>
13 <forward name="success" path="/ViewCustomer.jsp"/>
14 <forward name="error" path="/error.jsp" />
15 </action-mappings>

 

 

Model: ActionForm 
 

01 import org.apache.struts.action.ActionForm;
02 import org.apache.struts.action.ActionMapping;
03 import org.apache.struts.upload.FormFile;
04 public class CustomerForm extends ActionForm {
05 protected String firstName;
06 protected String lastName;
07 public void setFirstName(String firstName) {
08 this.firstName = firstName;
09 }
10 public void setLastName(String lastName) { ...}
11 //There would also be getters for these properties
12 }

 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code

 is

 

What an Action 

Class? 

 Java class that does the “work” of your


application
 Handles request
 Calls business objects (Model)
 Better to separate business logic into
separate Java Beans or EJBs
 Action class calls Model components

 

 

Struts Action Class
 

 User writes their Action class


which extends Struts Action class
 Delegates to model objects
 Action returns logical identifier of resource
to continue or render the response
 Typically a JSP™ page

 Controller passes control to the


selected resource

 

 

Action 

Class Sample 

1: public class CustomerAction extends Action {


2:
3: public ActionForward execute( ActionMapping mapping,
4: ActionForm form,
5: HttpServletRequest request,
6: HttpServletResponse response)
7: {
8: CustomerForm myForm = (CustomerForm) form;
9: String userId = myForm.getUserId();
10: try {
11: bdelegate.updateCustomer(userId, myForm) ;
12: return mapping.findForward("success");
13: } catch (Exception e) {
14: return mapping.findForward("error");
15: }
16: }
17: }

 

 
 

Struts-config.xml: ActionMapping 

1 <action-mappings>
2 <action path="/updateCustomer"
3 type="CustomerAction"
4 name="customerForm"
5 scope="request"
6 input="/logon.jsp">
7 </action>
8 <forward name="success" path="/ViewCustomer.jsp"/>
9 <forward name="error" path="/error.jsp" />
10 </action-mappings>

 

 

Struts Flow 
 

    

Server configured to pass *.do extensions to


org.apache.struts.action.ActionServlet via a
web.xml configuration file

ActionServlet object inspects the URI and tries to match it


against an ActionMapping located in the struts-config.xml file

Instance of appropriate Action class is found and it’s execute()


is called. Single instance per Action class, so must be threadsafe.

Action object handles the request and returns actionForward.


View is identified by ActionForward object.

 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo

 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code

 

 

Model Components 
 

 Model divided into concepts


 Persistent Domain Data
 Entity EJBs

 POJO's with JDBC

 JDO

 Services, Business rules, processes that


can change business data
 Session EJBs
 Java Beans

 

 
 

Model 

 Defining a model in Struts is simple


 Create a Java™ class and provide some function
 Model classes should be coded independent
of the Struts framework
 Maximum code reusability by other applications

 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo

 

 
 

Architecture 

http
http
request struts-config.xml response

ActionForm TagLibs
Action
ActionServlet Action JSP
Action JSP
Action
Controller View

ActionForm
ActionForm STRUTS
ActionForm Model
Your code

 

 
 

View 

 ActionForward object tells JSP page


to dispatch to
 The view in Struts is represented by JSP
 JSP can use ActionForm bean to get output
Model data to display
 Struts contains a series of tag libraries
 Facilitates communication between HTML
designers and developers
 Facilitates dynamic Web content

 Example
View:

 
 
 

01 <%@ page language="java" %>


02 <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
03 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
04 <html:html locale="true">
5 ...
6 <html:form action="/updateCustomer.do" >
07 <html:text property=”username” .../>
...
<html:text property="street" />
9
10 <html:submit property="submit" value="Submit"/>
11 ...
12 </html:form>
13 ...
14 </html:html>

 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo

 

 

Develop Struts 

Application in 

Sun Java Studio

 Struts console plug-in for Sun Java Studio


 http://www.jamesholmes.com/struts/console
 FREE standalone Java™ Swing application
for developing and managing Struts-based
applications

 
Sun

 

Java 

Studio(Struts Console) 




Steps to


 
 

Develop/Deploy
Struts 

Application in Sun Java Studio

1. Copy lib/struts*.tld into the WEB-INF


directory of your web application
2. Modify web.xml
3. Copy lib/struts.jar into the WEB-INF/lib
of your web application
4. Deploy .war on Sun Java System Application
Server

 

 
Steps
Development 
 

1.Create development directory structure


2.Write web.xml
3.Write struts-config.xml
4.Write ActionForm classes
5.Write Action classes
6.Create ApplicationResource.properties
7.Write JSP pages
8.Write ant build script
9.Build, deploy, and test the application

 

 
 
 



 

 
 
 



 web.xml
Write

 
 
 

 Same structure as any other Web


application
 Servlet definition and mapping of ActionServlet
 There are several Struts specific <init-
param> elements
 Struts tag libraries also need to be
defined

 

 

Modify web.xml: 
 

Servlet and url-pattern



  


       
 
 
 
 
   

 
  

   
 
 
 
 !

  " !

 


 

  


  #!
 

 

 

 

Modify web.xml: 
 

Tag Lib Declaration


 $
 $
 

$ ! $

 $
  

$ ! $
 
 $
 $
 $
 

 ! $


 $

 $
 

! $


 $
 

  ! $



 

 

3. Write 

struts-config.xml 

 <form-bean> elements for input forms


 <action-mappings> element with <action>
elements for Action's
 <forward> element within <action> for view
selection logic

 

 
 

Struts-config.xml: <form-beans> 

" %   &'"('  ! &')


**+,
"' %
-
. /0)1234 
  4561
7 '
  8   !  020  1   ""'
+ '9: ;    !!
 <"<"!!'
=
> 
 
*
, /

&&&&&&&&&&   0   &&&&&&&&&&&&&&&&&


"( 
$ 
""
"- 
$ &'  '
". ?&' ;  1  '
"7
"+ 
$ 

 

 
 

Struts-config.xml: <action-mappings> 

"
- /

&&&&&&&&&&  @   0   &&&&&&&&&&&&


.  
 
7
+    &'! 1 '
= ?&'5! 1  '
> &'  '
*  &'5! 1 :'
, &'A'
"(  ! &''
"" 8 ! &''  &'B81 :'
"- 8 ! &' '  &':'
".  
"7
"+  
 
"=
"> 
 

Write
4. 

 

ActionForm
 classes 

 Extend org.apache.struts.action.ActionForm
class
 Decide set of properties that reflect the
input form
 Write getter and setter methods for each
property
 Write validate() method if input validation
is desired

 

 

Model: ActionForm 
 

01 import org.apache.struts.action.ActionForm;
02 import org.apache.struts.action.ActionMapping;
03 import org.apache.struts.upload.FormFile;
04 public class CustomerForm extends ActionForm {
05 protected String firstName;
06 protected String lastName;
07 public void setFirstName(String firstName) {
08 this.firstName = firstName;
09 }
10 public void setLastName(String lastName) { ...}
11 //There would also be getters for these properties
12 }

 

 

5. Write Action 

Classes 

 Extend org.apache.struts.action.Action class


 Handle the request
 Decide what kind of server-side objects (EJB, JDO,
etc.) can be invoked
 Based on the outcome, select the next
view

 

 

Action 

Class Sample 

1: public class CustomerAction extends Action {


2:
3: public ActionForward execute( ActionMapping mapping,
4: ActionForm form,
5: HttpServletRequest request,
6: HttpServletResponse response)
7: {
8: CustomerForm myForm = (CustomerForm) form;
9: String userId = myForm.getUserId();
10: try {
11: bdelegate.updateCustomer(userId, myForm) ;
12: return mapping.findForward("success");
13: } catch (Exception e) {
14: return mapping.findForward("error");
15: }
16: }
17: }

 
Step 6:

 

Create 
 

ApplicationResource.properties

 Create resource file for default locale


 Create resource files for other locales


Step 
7:

 

Write JSP 

pages 

 Write one JSP page for each view


 Use Struts tags for
 Handing HTML input forms
 Writing out messages

 Example
View:

 
 
 

01 <%@ page language="java" %>


02 <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
03 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
04 <html:html locale="true">
5 ...
6 <html:form action="/updateCustomer.do" >
07 <html:text property=”username” .../>
...
<html:text property="street" />
9
10 <html:submit property="submit" value="Submit"/>
11 ...
12 </html:form>
13 ...
14 </html:html>


Step 8:


 

Write Ant 

BuildScript 




Step 9:


 
 

Build, Deploy, 

and Test Application



 

 

Accessing Web 

Application 



 

 
 

Agenda 

 Struts
 Architecture
 Model
 View
 Controller
 Development Steps
 Struts and J2EE design pattern demo

 

 

Example: Account 

Services Form 



 

 

Struts and Core

J2EE Patterns 

Controller Model
Service
Request Action Interface
Action
Mapping Action
Servlet
(xml)
Business Business
Delegate Service
Client
Uses

Service
Locator
Response
Action Action
JSP View
Forward Form

View View Helper



 

 

Struts and Core

J2EE Patterns 

Front Controller Business Delegate


   ActionServlet
 
        
Action           

 

      
             
! "#  
   $  

% ! "#

   
! "#  

 
             
' (  "#               

  
' (  ( ) !"#               

DataTransfer Object DataTransfer Object


 
 

 
 






 

 

Struts: Importance 
and Limitations 

 Popularity of Struts led to:


 Increased use of Tag Libs
 Wide adoption of MVC
 Struts tag libraries have limitations:
 Lack of flexibility
 No component model
 Struts paved the way for JSTL and JSF

 

 
 
 

  
  
 

 

 
 

Agenda 

 JavaServer™ Faces
 Architecture overview
 Key concepts
 Development steps
 Car demo

 Is
What

 
 

JavaServer™ Faces 

Technology?

A server-side user interface component


framework for JavaTM technology-based
web applications.


JSF Architecture


 
 
 

Server

Request
UI
Client (events)

Response
(markup)

 
JSF

 
 

Architecture 

Server
JSF Page

  HTML

  HTML
RenderKit

Front App
ctrl JSF Page Backend

WML

  RenderKit

WML

 

 

JavaServer 

Faces 

 Emerging Java™ technology (JSR 127)


 Designed to provide richer UI
 Server-side object model for client-side UI
 Server-side handling of simple client-side
events
Model
Page Form Object

c1 A c1 A A

c2 B c2 B B

c3 C c3 C C

Client Server

 

 

Motivation 

for JSF 

 Standard web framework


 Accessible to Corporate Developers
 Tool friendly
 Client device/protocol neutral
 Usable with/without JSP
 Usable with/without HTML-based
clients
 Scalable

 

 
to
Relationship 

Existing APIs 

JSF App
JSF App
JSF Tags
JSP
(1.2 or later) JSF API

Servlets (2.3 or later)



 

 

Roles 

and JavaServer™ Faces 

Developer Implementor

Page Tool
Author Provider

Application Component JSF


Developer Writer Implementor

 

 
 

Agenda 

 JavaServer™ Faces
 Architecture overview
 Key concepts
 Development steps
 Car demo

 

 

Important Basic

Capabilities 

 Extensible UI component model


 Flexible rendering model
 Event handling model
 Validation framework
 Basic page navigation support
 Internationalization
 Easy to use with tools

 

 
 
 
Components of JSF

 Special servlet called FacesServlet which


is responsible for all JSF requests and
responses
 JSF application configuration file
 faces-config.xml
 A set of JSF specific APIs
 A set of JSF specific tag libraries

 

 
 
 
JSF Extending Servlet/JSP

  




  

 
 


 







     
   

   

 

 
 
 
The web.xml Configuration File




















! "# 
$ 


!
 


       
 
 
    

 
  
      


%
! &  
%
!
  
     
 
$
 
 
    

! 
  
 ' ! 
 
  
$

 

 
 
 

JSF Application Packaging


  

   



 

 
 

Agenda 

 JavaServer™ Faces
 Architecture overview
 Key concepts
 Development steps
 Car demo

  in
Steps

 
 

Development Process 

1.Develop model objects (managed


beans) which hold the data
2.Add managed bean declarations to
Application Configuration File
faces-config.xml
3.Create Pages using UI component and
core tags
4.Define Page Navigation in
faces-config.xml
5.Configure web.xml

 Page
Login

 
 
 

 When 'Login' is pressed, the app will validate the user's


name against the password
 When 'Create' is pressed, the app will create a new user
with the login name and password


1. 

 

Develop 
Objects:
Model 

Managed Bean
 The model (M) in MVC
 A regular JavaBeans with get set methods for all
attributes or properties
 May contain action methods and
event handlers
 Use to hold data from a UI (JSP)
 Creation and lifetime is managed
by JSF runtime
 Application, session, request, none
 JSF keeps the bean’s data in sync with the UI

 

 
 

Login.jsp 

(&          !


()         !
((
(* 
!
"# +) +,! ! 
!-./0$#!%1
 
12.
 +)
(3 +, %-4$ 4  
-4$ 4
(5
(6 7 
,
(8 +, ! %-4! 
4
(9 
!:-4$ #
! 
4 1
&(
&& ;
< %,
&) +, !  %-4
< %4
&* 
!:-4$ #

< %4 1
&= 
&3  +,
&5 
!

 

 
 
 
LoginFormBean.java

1: Public class LoginFormBean.java {


2: // member declaration
3: public LoginFormBean() { }
4:
5: public void setUserName(String n) {
6: userName = n;
7: }
8: public String getUserName() {
9: return (userName);
10: }
11: public void setPassword(String p) {
12: password = p;
13: }
14: public String getPassword() {
15: return (password);
16: }
17: ...

 

 

Declare JavaBean 

as Managed Bean 

 Add managed-bean tag to faces-config.xml


 Specify a logical name and maps the
logical name to the JavaBean class


2. 

 

Managed Bean 

Declaration 

Faces-config.xml:

(&

$%1

() 

$% $ 
(* %  &
(= 

$%1


(3 

$% $
(5 ' %  &
(6 

$%1


(8 

$% $  
(9 ( 
&( 

$%1
 
&&

$%1


 

 

Managed Bean

Creation Facility 

For Value reference expressions that included


“loginFormBean”
 The server will attempt to find a bean under
this name in some scope
 If there is no such bean:
 Instantiate a bean of the specified type
 Store bean instance in specified scope
 Creation rules configured in a faces-
config.xml document

 

 

Binding 

UI to Managed Bean 


+, ! %-4! 
4

!:-4%  & ) 4

 $ 


$%1
 %  &


$%1

 !1 
 %  &
%  & 


$%1

 !1 % * ) ?@ 0


$%1

 !1  $ * ) ?@ 0
>
%  &


$%1




3.

 

Create JSF 

Pages 

 Must include JSF tag library


 HTML and core tags
 All JSF tags must be enclosed between a
set of 
! tags
 Use JSF form and form component tags
 <h:input_text> not <input type=”text”>
 <h:command_button> not <input type=”submit”>
 May include validators and event listeners
on any form components

 

 

3. Create 

JSF Pages 

Login.jsp
(&          !
()         !
((
(* 
!
"# +) +,! ! 
!-./0$#!%1
 
12.
 +)
((
(3 +, %-4$ 4  
-4$ 4
(5
(6 7 
,
(8 +, ! %-4! 
4
(9 
!:-4$ #
! 
4 1
&(
&& ;
< %,
&) +, !  %-4
< %4
&* 
!:-4$ #

< %4 1
&= 
&3  +,

Components
UI 

 
 
 


 A BA +C#A
:
% #!A   A
#!A
1A  %A
B A 


Components
UI 

 
 
 

 Standard UIComponent class


 JavaBean™ base class with standard behavior

 UICommands: Commands cause the page to


be “submitted” for processing
 Button and URL links are commands
 UICommands cause action events
 UIInput Components:
 input widgets: Text field, radio buttons, pull down list
 Cause value change events
 Layout components for laying out a page
(UIPanel) -List, grid

 

 
 

Components 

 UIComponent/UIComponentBase
 JavaBean™ base class with standard behavior

 Standard UIComponent subclasses


 UICommand, UIForm, UIGraphic, UIInput
 UIOutput, UIPanel, UIParameter
 UISelectBoolean, UISelectMany, UISelectOne

 

 

Sample JSF Page
TM

 

1: <%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>


2: <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>
3: Standard UIComponent subclasses
4:
5: <f:view>
6: <h:form formName=”logonForm”>
7: <h:panel_grid columns=”2”>
8: <h:output_text value=”Username:”/>
9: <h:input_text id=”username” length=”16”
10: valueRef=”loginFormBean.userName”/>
11:
12: <h:command_button type=”submit”
13: label=”Log On”
14: action=”success”/>
15: <h:command_button type=”reset”
16: label=”Reset”/>
17: </h:panel_grid>
18: </h:form>
19: </f:view>


TwoTag


 
 

Libraries 

 html_basic
 Defines tags for representing common HTML user
interface components
 jsf_core
 Defines other JSF related tags
 Independent of any rendering technology
 JSP page needs to declare them
 <%@ taglib uri="http://java.sun.com/jsf/html/"
prefix="h" %>
 <%@ taglib uri="http://java.sun.com/jsf/core/"
prefix="f" %>

 

 

Navigation 

Model 

 Navigation rules configured in faces-


config.xml document
 Default NavigationHandler bases decision
on:
 Which component tree (i.e., page) is currently being
processed?
 Which application Action was invoked?
 What outcome was returned by the Action?

Login Screen
 

 
 
Navigation 

Example
to-view

from-outcome 

from-view 






 





+ 





4. 

 

Define Page

Navigation Rules: 

Faces-config.xml
<h:command_button type=”submit” label=”Log On”
action=”success”/>
1: <navigation-rule>
1: <from-view-id>/login.jsp</from-tree-id>
2: <navigation-case>
3: <from-outcome>success</from-outcome>
4: <to-view-id>/menu.jsp</to-tree-id>
5: </navigation-case>
6: <navigation-case>
7: <from-outcome>error</from-outcome>
8: <to-view-id>/error.jsp</to-tree-id>
9: </navigation-case>
10: . . .
11: </navigation-rule>
12:
13:

 

 

Request 

Processing Lifecycle 

Response Response
Complete Complete

Faces
Request Reconstitute Apply
Component Request Process Process Process
Tree Values Events Validations Events

Render Response
Response Response
Complete Complete

Faces
Response Render Process Invoke Process Update
Responder Events Application Events Model
Values

Conversion Errors /
Render Response
Validation / Conversion
Errors / Render Response


JSF

 
 

Lifecycle 

 A JSF page is represented by a tree of UI


components, called a view
 When a client makes a request for the page, the
lifecycle starts:
 Reconstitute Component Tree

 

 
 
 
Reconstitute Component Tree

 Build request component tree or Restore


state of the current request tree
 From information embedded in the request
 From information saved in the session
 Save tree in Faces context

  !

"! #     



 

 

Request 
 Lifecycle
Processing 

Response Response
Complete Complete

Faces
Request Reconstitute Apply
Component Request Process Process Process
Tree Values Events Validations Events

Render Response
Response Response
Complete Complete

Faces
Response Render Process Invoke Process Update
Responder Events Application Events Model
Values

Conversion Errors /
Render Response
Validation / Conversion
Errors / Render Response

 

 

Request 
 Lifecycle
Processing 

 Apply request values – Convert request


parameters into component data values
 Process validations – Perform all
requested component validations

 

 

Converters and 

Validators 

 Converters— In webapps, everything


comes in as a String
 Standard Converters for native types Integer...
 Plug-in for conversions:
 Input: String to Object
 Output: Object to String

 Example 2 ways to use Standard converters:


in code
Integer age = 0;
public void setAge(Integer age) {this.age = age;}
or in JSP
<h:input_text value="#{LoginBean.Age}"
converter="javax.faces.convert.IntegerConverter />

 

 

Converters: 
 error message
example 



 

 
 
(located
Faces-config.xml in web- 

inf): Custom Converter


1:
2: <h:input_text id="ccno" size="16"
3: converter="#{creditCardConverter}"
required="true">
4: </h:input_text>
5: <h:messages for="ccno"/>

1:
2: <!-- Converter -->
3: <converter>
4: <description>CreditCard Converter</description>
5: <converter-id>creditcard</converter-id>
6: <converter-class>cardemo.CreditCardConverter
7: </converter-class>
8: </converter>

 

 

Converters and 

Validators 

 Validators— Perform correctness checks on


Input values
 Ensure values entered by the user are in the
correct format
 Display validation error through output_errors tag
(& ;
< %,
() +, !  %-4
< %4
(* 
!:-4$ #

< %4
(= ,
%
 D! %
(3 ,
%
$+
 ! -.&5.  ! -.5.
(5  +, ! 
(6 +,! !    -.
< %.
Password : Validation Error: length must be
more than 6 and less than 16

 

 

Validators, Event 

Listener Tags 

 Component tag Attributes for calling a


backing bean method:
 Validator: Refers to a backing bean method
that performs validation on the component's
value (in Process Validations phase)
 ValueChangeListener: Refers to a backing
bean method that handles ValueChangeEvents
 ActionListener: Refers to a backing bean
method that handles ActionEvents
 Action: discussed later

 

 

Validators: 

Custom Validator 

<h:input_text id="userNo" value="#{UserNumberBean.userNumber}"


validator="#{UserNumberBean.validate}"/>
<h:command_button id="submit" action="success" value="Submit"/>
<p>
<h:messages id="errors1" for="userNo"/>

 

 

Events 

and Listeners 

 Standard events and listeners


 ValueChangedEvent— UIInput component
whose value was just changed
 called during the Process Validations phase

<h:input_text id="firstName" value="#{customer.firstName}"


valueChangeListener="#{carstore.FirstNameChanged}" />

 

 

Events 

and Listeners 

 Standard events and listeners


 ActionEvent— UICommand component
activated by the user
 processed during the Apply Request Values
phase or the Invoke Application phase

<h:command_link id="NAmerica" action="storeFront"


actionListener="#{carstore.chooseLocaleFromLink}">

 

 

Request 
 Lifecycle
Processing 

Response Response
Complete Complete

Faces
Request Reconstitute Apply
Component Request Process Process Process
Tree Values Events Validations Events

Render Response
Response Response
Complete Complete

Faces
Response Render Process Invoke Process Update
Responder Events Application Events Model
Values

Conversion Errors /
Render Response
Validation / Conversion
Errors / Render Response

 

 

Request 
 Lifecycle
Processing 

 Update model values – Push component


values to corresponding model data
objects
 For “input” components only

<h:input_text id="email"
valueRef="subscriberBean.email">

 

 

Request 
 Lifecycle
Processing 

Response Response
Complete Complete

Faces
Request Reconstitute Apply
Component Request Process Process Process
Tree Values Events Validations Events

Render Response
Response Response
Complete Complete

Faces
Response Render Process Invoke Process Update
Responder Events Application Events Model
Values

Conversion Errors /
Render Response
Validation / Conversion
Errors / Render Response

 

 
 
 
Request Processing Lifecycle

 Invoke application – execute the action


specified in the action and retrieve the
outcome
 CommandEvent – UI Command (such as a menu
item) selected
 FormEvent – Input form (with associated fields) to
be processed
<h:command_button action="#{carstore.buyCurrentCar}
"
... />
1: public class CarStore extends Object { ...
2: public String buyCurrentCar() {
3: getCurrentModel().getCurrentPrice();
4: Return "confirmChoices";
5: }

 

 

Component Tag

attributes: 

calling a backing bean method

 Component tag Attributes:


 Action: Refers to a backing bean method that
performs navigation processing and returns a
logical outcome String
 ActionListener
 Validator
 ValueChangeListener

 

 

Request 
 Lifecycle
Processing 

Response Response
Complete Complete

Faces
Request Reconstitute Apply
Component Request Process Process Process
Tree Values Events Validations Events

Render Response
Response Response
Complete Complete

Faces
Response Render Process Invoke Process Update
Responder Events Application Events Model
Values

Conversion Errors /
Render Response
Validation / Conversion
Errors / Render Response

 

 
 
 
Request Processing Lifecycle

 Render response – Convert response


component tree into appropriate markup

 

 

Rendering 

Model 

 Renderers— Adapt components to a specific


markup language
 RenderKit— defines how component classes map
to component tags appropriate for a particular
client.
 For JSP™ pages, represented as a custom tag library
 Basic HTML RenderKit part of the standard

Example: UICommand Tags

Button

Link

 

 

What’s in Faces 

Application 

 It’s a WAR:
Your.jpg
your.jsp
WEB-INF/web.xml
WEB-INF/faces-config.xml
WEB-INF/classes/your.class
WEB-INF/lib/your.jar
(if not running in Java WSDP 1.3)
WEB-INF/lib/jsf-api.jar
WEB-INF/lib/jsf-ri.jar
WEB-INF/lib/jstl.jar
WEB-INF/lib/jsf-el.jar
WEB-INF/lib/standard.jar
WEB-INF/lib/commons-beanutils.jar
WEB-INF/lib/commons-digester.jar
WEB-INF/lib/commons-collections.jar
WEB-INF/lib/commons-logging.jar

 

 

Example: 

web.xml in JSF beta 

  
 
 
 :      1)C<6 

 
  
 
   
 
  
 



   


  :   8$  
 
 !

  "  !

 


/

   @  



 

   


   #
 

 


JavaWeb


 
 

Services 

Developer’s Pack 1.3



 

 
 
 
JSF and Development Tools

 All the major tool vendors are part of the expert


group
 Expect to see support in these tools
 Java Web Services Developer Pack 1.3
 Sun Java Studio Creator (formerly Project Rave)
 NetBeans /Sun Java Studio

 

 

Current Status
 

 JavaServer Faces Reference


Implementation, 1.0 Beta
 Http://java.sun.com/j2ee/javaserverfaces/download.ht
ml
 Integrated in JavaTM Web Services Developer Pack
(Version 1.3)
 Http://java.sun.com/webservices/downloads/webservicespack.ht
ml
 The JavaServer Faces Specification, 1.0
Proposed Final Draft in Dec, 2003


Sun Java


 

Studio
 

(Faces Console Plug-in)



 

 
 

Agenda 

 JavaServer™ Faces
 Architecture overview
 Key concepts
 Development steps
 Car demo


Car

 

Demo Page 

Flow 

More.jsp

Configure car Buy


car

Finish
Storefront.jsp Customer.jsp Thanks.jsp

Change
options Give personal
information

Buy.jsp

 

 

Combining SVG 

and
JavaServer™ 

Faces Technologies

 Scalable Vector Graphics (SVG)


is an industry standard for rich,
interactive, 2D graphics
 JavaServer™ Faces technology
is an extensible, markup independent
server-side user interface framework that
works with SVG
 There is an exciting synergy when
you use the two technologies together

 

 
or
Competitors 

Collaborators? 

 SVG and JavaServer™ Faces


technologies are great complements:
 SVG is a markup language for interactive
graphics which can be generated server-side
 JavaServer™ Faces technology is a
server-side component framework that can
generate any user interface markup
 To combine them, you would:
 Build a RenderKit that emits SVG markup
instead of HTML or WML markup
!  
 

 
 



"# $%&'



!  
"# ()'

 

 
 
 



 

 
 
 

  
!   *
+   

 

 

Struts 

and JavaServer Faces™ 

 What's relationship with Struts and


JavaServer Faces?

Struts
 and JavaServer


 
 
 Faces™ 

(cont.)

 Where did Struts come from?


 Two years of discussion about MVC
and Model 1 versus Model 2
 Based on experience building a large scale
web application that was fully internationalized
 The key feature – separation of concerns MVC
 The key technologies enforcing separation
 action mappings in struts-config.xml
 View --> Controller input encapsulated in form bean
 Controller --> View via RequestDispatcher

 

 

Struts 

and JavaServer Faces™ 

(cont.)

 Where is JavaServer Faces coming from?


 The need to provide rich UI
components to page developers
 The need for a standard set of components to
ease learning (and enable tools support)
 Also:
 Event handling

 Validation

 Navigation

Struts
 and JavaServer


 
 
 Faces™ 

(cont.)

 The ideal scenario:


 Struts applications can migrate their UI to use
Faces, one page at a time, with no changes to
the Actions, form beans, or business logic

Struts
 and JavaServer


 
 
 Faces™ 

(cont.)

 Struts-Faces Integration Library:


 Use JSF component model
 A few Struts-specific components / renderers
 Replace use of Struts HTML tags
 Maintain investment in business logic
 JSF/Struts integration:
 http://jakarta.apache.org/builds/jakarta-
struts/nightly/struts-faces/

 

 
 
 

 

 

 
 

Portals 




What are


 

Portals?
 

 Common access point to distributed


information and applications
 Typical Functions:
 Content aggregation from various sources
 User registration, Authentication and
Authorization, Single Sign-On
 Personalization based on profiles / behavior
 Customization of pages by users
 Pluggable portal components: Portlets
Integrated Communications
 

 
 
 Desktop




and Wireless Access

 @ E 1  !  !   
@   1   ?
F    @    0; 

  ? @$
8 !
0
 
4 

F @   

F 1  !  

@ ; 1  ! 
   
D !   

 

 
 
 


What are Portlets?

 Web Components
 Generate content as markup “fragments”
aggregated in a portal page
 managed by a portlet container
 Fragment generated may vary depending on
user profile and configuration
 Page personalization
 Like specialized servlets aware of portal
context
 JSR 168 Portlet – Standardization

 
JSR 168

 
 

Standardization 

Write Once

Custom
Portal

Portlet Interface

Deploy to Many
JSR 168
Compliant
Portals

 

 

Aggregation 

Technologies — 

Portlets
 Java™ Portlets 1.0, JSR-168 brand-
new specification
 Features include:
 Web components, managed by a
portlet container
 Aggregation, layout management
 Page personalization
 JSR 168 Portlet – Standardization

 

 
 

Portal-Common Terminology 

4

    

User Agent 4 
Browser 8; 4
Phone,
Aggregation
PDA Personalization
Security 4
G168 Define?

 
What

 

Does JSR
 

 Portlet API
 Portlet requests
 Preferences

 User information

 Security

 Deployment packaging

 Portlet Container
 Extension of servlet container
 Contract between component
and container
G168


What Does


 

JSR
 Define? 

 Portlet API
 Portlet requests
 Preferences
 User information
 Security
 Deployment packaging
 Portlet Container
 Extension of servlet container
 Contract between component and
container

 

 

Comparing 
 with Servlets
Portlets 

 ~ Portlets, as Servlets, are web


components
 ~ Portlet API is modeled after Servlet API
 ~ Portlets lifecycle is similar to Servlets
lifecycle (init, request processing, destroy)
 * Portlets decouple request processing
from content rendering
 * Portlets have additional state out of the
box: portlet mode, window state, portlet
preferences

 

 

Portlet Container 
 

 Portlets are deployed in a Portlet


container such that container can
 Manage life cycle of Portlets
 Provide persistent storage for storing
Portlet preferences
 Cache the portlets
 Receive requests from the portal
to execute requests on the portlet

 

 

Portlet Reference 

Architecture 

Window
Security Config

Remote Portlet
Execution
module Portlet Enterprise
Portlet
Dispatcher Information
Aggregation Systems
Engine
Portlet

User
Configuration/ Persistent
Personalization Data Store
Engine

 

 

Portlet Life Cycle 
 

  I! $?     init()


Notifies initialization of
portlet by container.

render() H ! A processAction()


notifies the Portlet to notifies the Portlet
generate the markup about user's request
fragment for action.

0?! $?     destroy()
Notifies the destruction
of portlet by container.
Should free up resources in
this method.

 

 

Portlet Interface
 

public interface Portlet {

public void init(PortletConfig) throws ...;

public void processAction(ActionRequest,ActionResponse) throws ...;

public void render(RenderRequest,RenderResponse) throws ...;

public void destroy();

}

 
Two

 

Types 
 Requests
of Portlet 

 Process Action Request


processAction(ActionRequest,ActionResponse)
 Invoked only when the URL of the request is an action targeted to
the Portlet, it does not produce output
 Render Request
render(RenderRequest,RenderResponse)
 Invoked on every request to the portal, it produces output to
create the portal page. Portal keeps sending last set of render
parameters

  and
Portal

 
 

Portlet Interaction 

4 4
5 4        1
   
0    
 1

D ! 
 !

D ! 
2 A
? $ !  
    !
D ! 1
 !

J

J 1

)!      4      4  

 

 
 

GenericPortlet class 

 Portlet Modes
 Render()--like service() in servlets, calls
specified render methods:
 doView() Portlet renders markup fragment in
this mode
 doEdit() Used to change per-user settings to
customize rendering
 doHelp() Used to display help information

 

 
 

DoView() 



 

 

 



 

 
 

DoEdit() 


 


  


  


IBM

X

 

 
 

ProcessAction() 

IBM

IBM
X








 




!"

 

 
 

PortletPreferences 

 PortletPreferences used to provide a custom


view per portlet/per user
 Can Retrieve and store preferences
configuration
 getValues(), setValues() to access PortletPreferences
 May modify during processAction(), call store()
 Default values are defined in the portlet.xml
deployment descriptor

 
User

 

Profile 

attributes 

 To access user information:


 Basic user information (name,
e-mail, phone, address, etc.)
 Portlet defines the attributes it wants to access
in the deployment descriptor
 Extensible attributes
 Available as a Map from the request
object

 

 

Portlet Example

– portlet class 

1:
2: public class HelloWorldPortlet extends GenericPortlet {
3:
4: public void doView( RenderRequest request,
5: RenderResponse response)
6: throws PortletException {
7:
8: response.setContentType(“text/html”);
9: PrintWriter writer = response.getWriter();
10: Writer.write("Hello World");
11: }
12: }

 

 

Portlet Request

Dispatcher 

 Portlets can include Servlets, JSPs and


static content during a render request
 Similar to Servlet’s RequestDispatcher

 

 

Portlet Example

– portlet.xml 

1: <portlet-app>
2: <portlet>
3: <portlet-name>HelloWorldPortlet</portlet-name>
4: <portlet-class>
5: Custom.HelloWorldPortlet
6: </portlet-class>
7: <supports>
8: <mime-type>text/html</mime-type>
9: <portlet-mode>VIEW</portlet-mode>
10: </supports>
11: <portlet-preference>
12: <preference>
13: <name>locale </name>
14: <value> USA </value>
15: </preference>
16: </portlet-preference>
17: </portlet>
18: </portlet-app>

 

 

Portlet Builder 

2.0 New Features 

 Support for JSR 168


 A “portlet application” leverages existing
features of web module development
 Portlet application is simulated using
the existing simulator
 Portlet application deployable as a
war file for PS Deployer Tool
 Portlets developed within portlet application

 Sun ONE Studio 5 Compatibility



 

 
 
 

*
  

 

 

Avoid 

String Concatenation 

"+=" (all)

 String objects are immutable


 String concatenation creates multiple,
intermediate representations
 Use mutable StringBuffer for heavy-duty
string manipulation
01 String badStr = new String();
02 StringBuffer goodBuff = new StringBuffer(1000);
03 for (int i=0; i<1000; i++) {
04 badStr += myArray[i]; //creates new String
05 goodBuff.append(myArray[i]); //same buffer
06 String goodStr = new String(goodBuff);

 

 

Avoid Overhead 

of
Acquiring and 

Closing JDBC Connection (All)


 Avoid acquiring connections directly
from JDBC driver
 Use JDBC connection pooling in JDBC2.0
 DataSource.getConnection()
Wrong Way!!!
01 public void doGet(...)
02 {...
03 Connection conn=DriverManager.getConnection(...);
04 PrepareStatement pStmt = conn.prepareStatement("...");
05 ResultSet rs = pStmt.executeQuery(); ...

Right Way!!!
01 Private DataSource ds = null;
02 public void doGet(...)
03 {...
04 Connection conn=ds.getConnection("db2admin", "db2admin");
05 PrepareStatement pStmt = conn.prepareStatement("...");
06 ResultSet rs = pStmt.executeQuery(); ...

  Overhead
Avoid

 
 of


Acquiring and Closing 

JDBC Connection (All) (cont.)

 Failing to close JDBC connections can cause other


users to wait for connections
 Close JDBC statements when you are through with
them
 Ensure your code to close all JDBC resources even
in exception and error conditions
Right Way!!!
01 Connection conn =null;
02 ResultSet rs =null;
03 PreparedStatement pss=null;
04 finally (
05 // release all JDBC resources in finally block .
06 try {if (pss != null) pss.close(); }
07 catch (Exception e) {}
08
09 try {if (conn!= null) conn.close(); }
010 catch (Exception e) {}

 

 

Reuse DataSource
 for JDBC 

connections (all)
 Make JDBC connections by obtaining
javax.sql.DataSource in JDBC 2.0
 DataSource.getConnection()

 Avoid overhead of acquiring a


javax.sql.DataSource for each SQL access
Wrong Way!!!
01 Public void doGet(...)
02 {...
03 ctx = new InitialContext(...)
04 DataSource ds = (DataSource)ctx.lookup("jdbc/SAMPLE");
05 ctx.close();
06 Connection conn = ds.getConnection("db2admin", "db2admin");
07 PrepareStatement pStmt = conn.prepareStatement("...");
08 ResultSet rs = pStmt.executeQuery();
09 ...

 

 

Reuse DataSource

for JDBC 

connections (all) (cont.)

 Acquire javax.sql.DataSource in init() method


and maintain it in a common location for reuse
01 //Caching DataSource which is obtained from init()
02 private DataSource ds = null;
03
04 public void init(...)
05 {...
06 Context ctx = null;
Right Way!!!
07 try {
08 ...
09 ctx = new InitialContext(...)
10 ds = (DataSource)ctx.lookup("jdbc/SAMPLE");
11 ctx.close();
12 } catch ...
13 }

 

 

Minimize 

Use of System.out.println (all) 

 System.out.println Synchronize processing for


the duration of disk I/O
 Can significantly slow throughput
 Avoid using indiscriminate System.out.println
 Use a "final boolean" to control error and debugging
situations
Right Way!!!
01 public SomeServlet extends HttpServlet {
02 private final static boolean DEBUG = false;
03 public void doGet(...) {
04 if (DEBUG) {
05 System.out.println("An error has...");
06 }
07 }
08 }

Release
 HttpSessions


 
 
 When 

Finished (servlets)

 Only a certain number of HttpSession


can be maintained in memory
 Use HttpSession.invalidate()
to release session resource
Right Way!!!
1: public class ReceiptServlet extends HttpServlet {
2: public void doPost ...{
3: ...
4: ShoppingCart scart = (ShoppingCart)
5: Session.getAttribute( "examples.bookstore.cart" );
6: ...
7: // Clear out shopping cart by invalidating the session
8: session.invalidate();
9: ...
10: }
11:}


Use HttpServlet.init()


 
 

to Perform 

Expensive Operations (servlets)

 Servlet.init() only invoked


once when servlet is first loaded
 Use HttpServlet.init() to perform
expensive operations that need only be
done once
 init() is thread-safe

 init() can be cached safely in servlet


instance variables

Don't
 Create HttpSessions


 
 
 in 

JSPs by Default (JSP)

 By default JSP creates HttpSession


 HttpSession is an implicit object

 If do not need HttpSession in JSP,


turn it to false
 Save some performance overhead

 <%@page session="false"%>

 

 

Avoid 

Beans.instanitiate()
to 

Create New Bean (servlets)


 Beans.instantiate() create a new bean
 By retrieving a serialized bean
 Or creating a new bean
 File system checks for a serialized bean

 Avoid overhead by simply using new to create bean


object
01 public void doGet(...)
02 {...
03 PingBean ab = (PingBean)Beans.instantiate(...); Wrong Way!!!
04 ...
05 }
01 public void doGet(...)
02 {...
03 PingBean ab = new PingBean();
04 ...
Right Way!!!
05 }

 

 
 
 

 , -
+ 

 

 
 

Summary 

 Web Application Frameworks can be


developed easily on Java Enterprise System
 Struts can work well with
JavaServer™ Faces
 For a development and
optimization process
 Use frameworks for the
architectural design and analysis
 Use programming best practices for JSP/Servlets
performance tuning

 

 
 

Resources 

 JavaServer Faces specification, tutorial, and early


access release are available at:
 http://java.sun.com/j2ee/javaserverfaces/

 Struts
 http://jakarta.apache.org/struts

 Struts integration library:


 http://jakarta.apache.org/builds/jakarta-struts/nightly/struts-faces/

 Online forum (free registration required):


 http://forums.java.sun.com/forum.jsp?forum=427

 

 
 
 

Q&A

 

 
 
 

Carol McDonald
Staff Engineer/Technology Evangelist
[email protected]

Sun™ Tech Days

You might also like