JSF
JSF
1
Objectives
• To explain what JSF is.
• To create a JSF page using NetBeans.
• To create a JSF managed bean.
• To use JSF expressions in a facelet.
• To use JSF GUI components.
• To obtain and process input from a form.
• To track sessions in application, session, view, and request
scope.
• To validate input using the JSF validators.
• To bind database with facelets.
2
Introduction
• Servlet is a primitive way to write server-side applications.
• Servlet embeds HTML code inside Java code to process an HTML
• JSP provides a scripting capability and allows you to embed Java
code inside XHTML.
• It is easier to develop Web programs using JSP than servlets.
• However, JSP has some problems.
– It can be very confused, because it mixes Java code with HTML.
– Using JSP to develop User Interface(UI) is tedious.
• JavaServer Faces (JSF) becomes to solve this problem.
• JSF enables you to completely separate Java code from HTML.
• You can quickly build web applications by assembling reusable
UI components in a page, connecting these components to Java
programs, and wiring client-generated events to server-side
event handlers.
• The application developed using JSF is easy to debug and
maintain. 3
Simple JSF Code XML Declaration
4
Basic JSF Page
• Facelets
– A facelet is an XHTML page that mixes JSF tags with XHTML
tags.
• XML Declaration
– It is used to state that the document conforms to the XML
version 1.0 and uses the UTF-8 encoding.
– This declaration is optional, but it is a good practice to use it.
– It must be the first item to appear in the document.
• DOCTYPE
– It specifies the version of XHTML used in the document.
– This can be used by the Web browser to validate the syntax of
the document.
• XML Comment
– for documenting the contents in the file.
– XML comment always begins with <!-- and end with -->.
5
Basic JSF Page
• Namespaces
– Namespaces are like Java packages.
– Java packages are used to organize classes and to avoid
naming conflict.
– XHMTL namespaces are used to organize tags and resolve
naming conflict.
– Each xmlns attribute has a name and a value separated by
an equal sign (=).
– Example:
• xmlns = http://www.w3.org/1999/xhtml specifies that any
unqualified tag names are defined in the default standard xhtml
namespace.
• xmlns:h = http://java.sun.com/jsf/html allows the tags defined in
the JSF tag library to be used in the document. These tags must
have a prefix h.
6
What is JavaBean?
JavaBeans are classes that encapsulate many objects into a single object (the bean).
It is a java class that should follow following conventions:
(1) It must be a public class;
(2) It must have a public no-arg constructor;
(3) It must implement the java.io.Serializable. (This requirement is not necessary in
JSP.)
class
Data members JavaBeans Component Minimum
Methods
Constructors requirement
public class
public no-arg constructor
serializable
may have accessor/mutator methods Optional
may have registration/deregistration methods requirement
7
Why JavaBeans?
The JavaBeans technology was developed to enable the
programmers to rapidly build applications by assembling
objects and test them during design time, thus making
reuse of the software more productive.
8
JavaBeans Properties and Naming Patterns
• The get method is named
get<PropertyName>(),
which takes no parameters and returns an object of the type
identical to the property type.
• For a property of boolean type, the get method should be named
is<PropertyName>(),
which returns a boolean value.
• The set method should be named
set<PropertyName>(newValue),
which takes a single parameter identical to the property type and
returns void.
NOTE: A property may be read-only with a get method but no set
method, or write-only with a set method but no get method.
9
package studentProfile;
public class Student {
private String firstName;
private String mi;
private String lastName;
private String telephone;
private String street;
private String city;
private String state;
private String email;
private String zip;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMi() {
return this.mi;
}
public void setMi(String mi) {
this.mi = mi;
}
10
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
11
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return this.zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
12
Managed JavaBeans for JSF
• JSF applications are developed using the MVC
architecture, which separates the application’s data
(model) from the graphical presentation (view).
• The controller is the JSF framework that is
responsible for coordinating interactions between
view and the model.
• In JSF, the facelets are the view for presenting data.
• Data are obtained from Java objects.
• Objects are defined using Java classes.
• In JSF, the objects that are accessed from a facelet
are JavaBeans objects.
13
Example: JavaBean
package jsfDemo;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class TimeBean {
public String getTime() {
return new Date().toString();
}
}
14
Code Description
• TimeBean is a JavaBeans with the @ManagedBean
annotation, which indicates that the JSF framework will
create and manage the TimeBean objects used in the
application.
• The @Override annotation tells the compiler that the
annotated method is required to override a method in a
superclass.
• The @ManagedBean annotation tells the compiler to
generate the code to enable the bean to be used by JSF
facelets.
• The @RequestScope annotation specifies the scope of the
JavaBeans object is within a request.
• You can also use @SessionScope or @ApplicationScope
to specify the scope for a session or for the entire
application.
15
JSF Expressions
16
Example
<?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:h = "http://java.sun.com/jsf/html">
<h:head>
<title>Display Current Time</title>
<meta http-equiv="refresh" content ="60" />
</h:head>
<h:body>
The current time is "#{timeBean.time}"
</h:body>
</html>
17
Code Description
• The meta tag defined inside the h:head tag is used to tell
the browser to refresh every 60 seconds.
• The JSF expression #{timeBean.time} is used to
obtain the current time.
• timeBean is an object of the TimeBean class.
• The object name can be changed in the @ManagedBean
annotation using the this syntax:
@ManagedBean(name = "anyObjectName“)
• By default the object name is the class name with the first
letter in lowercase.
• The JSF expression can either use the property
name or invoke the method to obtain the current time.
#{timeBean.time} Or
#{timeBean.getTime()}
18
JSF GUI Components
19
JSF GUI Components
JSF Tag Description
h:form inserts an XHTML form into a page.
h:panelGroup similar to a Java flow layout container.
h:panelGrid similar to a Java grid layout container.
h:inputText displays a textbox for entering input.
h:outputText displays a textbox for displaying output.
h:commandButton It submits a form to the application.
h:inputTextArea displays a textarea for entering input.
h:commandLink It links to another page or location on a page.
h:inputHidden It allows a page author to include a hidden
variable in a page.
h:inputFile It allows a user to upload a file.
h:dataTable It represents a data wrapper.
h:inputSecret displays a textbox for entering password.
h:outputLabel displays a label.
20
JSF GUI Components
JSF Tag Description
h:outputLink displays a hypertext link.
h:selectOneMenu displays a combo box for selecting one item.
h:selectOneRadio displays a set of radio button.
h:selectBooleanCheckbox displays a checkbox.
h:selectOneListbox displays a list for selecting one item.
h:selectManyListbox displays a list for selecting multiple items.
f:selectItem specifies an item in an h:selectOneMenu,
h:selectOneRadio, or h:selectManyListbox.
h:outputFormat It displays a formatted message.
h:message displays a message for validating input.
h:messages It displays localized messages.
h:dataTable displays a data table.
h:column specifies a column in a data table.
h:graphicImage displays an image. 21
Example: JSF GUI Components
This example displays a student registration
form by using some of JSF elements.
22
Example: JSF Code for the above GUI
<?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:h = "http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Student Registration Form</title>
</h:head>
<h:body>
<h:form>
<!-- Use h:graphicImage -->
<h3>Student Registration Form
<h:graphicImage name="usIcon.gif" library="image"/>
</h3>
<!-- Use h:panelGrid -->
<h:panelGrid columns="6" style="color:green">
<h:outputLabel value="Last Name"/>
<h:inputText id="lastNameInputText" />
<h:outputLabel value="First Name" />
<h:inputText id="firstNameInputText" />
<h:outputLabel value="MI" />
<h:inputText id="miInputText" size="1" />
</h:panelGrid> 23
Example: JSF Code for the above GUI
<!-- Use radio buttons -->
<h:panelGrid columns="2">
<h:outputLabel>Gender </h:outputLabel>
<h:selectOneRadio id="genderSelectOneRadio">
<f:selectItem itemValue="Male” itemLabel="Male"/>
<f:selectItem itemValue="Female”itemLabel="Female"/>
</h:selectOneRadio>
</h:panelGrid>
<!-- Use combo box and list -->
<h:panelGrid columns="4">
<h:outputLabel value="Major "/>
<h:selectOneMenu id="majorSelectOneMenu">
<f:selectItem itemValue="Computer Science"/>
<f:selectItem itemValue="Mathematics"/>
</h:selectOneMenu>
<h:outputLabel value="Minor "/>
<h:selectManyListbox id="minorSelectManyListbox">
<f:selectItem itemValue="Computer Science"/>
<f:selectItem itemValue="Mathematics"/>
<f:selectItem itemValue="English"/>
</h:selectManyListbox>
</h:panelGrid>
24
Example: JSF Code for the above GUI
<!-- Use check boxes -->
<h:panelGrid columns="4">
<h:outputLabel value="Hobby: "/>
<h:selectManyCheckbox id="hobbySelectManyCheckbox">
<f:selectItem itemValue="Tennis"/>
<f:selectItem itemValue="Golf"/>
<f:selectItem itemValue="Ping Pong"/>
</h:selectManyCheckbox>
</h:panelGrid>
<!-- Use text area -->
<h:panelGrid columns="1">
<h:outputLabel>Remarks:</h:outputLabel>
<h:inputTextarea id="remarksInputTextarea"
style="width:400px; height:50px;" />
</h:panelGrid>
<!-- Use command button -->
<h:commandButton value="Register" />
</h:form>
</h:body>
</html>
25
Session Tracking
• JSF supports session tracking using JavaBeans at
the application scope, session scope, and request
scope.
• Additionally, JSF 2.0 supports the view scope,
which keeps the bean alive as long as you
stay on the view.
• The view scope is between session and request
scopes.
26
Input Validation
• JSF provides several convenient and powerful ways for
input validation.
• You can use the standard validator tags in the JSF Core
Tag Library or create custom validators.
• The following Table lists some JSF input validator tags.
JSF Tag Description
f:validateLength validates the length of the input.
f:validateDoubleRange validates whether numeric input falls within acceptable range of
double values.
f:validateLongRange validates whether numeric input falls within acceptable range of
long values.
f:validateRequired validates whether a field is not empty.
28
Example: ValidationForm.html
<?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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Validate Form</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="Name:"/>
<h:inputText id="nameInputText" required="true"
requiredMessage="Name is required"
validatorMessage="Name must have 1 to 10 chars"
value="#{validateForm.name}">
<f:validateLength minimum="1" maximum="10" />
</h:inputText>
<h:message for="nameInputText" style="color:red"/>
<h:outputLabel value="SSN:" />
29
Example: ValidationForm.html …
<h:inputText id="ssnInputText" required="true"
requiredMessage="SSN is required"
validatorMessage="Invalid SSN”
value="#{validateForm.ssn}">
<f:validateRegex pattern="[\d]{3}-[\d]{2}-[\d]{4}"/>
</h:inputText>
<h:message for="ssnInputText" style="color:red"/>
<h:outputLabel value="Age:" />
<h:inputText id="ageInputText" required="true"
requiredMessage="Age is required"
validatorMessage="Age must be betwen 16 and 120"
value="#{validateForm.ageString}">
<f:validateLongRange minimum="16" maximum="120"/>
</h:inputText>
<h:message for="ageInputText" style="color:red"/>
<h:outputLabel value="Heihgt:" />
<h:inputText id="heightInputText" required="true"
requiredMessage="Heihgt is required“
validatorMessage="Heihgt must be betwen 3.5 and 9.5“
value="#{validateForm.heightString}“>
30
Example: ValidationForm.html …
31
Example: ValidationForm.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class ValidateForm {
private String name, ssn, ageString, heightString;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getAgeString() {
return ageString;
}
32
Example: ValidationForm.java
public void setAgeString(String ageString) {
this.ageString = ageString;
}
public String getHeightString() {
return heightString;
}
public void setHeightString(String heightString) {
this.heightString = heightString;
}
public String getResponse() {
if (name == null || ssn == null || ageString
== null || heightString == null) {
return "";
}
else {
return "You entered " + " Name: " + name
+ " SSN: " + ssn + " Age: " + ageString
+ " Heihgt: " + heightString;
}
}
}
33
The End!!
34