Jsf

48
1 By Shaharyar Khan shaharyar.khan555@gmail .com

description

In this lecture I tried to cover almost all aspects of JSF 2.0.Also you can find the coding examples in tis lectures

Transcript of Jsf

Page 1: Jsf

1

By Shaharyar [email protected]

Page 2: Jsf

Java Server Faces (JSF) is a Java-based Web application framework intended to simplify development integration of web-based user interfaces

It is part of the Java Platform, Enterprise Edition

a standard framework for building presentation tiers for web applications

JSF is a spec which defines a component-based MVC framework

[email protected]

Page 3: Jsf

JSF is a request-driven MVC web framework for constructing user interfaces using components

Provides an event model for wiring the interactions between the UI and the application objects

Also provide us strong navigation rules and support with other technologies like AJAX

[email protected]

Page 4: Jsf

4

JSF 2.1 (2010-10-22) — Current version. Second maintenance release of 2.0. Only very minor amount of spec changes

JSF 2.0 (2009-06-28) — Major release for ease of use, enhanced functionality, and performance. Coincides with Java EE 6.

JSF 1.2 (2006-05-11) — Many improvements to core systems and APIs. Coincides with Java EE 5. Initial adoption into Java EE.

JSF 1.1 (2004-05-27) — (DEPRECATED) bug fix release. There were no spec or HTML renderkit changes.

JSF 1.0 (2004-03-11) — (DEPRECATED) the initial release of the JSF specification. Separate release that wasn't part of any Java EE/J2EE release.shaharyar.khan555@gmail

.com

Page 5: Jsf

5

Stable release2.1.9 (Mojarra Reference Implementation) / May 31, 2012; a month ago

Websitejavaserverfaces.java.net

The spec was developed by involving many people from orgs like Sun, Apache, IBM, Oracle

[email protected]

Page 6: Jsf

JSF creates “component tree”

Each element corresponds to a UI value

Steps in processing request i. Restore viewii. Apply request valuesiii. Process validationsiv. Update model valuesv. Invoke applicationvi. Render response

[email protected]

Page 8: Jsf

Components

Renderers

Managed beans

Converters / Validators

Controller (navigation model)

Event handling

Request lifecycle

[email protected]

Page 9: Jsf

JSF spec defines a standard set of components and relationships

The View layer (e.g. JSP) and the Java code on the server use these components to interact and pass data

JSF tree is the current set of components in a Java object graph

Components are represented using a tree.<f:view>

<h:form id=“form1”><h:outputText id=“lbl_name”

value=“Name”><h:inputText id=“txt_name”

value=“NameValue”></h:form>

</f:view> [email protected]

Page 10: Jsf

10

We can say that “Components are used to Separate business logic from presentation”

[email protected]

Page 11: Jsf

Component renderer encodes (generates the HTML) for the component

Renderer also decodes (sets component values from URL query string and form vars)

Render is basically a response for the user view the page that was originally requested Or render a different page

Renderers are grouped into render kits Default render kit is HTML Provide device independence w/o changing the

templating language or components themselves

[email protected]

Page 12: Jsf

Glues the UI given by jsp files to the business logic of your application

Are simply JavaBeans following standard rules a zero-argument (empty) constructor -- either by explicitly

defining such a constructor or omit all constructors no public instance variables (fields) use accessor methods instead of allowing direct access to

fields accessed through methods called getXxx and setXxx If class has method getTitle that returns a String, class

issaid to have a String property named title Boolean properties use isXxx instead of getXxx

12

Managed by the framework in Application, Session, View, Request, or no scope

[email protected]

Page 13: Jsf

@NoneScopedManaged beans with a none scope are not instantiated nor stored in any other scope.Instead, they are instantiated on demand by another managed bean. Once created, they will persist as long as the calling bean stays alive because their scope will match the calling bean’s scope.

@RequestScopedManaged beans registered with request scope will be instantiated and stay available throughout a single HTTP request. This means that the bean can survive a navigation to another page, provided it was during the same HTTP request.

[email protected]

Page 14: Jsf

@ViewScopedManaged beans registered in view scope remain available as long as the user stays on the same view. Navigating away from that view will cause beans registered in that view’s scope to be deallocated.

@SessionScopedManaged beans registered with a session scope will be stored on the HTTP session.This means that the values in the managed bean will persist beyond a single HTTP request for a single user. This is ideal for a shopping cart type of usage where values must be stored and made available during multiple requests.

[email protected]

Page 15: Jsf

@ApplicationScopedManaged beans registered with an application scope retain their values throughout the lifetime of the application and are available to all users.

