3. introduction to java server faces.ppt - ntuacourses.dbnet.ntua.gr/fsr/6077/3. introduction to...
Post on 31-Jan-2018
234 Views
Preview:
TRANSCRIPT
1
Introduction to
Java Server Faces
Java Server Faces
StrutsStruts
WingSWingS
WebWorkWebWork
MaverickMaverick
SpringSpring
TapestryTapestry
WebObjectsWebObjectsEchoEcho
Web Tier Frameworks
2
Frameworks, frameworks, frameworks
• JavaServer Faces is a “framework” for
developing web-based UIs in Java.
• Frameworks are extremely common these
days, and for a good reason:
• they help make web development easier.
• JSF enforces a clean separation of
presentation and business logic.
• It focuses more on the UI side of things and
can be integrated with other frameworks,
like Struts.
What is Java Server Faces?
� JSF is a web application framework that
accomplishes the MVC paradigm
�Provides set of reusable custom
components.
�Provides set of JSP tags to access those
components. 4
3
Java Server Faces
• A Java web application framework
• A set of UI components (represent html entities)
• APIs to
• represent components,
• manage state,
• handle events,
• validate input, etc.
• Custom tag libraries to put JSF in a JSP
• State management and even model
• Backing Beans (managed beans)
• Expression Language (EL)
• Servlet based, normally uses JSPs
JSF Benefits
• JSF helps web application developers to create user interfaces (UIs):
• Makes it easy to construct a UI from a set of reusable UI components
• Simplifies migration of application data to and from the UI
• Helps manage UI state across server requests
• Provides a simple model for wiring client-generated events to server-side application code
• Allows wiring client-generated events to server-side application code
4
JSF
• The primary design pattern of JSF is the Model-View-Controller (MVC) pattern.
• JSP was designed to make the view component of a web application easy to create and manage.
• JSF brings a component-based model to web application development
• Similar to the model used in stand-alone GUI applications
JSF Applications
• JavaServer Faces applications are similar to any
other Java web application.
• They run in a servlet container, and they typically
contain the following:
• JavaBeans components containing application-specific
functionality and data
• Event listeners
• Pages, such as JSP pages
• Server-side helper classes, such as database access
beans
5
JSF Component Model
• Covers a wide range components.
• Reusable
• Customizable
• State aware
• Easy to plug in third party components.
• Easy to create custom components of your
own.
• Renderers brings abstraction
Simple Example: HtmlInputText
• Declared as;
• <h:inputText id=“id1” value=“xxx” />
• Gives the output
• <input type=“text” id=“parentformid:id1”
value=“xxx” />
• Customization attributes like;
• Styleclass
• Javascript events (onmousover etc...)
6
JSF Architecture
� JSF follows MVC framework
�Model: objects and properties of application
�View: Renderers take care of view.
�Controller: FacesServlet/ JSF infrastructure defines the flow of the application.
11
Theory vs. Practice
12
7
In theory
• Web applications that work more like desktop apps
• Easier to program
• Less concern about request cycle
• Better scoping and separation
• Application/Session/Request
• Component bindings from UI to model
• Abstract component tree that is independent of thetarget (HTML, etc.)
• Good separation of the logic and presentation
13
In practice
• Harder to work with than the average web
application framework
• Big learning curve
• Have to understand the request cycle well
• Especially the ways JSF may short circuit it
• Prevents you from accessing half the capability of
HTML
• Abstraction done via custom taglibs which make the
templates into “JSF XML”
• Logic in template and custom tags defeat the goal of
separation of UI and logic
14
8
In practice
• JSF event-model introduces the need for
wrappers to actually deal with model
• Must keep the component tree and event-
model in session
15
JSF structure and code
16
9
JSF templates
• The template (most commonly jsp) defines the interface
• The faces-config defines the navigation and the backing beans
• Backing beans handle action processing, navigation processing, and connections to the logic (business) layer
• Wrapper bean wraps the data POJOs for JSF handling
• Logic layer beans can be injected as defined in the faces-config
• Model is basic data POJO17
Template(jsp)
Backing Bean(java)
Logic Layer(rest of app)
faces-config(xml)
Wrapper(java)
model(java)
JSF templates
• JSP files most of the time
• Heavily reliant on tag libraries (taglibs)
• Core (f) - basic page definition tags
• Html (h) - defines standard html tags
• Must learn a large set of restrictive taglibs
• Difficult to work with since it does not look like normal html
• Even more difficult to write new ones
• Large use of EL (expression language)
• Can encourage mixing code with html
18
10
Sample template
19
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html><head><title>Items</title></head><body>
<h:form id="items">
<h:dataTable id="itemlist” value="#{JsfBean.allItems}” var="entry">
<h:column>
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:selectBooleanCheckbox id="itemSelect" value="#{entry.selected}"
rendered="#{entry.canDelete}"/>
<h:outputText value="" rendered="#{not entry.canDelete}"/>
</h:column>
</h:form>
</body></html>
</f:view>
faces-config.xml
• Defines the backing beans
• Name used in EL in template
• Scope controlled (request, session, etc.)
• Defines navigation rules
• Based on views
• Where from (view)
• Which outcome (id)
• Where to go (view)
• Can match outcomes using wildcards20
11
Sample faces-config
21
<faces-config>
<navigation-rule>
<from-view-id>/jsf/JsfItems.jsp</from-view-id>
<navigation-case>
<from-outcome>newItem</from-outcome>
<to-view-id>/jsf/JsfAddItem.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>*</from-outcome>
<to-view-id>/jsf/JsfItems.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>JsfBean</managed-bean-name>
<managed-bean-class>org.example.jsf.JsfBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>logic</property-name>
<value>#{someLogicBean}</value>
</managed-property>
</managed-bean>
</faces-config>
JSF backing beans
• Typical bean with getters and setters and additional methods to handle actions
• Store data needed for processing the user actions using setters
• Retrieve data using getters and methods
• Process actions using methods
• Often includes code to wrap data objects
• Connects to the rest of the application
• Typically via injection
• Non-recursive (i.e. not like Spring), will not instantiate dependencies of dependencies
22
12
Sample backing bean
23
public class JsfBean {
private DataModel itemsModel;
private JsfItemWrapper currentItem = null;
...
private JsfLogic logic;
public void setLogic(JsfLogic logic) {
this.logic = logic;
}
...
public DataModel getAllItems() {
List wrappedItems = new ArrayList();
List items = logic.getAllVisibleItems(logic.getCurrentSiteId());
for (Iterator iter = items.iterator(); iter.hasNext(); ) {
JsfItemWrapper wrapper =
new JsfItemWrapper((Item) iter.next());
wrappedItems.add(wrapper);
}
itemsModel = new ListDataModel(wrappedItems);
return itemsModel;
}
...
public String processActionList() {
return "listItems";
}
}
JSF wrapper bean
• Wraps basic data POJO
• Required to avoid putting UI information in the
data POJO
• Often includes basic setters and getters for the UI
related properties
• Can be methods as well
• Also includes a setter and getter for the data POJO
24
13
Sample wrapper bean
25
public class JsfItemWrapper {
private Item item;
private boolean isSelected; // is this item selected by the user
public JsfItemWrapper(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Major JSF Concepts
• Components
• Renderers
• Managed beans
• Converters / Validators
• Controller (navigation model)
• Event handling
• Request lifecycle
14
JSF Components
• Separate business logic from presentation
• Every view is composed of a component hierarchy
• Components can be added to view programmatically or
via template (JSP by default, Facelets for superior
performance and ease of development)
• Standard components divided into two groups:
• Faces Core <f:view>, <f:loadBundle>
• HTML wrappers <h:dataTable>, <h:selectMany>, etc.
• Component = class + [renderer] + tag handler (JSP)
JSF Renderers
• Component renderer encodes (generates the HTML) for the
component
• Renderer also decodes (sets component values from URL query
string and form vars)
• Renderers are grouped into render kits
• Default render kit is HTML
• Provide device independence w/o changing the templating language
or components themselves
15
Backing beans
• Specialized JavaBeans that collect values from UI components and implement event listener methods
• JSF allows you to declaratively associate backing beans with UI components.
• with markup instead of code
• You associate a component with a backing bean via the JSF expression language
• Similar to the JSTL EL
Backing Beans
• <h:outputText id="helloBeanOutput“
value="#{helloBean.numControls}"/>
• hooks up an HtmlOutputText component’s value directly to the
numControls property of an object called helloBean.
16
Managed Beans
• JSF provides a declarative mechanism called the Managed Bean Creation facility to allow the creation of backing beans<managed-bean>
<managed-bean-name>helloBean</managed-bean-name>
<managed-bean-class>com.virtua.jsf.sample.hello.HelloBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
• This tells JSF to create an instance of the HelloBean class called helloBean, and store it in the user’s session.
• This little snippet is all that’s required to make an object available for integration with UI components.
• Any objects that use this facility are called managed beans.
JSF Managed Beans
• Link view to the model (like controller)
• Provide event handler methods which in turn call appropriate model code (save, new)
• Provide helper methods (getAvailableSelectItems)
• Hold references to one or more domain objects
• Managed by the framework in Application, Session, Request, or no scope
• Can inject references to related beans for nested flows
17
JSF Value Binding
• Component values bind to model beans
• For each request, the framework
• Converts each input value (String) into the underlying Java type (MoneyAmount)
• On output, converts underlying Java type to String
• You register converters for custom types
• All security validation therefore handled centrally and automatically by model type
JSF Value Binding Example
view.xhtml
In logger object
18
JSF Value Binding Example
Managed beans are registered in faces-config.xml
view.xhtml
JSF Converters / Validators
• Converters are bi-directional
• Input converter: getAsObject()
• Output converter: getAsString()
• Validators work with Objects, not just Strings
• JSF supplies standard converters for date / time, numbers, etc.
• You write custom converters for rich types or special behavior
19
Converter
• Converts a component’s value to and from a string for display
• A UI component can be associated with a converter
• JSF ships with converters for common types like dates and numbers
• Converters also handle formatting and localization.<h:outputText value="#{user.dateOfBirth}">
<f:convert_datetime type="both" dateStyle="full"/>
</h:outputText>
JSF Converters / Validators
20
JSF Converter Example
Converter is registered in faces-config.xml, so all
ValuedTypesafeEnum properties of any bean will use this converter
Validators also registered in faces-config.xml, but not by class
Events and listeners
• JSF uses the JavaBeans event/listener model (also used by Swing).
• UI components generate events, and listeners can be registered to handle those events.
• In a JSF application, Integrating application logic is a matter of assigning the appropriate listeners to components that generate events that the listeners understand.
21
Events and listeners
• There are four standard events:
• Value-change events
• Action events
• Data model events
• Fired when a data-aware component selects
a row for processing
• Phase events
• Execute while JSF processes an HTTP
request
Value-Change Events
• Value-change events are generated by input controls when the user enters a new value into an input component.
• Value-change listeners handle Value-change events• <h:inputText
valueChangeListener="#{myForm.processValueChanged}"/>
• When a user changes the text in the control and submits the form, JSF will generate a value-change event
public void processValueChanged(ValueChangeEvent event){HtmlInputText sender = (HtmlInputText)event.getComponent();sender.setReadonly(true);
}
22
Action events
• Generated when a user activates a
command component
• Components that generate action events,
also called action sources, include controls
such as buttons or hyperlinks
• Action events are handled by action
listeners
• Action Listeners may or may not affect
navigation
Action Listeners
• Action listeners that affect navigation typically perform some processing and then return a logical outcome that is used by JSF’s navigation system to select the next page
• Listeners that don’t affect navigation usually manipulate components in the current view, or perform some processing that changes model object, but doesn’t alter the current page the user is accessing.
• the page is usually redisplayed after the listener finishes executing.
23
Action Listeners
• Technically, all navigation is handled by a single
action listener.
• This listener automatically handles any action
events fired by a component, so it doesn’t need
to be registered manually.
• By default, this action listener delegates all of its
work to action methods in your backing beans,
so you can have different action methods handle
different parts of your application.
Action Methods
• <h:commandButton type="submit" value="Login“ action="#{loginForm.login}"/>
• When a user clicks on this button, an action event is fired, and a method login in the loginForm bean is executed
public class LoginForm {
...
public String login(){
if (...) {// login is successful
return "success"; }
else{ return "failure"; }}
...
}
• The control would be forwarded based on the return string
24
Action Listener Methods
public void doIt(ActionEvent event){
HtmlCommandButton button =
(HtmlCommandButton)event.getComponent();
button.setValue("It's done!");
}
JSF Controller
• Stateful or stateless navigation model
• Framework selects next view based on
• Previous view
• Outcome of the event handler
• Event itself (regardless of outcome)
• Any combination of the above
• Possibilities
• Universal error view (triggered by “error” outcome)
• Wildcard matching permitted in outcomes, view IDs
25
JSF Event Handling
• <h:commandButton action=“#{ReportCtrl.save}”>
• Generates an event when pressed
• save() is a method on a managed bean
• JSF calls ReportController.save()
• Can also define action listeners associated with other components in the form
• Example: AccountSearch on any page without having to tell JSF navigation controller about each instance
• Custom ActionListenerImpl runs before invoking method
Phase Events
• Whenever a JSF application receives a request, it goes through
a six-step process called the Request Processing Lifecycle.
26
May skip to
render phase
or abort request
JSF Request Lifecycle
Restore
View
Apply Request
Values
Process
Validations
Update
Model
Invoke
Application
Render
Response
Request
Response
Retrieve component tree
from client or session
Decode components
(populate w/ String values)
Convert Strings to Objects
Validate Objects
Invoke bean method(s)
Compute navigation
Call setters
on managed beans
Call bean getters to
populate components
JSF Extension Points
• Custom components
• Phase listeners (before, after any phase)
• Custom converters / validators
• Custom renderers
• Custion ActionListenerImpl to handle event
• Decorate or replace view handler, navigation handler, state
manager, etc.
27
Web app basics
4 key things you need to do in a webapp
1. Output dynamic text
• Render data to the screen
2. Loop structures
• Output collection or render tables
3. Optional rendering of components
• Render some components based on state
4. Trigger Actions
• User actions or data transmission
53
Output dynamic text
• Uses the h:outputText tag
• Also h:outputLabel and h:outputFormat
• Uses Expression Language
• Requires a bean
• Defined in the faces-config or the template
• Can set style and turn on/off escaping
54
<h:outputText value="#{JsfAppBean.currentItem.title}"/>
<h:outputText value="#{msgs.jsfapp_text}"/>
28
Loop structure
• h:dataTable is the main loop structure• Also h:panelGrid to a degree
• Takes a collection as value• Uses a variable (entry) to interact with collection
• Uses h:column to define each column 55
<h:dataTable id="itemlist” value="#{JsfAppBean.allItems}” var="entry">
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.jsfapp_text}"/>
</f:facet>
<h:outputText value="#{entry.item.title}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{msgs.jsfapp_hidden}"/>
</f:facet>
<h:selectBooleanCheckbox id="itemHidden" value="#{entry.item.hidden}"
disabled="true" />
</h:column>
</h:dataTable>
Optional rendering
• Handled per h: tag with the rendered attribute (which takes EL)
• Can prefix with not to invert
• Brings render logic into the template
56
<h:outputText value="#{entry.item.title}"
rendered="#{not entry.canDelete}"/>
<h:commandLink id="updatelink"
action="#{JsfAppBean.processActionUpdate}"
rendered="#{entry.canDelete}">
<h:outputText value="#{entry.item.title}"/>
</h:commandLink>
29
Trigger actions
• Effectively binds a bean action to a submit button (h:commandButton)
• Also h:commandLink
• Triggers an action in the bean which returns a string to indicates the view to navigate to
57
<h:commandButton value="#{msgs.jsfapp_new}"
action="#{JsfAppBean.processActionNew}" />
public String processActionNew() {
currentItem = null;
itemText = TEXT_DEFAULT;
itemHidden = HIDDEN_DEFAULT;
return "newItem";
}
JSF in practice
58
30
JSF experience
• JSF has a steep learning curve
• Tends to do things in a non-intuitive way
• UI components are restrictive
• Not enough of them, not flexible enough
• Very hard to make AJAX work
• This may be changing
• Uses Javascript too heavily
• URL location is wrong, no back button
• Very hard for UI designers to work with
59
JSF structure revisit• The template mixes html and
presentation logic
• Bad for UI designers
• The faces-config is difficult to maintain (navigation also in the backing bean)
• Easy to get out of sync
• Syntax not like Spring
• Backing beans actually work fairly well
• One of the saving graces
• Wrapper bean is extra work to have to deal with
• Sometimes have to wrap multiple objects
• Requires extra code in the backing bean
60
Template(jsp)
Backing Bean(java)
Logic Layer(rest of app)
faces-config(xml)
Wrapper(java)
model(java)
31
Apache MyFaces
• Apache implementation of JSF
• http://myfaces.apache.org/
• Open source
• Better than Sun reference implementation
• Extra features
• Additional and more flexible taglibs
• Tomahawk (h) - new and updated components
• http://myfaces.apache.org/tomahawk/
• Recommended over the Sun RI
61
URL: http://myfaces.apache.org/tomahawk/
Oracle ADF faces
• A robust and rich set of UI components that work with JSF
• Advanced tables
• Date and color pickers
• File upload
• Client side validators
• Designed to work with Oracle Jdeveloper
• Decent AJAX support
62
URL: http://www.oracle.com/technology/products/jdev/htdocs/partners/addins/exchange/jsf/
32
Other faces
• Facelets
• https://facelets.dev.java.net/
• JSF without JSP (similar to tapestry)
• Struts Shale
• http://shale.apache.org/
• Framework based on JSF, similar to struts
63
Questions
top related