3. Introduction to Java Server Faces

32
Introduction to Java Server Faces Java Server Faces Struts Struts WingS WingS WebWork WebWork Maverick Maverick Spring Spring Tapestry Tapestry WebObjects WebObjects Echo Echo Web Tier Frameworks

Transcript of 3. Introduction to Java Server Faces

Page 1: 3. Introduction to Java Server Faces

IntroductiontoJavaServerFaces

Java Server Faces Struts Struts

WingS WingS

WebWork WebWork

Maverick Maverick

Spring Spring

Tapestry Tapestry

WebObjects WebObjects Echo Echo

Web Tier Frameworks

Page 2: 3. Introduction to Java Server Faces

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. 

WhatisJavaServerFaces?

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

Page 3: 3. Introduction to Java Server Faces

JavaServerFaces

• 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 

JSFBenefits

• 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 

Page 4: 3. Introduction to Java Server Faces

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 

JSFApplications

• 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 

 

Page 5: 3. Introduction to Java Server Faces

JSFComponentModel

• 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 

SimpleExample: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...) 

Page 6: 3. Introduction to Java Server Faces

JSFArchitecture

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

Theoryvs.Practice

12

Page 7: 3. Introduction to Java Server Faces

Intheory• 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 the target (HTML, etc.) 

• Good separation of the logic and presentation 

13

Inpractice

• 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

Page 8: 3. Introduction to Java Server Faces

Inpractice

• JSF event‐model introduces the need for wrappers to actually deal with model 

• Must keep the component tree and event‐model in session 

 

15

JSFstructureandcode

16

Page 9: 3. Introduction to Java Server Faces

JSFtemplates

• 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 POJO 17

Template (jsp)

Backing Bean (java)

Logic Layer (rest of app)

faces-config (xml)

Wrapper (java)

model (java)

JSFtemplates

• 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

Page 10: 3. Introduction to Java Server Faces

Sampletemplate

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

Page 11: 3. Introduction to Java Server Faces

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

JSFbackingbeans

• 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

Page 12: 3. Introduction to Java Server Faces

Samplebackingbean

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"; } }

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

Page 13: 3. Introduction to Java Server Faces

Samplewrapperbean

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

MajorJSFConcepts• Components 

• Renderers  

• Managed beans 

• Converters / Validators 

• Controller (navigation model) 

• Event handling 

• Request lifecycle 

Page 14: 3. Introduction to Java Server Faces

JSFComponents

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

JSFRenderers

• 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 

Page 15: 3. Introduction to Java Server Faces

Backingbeans

• 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 

 

BackingBeans

• <h:outputText id="helloBeanOutput“ value="#{helloBean.numControls}"/> 

• hooks up an HtmlOutputText component’s value directly to the numControls property of an object called helloBean. 

 

Page 16: 3. Introduction to Java Server Faces

ManagedBeans

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

JSFManagedBeans

• 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 

Page 17: 3. Introduction to Java Server Faces

JSFValueBinding

• 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 

JSFValueBindingExample

view.xhtml

In logger object

Page 18: 3. Introduction to Java Server Faces

JSFValueBindingExample

Managed beans are registered in faces-config.xml

view.xhtml

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

Page 19: 3. Introduction to Java Server Faces

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> 

JSFConverters/Validators

Page 20: 3. Introduction to Java Server Faces

JSFConverterExample

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

Eventsandlisteners

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

Page 21: 3. Introduction to Java Server Faces

Eventsandlisteners

• 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‐ChangeEvents

• 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); } 

Page 22: 3. Introduction to Java Server Faces

Actionevents

• 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 

ActionListeners

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

Page 23: 3. Introduction to Java Server Faces

ActionListeners

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

 

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

Page 24: 3. Introduction to Java Server Faces

ActionListenerMethodspublic void doIt(ActionEvent event){ 

HtmlCommandButton button = (HtmlCommandButton)event.getComponent(); 

button.setValue("It's done!"); 

 

JSFController

• 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 

Page 25: 3. Introduction to Java Server Faces

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

PhaseEvents• Whenever a JSF application receives a request, it goes through a six‐step process called the Request Processing Lifecycle. 

 

Page 26: 3. Introduction to Java Server Faces

May skip to

render phase or abort request

JSFRequestLifecycle

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

JSFExtensionPoints• 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. 

Page 27: 3. Introduction to Java Server Faces

Webappbasics

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

Outputdynamictext

• 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}"/>

Page 28: 3. Introduction to Java Server Faces

Loopstructure

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

Optionalrendering

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

Page 29: 3. Introduction to Java Server Faces

Triggeractions

• 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"; }

JSFinpractice

58

Page 30: 3. Introduction to Java Server Faces

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

JSFstructurerevisit• 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)

Page 31: 3. Introduction to Java Server Faces

ApacheMyFaces• 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/

OracleADFfaces• 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/

Page 32: 3. Introduction to Java Server Faces

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