Another scope which is “CustomScope” is also available but it is not important , So we skip that scope right now

[email protected]

Page 16: Jsf

A kind of managed beans, although no technical difference with managed bean

Backing beans – focus on UI of the application

[email protected]

Page 17: Jsf

17

<managed-bean> <managed-bean-name>library</managed-bean-name>

<managed-bean-class>com.oreilly.jent.jsf.library.model.Library</managed-bean-class>

<managed-bean-scope>application</managed-bean-scope> </managed-bean>

<managed-bean> <managed-bean-name>usersession</managed-bean-name> <managed-bean-

class>com.oreilly.jent.jsf.library.session.UserSession</managed-bean-class>

<managed-bean-scope>session</managed-bean-scope> </managed-bean>

<managed-bean> <managed-bean-name>loginform</managed-bean-name> <managed-bean-

class>com.oreilly.jent.jsf.library.backing.LoginForm</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope> </managed-bean>

[email protected]

Page 18: Jsf

JSF provides a very easy and best way for conversion and validation

<h:inputText id="salary" value="#{testBean.salary}"             required="true">    <f:convertNumber type="currency"/></h:inputText>it may display $1999, if the locale(faces-config.xml) is

pointing to US._______________________________________________<h:inputText id="discount"

value="#{testBean.discount}"            required="true">    <f:convertNumber type="percent"/></h:inputText>

By specifying the type as 'percentage', the display value will have a '%' symbol followed by the original value.

18

We can create our own custom converters.

[email protected]

Page 19: Jsf

JSF provide a very smart way to validate the fields and if validation fails then generate a error message define by a developer.

JSF provides different tags to handle and display messages on the view.

There are two message tags in SUN’s reference implementation of JSF HTML library:

<h:message /><h:messages />

We can place tag at the top of the form and set it to display only global messages

<h:messages globalOnly="true" />

[email protected]

Page 20: Jsf

<h:form>Enter text in this box :<br> <h:inputText id="input_text" value="#{MessageBean.a}"  required="true"/>   <h:message for="input_text" /><br>   <h:commandButton action="Submit" value="Submit"/>

[email protected]

Page 21: Jsf

An attibute for=“” can be used to specify the id of a component whose error messages we need to display

<h:inputText id="userName" value="#{userBean.userName}" />

<h:message for="userName" />

Built-in validation components

<h:inputText id="Username" value="#{UserBean.userName}">    <f:validateLength minimum="6" maximum="15"/></h:inputText>....<h:inputText id="Age" value="#{UserBean.age}">    <f:validateLongRange minimum="1" maximum="120"/></h:inputText>

[email protected]

Page 22: Jsf

We can also validate by a backing bean method

<h:inputText value="#{userBean.name}" validator="#{userBean.checkUsername}">

</h:inputText>

AND

Same like converters, We can create a custom converter

[email protected]

Page 23: Jsf

The JSF navigation system is built on top of a simple rule system that answers the

question, “which view should be shown next?” To answer this question, the rule system

considers several different questions, such as “what is the current view?” “which button was

pressed?” “does the view which should be shown next actually exist?” and “am I allowed to

show the view which should be shown next?” and

[email protected]

Page 24: Jsf

Navigation is a set of rules for choosing the next page to be displayed after a button or hyperlink component is clicked. Navigation rules are defined in the application configuration resource file.

After the proper navigation rule is selected, the choice of which page to access next from the current page depends on two factors:

The action method that was invoked when the component was clicked

The logical outcome that is referenced by the component’s tag or was returned from the action method

[email protected]

Page 25: Jsf

25

Outcome What It Means

success Everything worked. Go on to the next page.

failure Something is wrong. Go on to an error page.

logon The user needs to log on first. Go on to the logon page.

no results The search did not find anything. Go to the search page again.

Common Outcome Strings

[email protected]

Page 26: Jsf

26

<h:commandButton value="Proceed to Page2" action="gotopage2" />

<navigation-rule><from-view-id>/page1.xhtml</from-view-id><navigation-case><from-outcome>gotopage2</from-outcome><to-view-id>/page2.xhtml</to-view-id></navigation-case></navigation-rule>

Notice that for this example a from-action is not needed; instead, the from-outcomeis compared to the action attribute of the navigation UI component (commandLinkor commandButton).

[email protected]

Page 27: Jsf

27

<navigation-rule><from-view-id>/login.xhtml</from-view-id><navigation-case><from-action>#{login.loginAction}</from-action><from-outcome>success</from-outcome><to-view-id>/success.xhtml</to-view-id></navigation-case><navigation-case><from-action>#{login.loginAction}</from-action><from-outcome>failure</from-outcome><to-view-id>/failure.xhtml</to-view-id></navigation-case></navigation-rule></faces-config>At this point the application is complete with a successful navigation to the success.xhtml page occurring when “guest” and “welcome” are entered in the login page, and a navigation to failure.xhtml when anything else is entered in the login page.

[email protected]

Page 28: Jsf

Here is a navigation rule that could be used with the example just described:

<navigation-rule> <from-view-id>/logon.jsp</from-view-id> <navigation-case> <from-action>#{LogonForm.logon}</from-action> <from-outcome>success</from-outcome> <to-view-id>/storefront.jsp</to-view-id> </navigation-case> <navigation-case> <from-action>#{LogonForm.logon}</from-action> <from-outcome>failure</from-outcome> <to-view-id>/logon.jsp</to-view-id> </navigation-case>

</navigation-rule>

[email protected]

Page 29: Jsf

<navigation-rule><from-view-id>/catalog.jsp</from-view-id> <navigation-case>

<from-outcome>success</from-outcome>

<to-view-id>/bookcashier.jsp</to-view-id>

</navigation-case> <navigation-case>

<from-outcome>out of stock</from-outcome>

<from-action> #{catalog.buy} </from-action>

<to-view-id>/outofstock.jsp</to-view-id>

</navigation-case> <navigation-case> <from-outcome>error</from-outcome> <to-view-id>/error.jsp</to-view-id> </navigation-case>

</navigation-rule>

29

Note:<from-view-id>/books/*</from-view-id>Don’t get confuse if you see this line somewhere

[email protected]

Page 30: Jsf

Events are created based on the request parameters.

Each event is broadcasted to the related listeners.

<h:commandButton action=“#{ReportCtrl.save}”>Generates an event when pressedsave() 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

[email protected]

Page 31: Jsf

Even when you have event listeners, you almost always have action controllers

As before, these invoke business logic and participate in navigation flow (via navigation-rule entries in config file)

Setter methods and validation fire before action controller

<h:form>…<h:commandButton value="Show Preview"action="#{resumeBean.showPreview}"/></h:form>

[email protected]

Page 32: Jsf

Listener is usually in the form bean class But can be in separate class if you use FacesContext to get the request or session object and look up the form bean explicitly

Takes an ActionEvent as an argument Void return type (not String as in action controllers) ActionEvent is in javax.faces.event ActionEvent has a getComponent method that lets you obtain the UIComponent reference

From the UIComponent, you can get the component ID, renderer, and other low-level information

public void someMethod(ActionEvent event) {doSomeSideEffects();

}

[email protected]

Page 33: Jsf

<h:commandButton id="confirm" value="Confirm Age"

       actionListener="#{userDetails.calculateAgeListener}"></h:commandButton>______________________________________________public void calculateAgeListener(ActionEvent event) {       int calculatedAge = calculateAgeFromDOB();       if (event.getComponent().getId().equals("confirm")) {             if (calculatedAge != this.age) {                  this.isAgeCorrected = true;                  this.output = null;                  this.age = calculatedAge;             }       }}

33

Implemented in backing bean

[email protected]

Page 34: Jsf

Facelets is an open source Web template system under the Apache license and the default view handler technology (aka view declaration language) for JavaServer Faces (JSF)

The language requires valid input XML documents to work

Facelets supports all of the JSF UI components and focuses completely on building the JSF component tree, reflecting the view for a JSF application

Initially, Facelets was available as a separate, alternative view declaration language for JSF 1.1 and JSF 1.2 which both used JSP as the default view declaration language.

Starting from JSF 2.0, Facelets has been promoted by the JSF expert group to be the default view declaration language. JSP has been deprecated as a legacy fall back

[email protected]

Page 35: Jsf

Element conversion

Templating

Content re-useReferencing a fileCustom tagsComposite components

Parameterized includes

[email protected]

Page 36: Jsf

ui:insert : Used in template file, it defines content that is going

to replace by the file that load the template. The content can be replace with “ui:define” tag.

ui:define:Defines content that is inserted into template

with a matching “ui:insert” tag.

ui:include:Similar to JSP’s “jsp:include”, includes content

from another XHTML page..

[email protected]

Page 37: Jsf

ui:composition:If used with “template” attribute, the specified template is loaded, and the children of this tag defines the template layout; Otherwise, it’s a group of elements, that can be inserted somewhere. In addition, JSF removes all tags “outside” of “ui:composition” tag

[email protected]

Page 38: Jsf

38

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:body> <h3>JSF 2.0 + Ajax Hello World Example</h3>

<h:form> <h:inputText id="name" value="#{helloBean.name}"></h:inputText> <h:commandButton value="Welcome Me"> <f:ajax

execute="name" render="output" /> </h:commandButton>

<h2><h:outputText id="output"

value="#{helloBean.sayWelcome}" /></h2>

</h:form></h:body> </html>shaharyar.khan555@gmail

.com

Page 39: Jsf

Apache MyFaces, Mojarra (or) Sun JSF also known as RI(reference implementation) , PrimeFaces are all JSF standard implementations

When we need additional features then we have to include these implementations

All these implementations provide us Additional tags and features which are not available in JSF core.

[email protected]

Page 40: Jsf

Let see a simple login example of JSF<%@ page contentType="text/html"%>

<%@ 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>JSF Simple Login Example</title></head><body><h:form><table><tr><td><h:outputText value="Enter Login ID: " /></td><td><h:inputText id="loginname" value="#{SimpleLogin.loginname}" /></td></tr> 40

[email protected]

Page 41: Jsf

</tr><tr><td><h:outputText value="Enter Password: " /></td><td><h:inputSecret id="password" value="#{SimpleLogin.password}" /></td></tr><tr><td> </td><td><h:commandButton value="Login" action="#{SimpleLogin.CheckValidUser}"/></td></tr></table></h:form></body></html></f:view>

[email protected]

Page 42: Jsf

public class SimpleLogin{ String loginname; String password;

public SimpleLogin(){} public String getLoginname(){

return loginname; } public void setLoginname(String loginname){

this.loginname = loginname; } public String getPassword(){

return password; } public void setPassword(String password){

this.password = password; } public String CheckValidUser(){

if(loginname.equals("chandan") && password.equals("chand")){ System.out.println("chandan"); return "success";

} else{ return "fail";

} }

}42

[email protected]

Page 43: Jsf

<?xml version="1.0"?> <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd"> <faces-config>

<managed-bean> <managed-bean-name>SimpleLogin</managed-bean-name> <managed-bean-class>roseindia.SimpleLogin </managed-bean-class> <managed-bean-scope>request</managed-bean-scope>

</managed-bean> <navigation-rule>

<from-view-id>/login.jsp</from-view-id> <navigation-case>

<from-action>#{SimpleLogin.CheckValidUser} </from-action>

<from-outcome>success</from-outcome> <to-view-id>resultforsuccess.jsp</to-view-id>

</navigation-case> <navigation-case>

<from-action>#{SimpleLogin.CheckValidUser}</from-action>

<from-outcome>fail</from-outcome> <to-view-id>resultforfail.jsp</to-view-id>

</navigation-case> </navigation-rule>

</faces-config>43

[email protected]

Page 44: Jsf

<?xml version="1.0"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2.3//EN" "http://java.sun.com /dtd/web-app_2_3.dtd"> <web-app>

<context-param> <param-name>javax.faces.STATE_SAVING_METHOD </param-

name> <param-value>server</param-value> </context-param>

<!-- Faces Servlet --> <servlet>

<servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet

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

<!-- Faces Servlet Mapping --> <servlet-mapping>

<servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsp</url-pattern>

</servlet-mapping> </web-app>

[email protected]

Page 45: Jsf

Annotations are very powerful and helpful mehanism.

Now it is provided in every part of even JAVA as well as in many framesworks like JSF , Hibernate , JPA , EJB’s etc

Let see how annotations are helpful for programmers.

In previous slides We have seen that for navigation and setting bean properties , We used faces-config.xml

It is very annoying that we have to edit faces-config.xml file for every navigation and for setting bean classes or properties.

Annotations gives us facility to handle these things without this hectic configurations.

Let see How

[email protected]

Page 46: Jsf

For this bean class

public class SimpleLogin{//code implementation

}

46

We provided this configuration in face-config.xml

<managed-bean> <managed-bean-name>SimpleLogin</managed-bean-name> <managed-bean-class>roseindia.SimpleLogin </managed-bean-

class><managed-bean-scope>request</managed-bean-scope>

</managed-bean>

[email protected]

Page 47: Jsf

But if we create our class by placing annotation before writing our class then we can save ourself from the configurations of faces-config.xml

@ManagedBean@RequestScopedpublic class SimpleLogin{

//code implementation}

47

Like this , We have annotations for everything as well as for components@FacesComponent@FacesRenderer@FacesConverter@FacesValidator@FacesBehavior

[email protected]

Page 48: Jsf

48