A server side user interface component framework for Java technology-based web applications
JSF contains an API for representing UI components and managing their state; handling events, server-side validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.
user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
* Offers a clean separation between behavior and presentation.
* Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
* Robust event handling mechanism.
* Events easily tied to server-side code.
* Reference Implementation (RI) by Sun Microsystems.
* Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
* JavaBeans components for managing application state and behavior.
* Event-driven development (via listeners as in traditional GUI development).
* Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed
Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data
Because Struts is a web application framework, it has a more sophisticated controller architecture than does JavaServer Faces technology
Application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller.
the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces
Struts includes a powerful layout management framework, called Tiles, which allows you to create templates that you can reuse across multiple pages, thus enabling you to establish an overall look-and-feel for an application
The Struts validation framework includes a larger set of standard validators, which automatically generate both server-side and client-side validation code based on a set of rules in a configuration file.
The greatest advantage that JavaServer Faces technology has over Struts is its flexible, extensible UI component model, which includes:
–> A standard component API for specifying the state and behavior of a wide range of components, including simple components, such as input fields, and more complex components, such as scrollable data tables. Developers can also create their own components based on these APIs, and many third parties have already done so and have made their component libraries publicly available.
–> A separate rendering model that defines how to render the components in various ways. For example, a component used for selecting an item from a list can be rendered as a menu or a set of radio buttons.
An event and listener model that defines how to handle events generated by activating a component, such as what to do when a user clicks a button.
–> Conversion and validation models for converting and validating component data.
http://www.developersbook.com/jsf/interview-questions/jsf-interview-questions-faqs.php
http://www.techartifact.com/blogs/2013/02/learn-jsf-2-0-a-ppt-on-the-jsf-2-0.html?goback=.gde_70526_member_210728763
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:
Use of XHTML for creating web pages
Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries
Support for the Expression Language (EL)
Templating for components and pages
Advantages of Facelets for large-scale development projects include the following:
Support for code reuse through templating and composite components
Functional extensibility of components and other server-side objects through customization
Faster compilation time
Compile-time EL validation
High-performance rendering
http://docs.oracle.com/javaee/6/tutorial/doc/gijtu.html
The SpringBeanFacesELResolver is the glue that allows JSF pages to use Spring beans is if they were @ManagedBeans.
http://papweb.wordpress.com/2011/07/29/spring-mvc-3-jsf-2-with-maven-2-and-tomcat/
- The SpringBeanFacesELResolver is the glue that allows JSF pages to use Spring beans is if they were @ManagedBeans.
http://papweb.wordpress.com/2011/07/29/spring-mvc-3-jsf-2-with-maven-2-and-tomcat/
A set of Web-based GUI controls and handlers?
– JSF provides many prebuilt HTML-oriented GUI controls, along
with code to handle their events.
• A device-independent GUI control framework?
– JSF can be used to generate graphics in formats other than HTML,
using protocols other than HTTP.
• An MVC-based Web app framework?
– Like Apache Struts, JSF can be viewed as an MVC framework for
building HTML forms, validating their values, invoking business
logic, and displaying results.
• An Ajax library?
– JSF 2.0 provides very easy-to-use Ajax support. So, JSF 2.0 can be
viewed as an alternative to jQuery or GWT.
• But which is the proper way to view JSF?
– The answer depends on what you are going to use it for, but 1 & 3
are the most common ways of looking at JSF
Integrated Ajax support
– You can use jQuery, Dojo, or Ext-JS with servlets and JSP. However, JSF
lets you use Ajax without explicit JavaScript programming and with very
simple tags. Also, the Ajax calls know about the server-side business logic
Page templating
– Although JSP has jsp:include for reuse of content, JSF has a full-fledged
page templating system that lets you build pages that share layout or
content
JSF 2 vs. Struts 2
You decide that for your application, the benefits (power)
of using a Web application framework [vs. servlets/JSP
with MVC] outweigh the disadvantages (complexity)
• Problem
– JSF is not the only game in town
• Alternatives
– Struts is the most popular alternative to JSF
– But there are many more
• Spring MVC
• Apache Wicket
• Apache Tapestry
• jMaki
Advantages of JSF
(vs. Struts)
• Custom components
JSF makes it relatively easy to combine complex GUIs into a single
manageable component; Struts does not
There are many existing third-party component libraries for JSF,
virtually none for Struts
• PrimeFaces, JBoss RichFaces, Oracle ADF, IceFaces, Apache
Tomahawk, Woodstock, Web Galileo, …
Official part of Java EE
– JSF is part of the Java EE spec, and all servers that support Java EE
include JSF (JSF 2.0 is part of Java EE 6)
Simpler controller and bean definitions
– JSF does not require your controller and bean classes to extend
any particular parent class (e.g., Action) or use any particular
method (e.g., execute). Struts does.
Disadvantages of JSF (vs. Struts)
Confusion vs. file names
– The actual pages used in JSF end in .xhtml. But the URLs used
end in .faces or .jsf. This causes many problems.
• You cannot browse directories and click on links
• It is hard to protect raw XHTML pages from access
• It is hard to refer to non-faces pages in faces-config.xml
Self-submit approach
– With Struts, the form (blah.jsp) and the handler (blah.do)have
different URLs; with JSF they are the same (blah.jsf).
Much weaker automatic validation
– Struts comes with form-field validators for email address,
credit card numbers, regular expressions, and more. JSF
only comes with validators for missing values, length of
input, and numbers in a given range.
• You can use third-party validation libraries with JSF (e.g.,
MyFaces/Tomahawk built on the Struts/Commons
validation library), but still not as powerful as Struts
Lack of client-side validation
– Struts supports JavaScript-based form-field validation;
JSF does not
• You can use Ajax-based validation in JSF, but still not as
good as the true client-side validation in Struts
JSF 2.0 vs. JSF 1.x
New features vs. JSF 1.x
– Smart defaults
– Annotations to replace many faces-config.xml entries
– Ajax support
– Integrated support for facelets
– Simpler custom components
– More components and validators
– Support for Groovy
– Ability to bookmark results pages
– Lots more
Main JSF 2.0 Implementations
un/Oracle Mojarra
– Main page: http://javaserverfaces.java.net/
– Runs in any server supporting servlets 2.5 or later
– Also integrated into Glassfish 3
• Apache MyFaces
– Main page: http://myfaces.apache.org/core20/
– Runs in any server supporting servlets 2.5 or later
– Also integrated into Apache Geronimo 3
• Any Java EE 6 server
– JSF 2.0 is an official part of Java EE 6
• JBoss 6, Glassfish 3, WebLogic 11, WebSphere 8,
Geronimo 3, etc.
JSF2-Overview.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Getting required software
– Installing Java SE 6 or 7
– Installing Eclipse (Java EE version)
– Installing a server for JSF 2.0
• Tomcat 6 or 7 (also needs javax.faces-2.1.x .jar) or
• Any Java EE 6 server (e.g., Glassfish 3)
Requirements for Running JSF 2
server
– Servers that just support servlets 2.5 or later (e.g., Tomcat 6 or 7) need JSF
JAR file (javax.faces-2.1.7.jar in Mojarra, but could have other name)
• In addition, JSTL 1.2 JAR files needed if you use ui:repeat tag
• JSF 2.0 also runs on the Google cloud server (which uses Jetty)
– Servers that support Java EE 6 (e.g., Glassfish 3, JBoss 6, WebLogic 11g)
have built-in support for JSF 2.0 & JSTL 1.2
• All tutorial examples run on Tomcat 6, Tomcat 7, & Glassfish 3
o run on Tomcat
– Install Java
• Java 5 or later
– Install an IDE
• I use Eclipse 3.8 (Juno)
– Download Tomcat 6 or 7
• Or any server supporting
servlets 2.5
– Get JSF 2.x JAR files
• javax.faces-2.1.x .jar
• (JSTL 1.2 JAR files)
• Download from Oracle
Mojarra or Apache
MyFaces
– web.xml, faces-config.xml
• Required entries shown
later in tutorial
To run on Glassfish
– Install Java
• Java 6 or later
– Install an IDE
• I use Eclipse 3.8 (Juno)
– Download Glassfish 3
• Or any server supporting
Java EE 6
– No extra JAR files needed
• Java EE 6 has built-in
support for JSF 2.0
– web.xml, faces-config.xml
• Required entries shown
later in tuto
Tell Eclipse about Java version
– Window ?Preferences ?Java ?
Installed JREs ?Press “Add”, choose
“Standard VM”, navigate to JDK folder
(not “bin” subdirectory)
• E.g., C:\Program Files\Java\jdk1.6.0_35
SF 2.0 support
– Eclipse 3.8 has support for JSF 2.
• R-click and add Project Facet for JSF 2
• R-click .xhtml files and
Open With, Web Page Editor
• Double-click faces-config.xml
Downloading JSF 2.0 From Scratch (Mojarra)
Required JAR files: javax.faces-2.1.x.jar
– Goes in the WEB-INF/lib folder of your projects.
– Download
• http://javaserverfaces.java.net/download.html
• Click on latest 2.x .y binary bundle
• Download and grab the JAR file from lib folder
• Suggested: jstl-1.2-api.jar, jstl-1.2-impl.jar
– Although the Mojarra Web site states that only the
javax.faces…jar file is needed, the standard ui:repeat tags
use JSTL 1.2 internally. So, the JSTL JARs are highly
recommended.
– Download
• http://jstl.java.net/download.html
• Click on both “API” and “Implementation” links
@ManagedBean
Declares this as managed bean, without requiring entry in faces-config.xml
Since no scope given, it is request scope.
HealthPlanBean.java
Since no name given, name is the class name with the first letter changed to lower case (i.e., healthPlanBean).
return("accepted");
Since there are no explicit navigation rules in faces-config,
these return values correspond to accepted.xhtml and rejected.xhtml (in same folder as page that has the form).
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Getting-Started.pdf
- the most important features that are new in JSF 2.0
Facelets, not JSP, is the standard technology for all your JSF pages. Name the pages blah.xhtml, but use the URL blah.jsf (assuming a url-pattern of *.jsf in web.xml). Use xhtml format for the pages themselves. Don't use @taglib, but instead use xmlns:h="http://java.sun.com/jsf/html". Then, use h:head, h:body, and h:form (but not usually f:view) in the page
You can use default bean names. Instead of declaring beans with managed-bean in faces-config.xml, you can put @ManagedBean above the class definition. Then, take the bean classname, change the first letter to lower case, and use that as the managed bean name. For example, if the class is package1.package2.MyBean, you would use #{myBean.whatever} in your code. You can also do @ManagedBean(name="someName"). Beans are request scoped by default, but there are annotations like @SessionScoped to change the default
You can use default mappings of outcomes to results pages. In the absence of explicit navigation rules, the return values of the action controller method correspond to the file names that should be used. Suppose that your form (file form.xhtml, URL form.jsf) says <h:commandButton ... action="#{someBean.someMethod}"/>. When the button is pressed, the bean named someBean is instantiated (assuming request scope), setter methods corresponding to the h:inputBlah elements are run, validation occurs, and then someMethod is executed. This is the same as in JSF 1.x, except that the managed bean name (someBean) can be derived from the bean class name (SomeBean). But now, if someMethod returns "foo" and "bar", and there are no explicit navigation rules in faces-config.xml for those outcomes, then JSF will assume that they correspond to foo.xhtml and bar.xhtml (from the same folder as form.xhtml), respectively. For example, in the this sample bean, the outcomes correspond to accepted.xhtml and rejected.xhtml. In a later section on page navigation, I will argue that explicit navigation rules are probably what you will use in real projects, but the implicit navigation lets you get your app up and running more quickly, and is particularly convenient for test apps where you just want to experiment with some particular JSF 2 feature.
Mere mortals can build custom components. In JSF 1.x, the existence of an API for custom components was a real boon. Because of it, a whole market for third-party component libraries developed, with PrimeFaces, RichFaces, IceFaces, Tomahawk, ADF, and Web Galileo being notable libraries. However, the API was so complex that it was more trouble than it was worth for most ordinary JSF programmers. Now, there is a very easy-to-use facelets-based (rather than Java-based) method for building simple and medium-complex components. This is somewhat analogous to the tag-file way of building JSP custom tag libraries, but even simpler and even more powerful. A later section covers composite components in detail.
There is a powerful and relatively easy to use page templating library (better than Tiles!). JSP always had jsp:include, but it lacked a serious library for building page templates, sub-templates, and concrete pages built upon templates. However, most modern Web apps have many similar-looking pages, so templating is a must. JSF 2 has a well-thought-out, extensible, and moderately easy-to-use templating framework that is arguably even better than Apache Tiles on which it was loosely based
http://www.coreservlets.com/JSF-Tutorial/jsf2/#New-Features
There will be no content inside the tags for any of the examples in this section. All examples in this section use
default bean names (derived from the bean’s class name with the first letter changed to lower case) and default
results pages (derived from the action controller’s return values)
web.xml
You must have a url-pattern for the FacesServlet, just as
in JSF 1.x. You can optionally set the PROJECT_STAGE,
which is recommended during development and testing
Eclipse Support: Issues
Poor web.xml file created when facet added
• Creates a web.xml file with spurious entries, and without the very
valuable Development PROJECT_STAGE entry
– Editing .xhtml files
• By default, they open in normal HTML editor, not smart editor that
understands and previews the h: tags
Managed beans are Java classes that are declared with
@ManagedBean or listed in faces-config.xml. More detai
will be given in the next tutorial sections, but for now the
main points are:
• They are usually POJOs (they implement no special
interfaces, and most methods have no JSF-specific
argument or return types).
• They have pairs of getter and setter methods
corresponding to each input element in the form.
• They have an action controller method that takes no
arguments and returns a String. This is the method listed
the action of the h:commandButton in the input form.
• (They also typically have placeholders for derived
properties – information that will be computed based on th
input data. More on this in the next lecture on managed
beans.)
@ManagedBean annotation
You refer to bean with #{someName.blah}, where bean
name is class name (minus packages) with first letter
changed to lower case. Request scoped by default.
• And “blah” is either an exact method name (as with action
of h:commandButton), or a shortcut for a getter and setter
method (as with value of h:inputText).
Return values of action controller method
– If action controller method returns "foo" and "bar" and
there are no explicit mappings in faces-config.xml, then
results pages are foo.xhtml and bar.xhtml
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Programming-Basics.pdf
- Three parts of beans in JSF
– Getter/setter methods to represent input elements
– Action controller method
– Placeholder for results (properties derived from input)
Basic Beans
Java classes that follow certain conventions
– Must have a zero-argument (empty) constructor
• You can satisfy this requirement either by explicitly
defining such a constructor or by omitting all constructors
Should have no public instance variables (fields)
• You should already follow this practice and use accessor
methods instead of allowing direct access to fields
Persistent values should be accessed through methods
called getBlah and setBlah
• If class has method getTitle that returns a String, class is
said to have a String property named title
– JSF uses #{book.title} to mean “call getTitle on ‘book’ ”.
• Boolean properties may use isBlah instead of getBlah
• What matters is method name, not instance variable name
Bean Properties
Usual rule to turn method into property
– Drop the word “get” or “set” and change the next letter to
lowercase. Again, instance var name is irrelevant.
• Method name: getFirstName
• Property name: firstName
• Example: #{customer.firstName}
• Exception 1: boolean properties
– If getter returns boolean or Boolean
• Method name: getPrime or isPrime
• Property name: prime
• Example: #{myNumber.prime}
• Exception 2: consecutive uppercase letters
– If two uppercase letters in a row after “get” or “set”
• Method name: getURL
• Property name: URL (not uRL)
• Example: #{webSite.URL}
Why You Should Use Accessors, Not Public Fields
private double speed; // Var name need not match method name
public double getSpeed() {
return(speed);
}
public void setSpeed(double speed) {
this.speed = speed;
}
You are probably following most of the conventions
already anyhow
• Zero arg constructor
• No public instance variables
• Use getBlah/setBlah or isBlah/setBlah naming conventions
JSF often refers to “bean properties”
– Which are shortcuts for getter/setter methods
• getFirstName method: refer to “firstName”
– #{customer.firstName}
• isVeryCool method (boolean): refer to “veryCool”
– #{invention.veryCool}
• getHTMLString method: refer to “HTMLString”
– #{message.HTMLString}
JSF automatically “manages” the bean
– Instantiates it
• Thus the need for a zero-arg constructor
– Controls its lifecycle
• Scope (request, session, application) determines lifetime
– Calls setter methods
• I.e., for <h:inputText value="#{customer.firstName"/>, when form
submitted, the value is passed to setFirstName
– Calls getter methods
• #{customer.firstName} results in calling getFirstName
Simplest: @ManagedBean before class
• Results in request scope. See next lecture for other scopes.
– Most powerful: <managed-bean> in faces-config.xml
Managed beans typically have three parts
– Bean properties (i.e, pairs of getter and setter methods)
• One pair for each input element
• Setter methods called automatically by JSF when form
submitted. Called before action controller method.
– Action controller methods
• Often only one, but could be several if the same form has
multiple buttons
• Action controller method (corresponding to the button that
was pressed) called automatically by JSF
– Placeholders for results data
• Not automatically called by JSF: to be filled in by action
controller method based on results of business logic.
• Needs a getter method so value can be output in results
page, but not required to have a setter method
Performance Principle: Make Getter Methods Fast
Problem
– Getter methods of managed beans called several times.
• E.g., at a minimum, once when form is displayed
(<h:inputText value="#{user.customerId}"/>) and again
when result is shown (#{user.customerId}).
– But often extra times.
– So, if getter method talks to database or does other
expensive operation, performance can be unexpectedly
bad.
• Solution
– Store data in instance variables, have getter methods
merely return the existing values
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-1.pdf
A getter method will be called everytime when ValueExpression#getValue() is been invoked on the given EL expression. This will normally be invoked one or two times per JSF request-response cycle, depending on whether the component is an input or output component (learn it here). However, this count can get up (much) higher when used in iterating JSF components (such as <h:dataTable> and <ui:repeat>), or here and there in a boolean expression like the rendered attribute. JSF (specifically, EL) won't cache the evaluated result of the EL expression at all as it may return different values on each call (for example, when it's dependent on the currently iterated datatable row).
Evaluating an EL expression and invoking a getter method is a very cheap operation, so you should generally not worry about this at all. However, the story changes when you're performing expensive DB/business logic in the getter method for some reason. This would be re-executed everytime!
Getter methods in JSF backing beans should be designed that way that they solely return the property and nothing more, exactly as per the Javabeans specification. They should not do any expensive DB/business logic at all. For that the bean's (post)constructor, initialization blocks and/or (action)listener methods should be used. They are executed only once during bean's life and that's exactly what you want.
Here is a summary of all different right ways to preset/load a property.
public class Bean {
// Direct initialization.
private SomeObject someProperty = loadSomeProperty();
{
// Or in init block (applies to all constructors, not so relevant in javabeans).
someProperty = loadSomeProperty();
}
public Bean() {
// Or in constructor.
someProperty = loadSomeProperty();
}
@PostConstruct
public void init() {
// Or in @PostConstruct (Will be invoked AFTER construction and dependency/property injection).
someProperty = loadSomeProperty();
}
public void change(ValueChangeEvent event) {
// Or in some FacesEvent method.
someProperty = loadSomeProperty();
}
public void listener(AjaxBehaviorEvent event) {
// Or in some BehaviorEvent method.
someProperty = loadSomeProperty();
}
public String submit() {
// Or in Action method.
someProperty = loadSomeProperty();
return "outcome";
}
public SomeObject getSomeProperty() {
// Just keep getter untouched. It isn't intented to do business logic!
return someProperty;
}
}
If there are for you really no other ways, due to some restrictive design requirements, then you should introduce lazy loading inside the getter method. I.e. if the property is null, then load and assign it to the property, else return it.
public SomeObject getSomeProperty() {
// If there are really no other ways, introduce lazy loading.
if (someProperty == null) {
someProperty = loadSomeProperty();
}
return someProperty;
}
This way the expensive DB/business logic won't unnecessarily be executed on every single getter call.
http://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times/2090062#2090062
The getter, as its name already self-describes, is just there with the pure purpose to retrieve the data. JSF doesn't cache this data. It will call it whenever needed. The cost of calling a getter is in practice nihil --unless you do something more than returning the data, e.g. hitting the DB everytime, this logic should then be moved out of the getter or be turned into lazy loading.
http://stackoverflow.com/questions/2786834/between-a-jsf-page-and-a-managed-bean-why-the-getter-method-is-called-twice
session-scoped solution?
<!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:body>
…
<fieldset>
<legend>Bank Customer Lookup (Request Scope)</legend>
<h:form>
Customer ID:
<h:inputText value="#{bankingBean.customerId}"/><br/>
Password:
<h:inputSecret value="#{bankingBean.password}"/><br/>
<h:commandButton value="Show Current Balance"
action="#{bankingBean.showBalance}"/>
</h:form>
</fieldset>
…
</h:body></html>
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-1.pdf
- Giving Custom Names to Beans
The name attribute of @ManagedBean
@ManagedBean(name="anyName")
public class BeanName { … }
– You refer to bean with #{anyName.blah}, where bean
name is exact value of name attribute.
• Still request scoped by default.
• Still no entries in faces-config.xml
Bean Scopes
dea
– Designates how long managed beans will stay “alive”,
and which users and requests can access previous bean
instances.
• JSF 1.x scopes
– Request, session, application
– Specified in faces-config.xml
– Request scope is the default
• JSF 2.0 scopes
– request, session, application, view, none, custom
– Specified either in faces-config.xml or by one of the new
annotations (e.g., @SessionScoped)
– Request scope is still the default
Annotations to Specify Bean Scope
@RequestScoped
– Default. Make a new instance for every HTTP request.
Since beans are also used for initial values in input form,
this means bean is generally instantiated twice (once
when form is displayed, once when form is submitted).
• @SessionScoped
– Put bean in session scope. If same user with same cookie
(JSESSIONID) returns before session timeout, same bean
instance is used. You should make bean Serializable.
• @ApplicationScoped
– Put bean in application scope. Shared by all users. Bean
either should have no mutable state or you must carefully
synchronize access. Usually immutable
@ViewScoped
– Same bean instance is used as long as same user is on
same page (e.g., with event handlers or Ajax).
• New scope in JSF 2.0.
• Bean should implement Serializable
• @CustomScoped(value="#{someMap}")
– Bean is stored in the Map, and programmer can control
lifecycle.
• New scope in JSF 2.0
• @NoneScoped
– Bean is not placed in a scope. Useful for beans that are
referenced by other beans that are in scopes.
• New scope in JSF 2.0
No automatic access to request & response
– JSF action controller methods do not have direct access
• Unlike in Struts, where action controller method (execute)
gets request and response automatically
@ManagedProperty:
JSF supports simple dependency injection
– That is, you can assign values to a managed bean
property (i.e., a value the main bean depends on) without
hardcoding it into the class definition
• Not as powerful as with Spring, but still useful
– @ManagedProperty lets you do this with annotations
• @ManagedProperty(value="#{someBean}")
private SomeType someField;
– <managed-property> lets you do it in faces-config.xml
• This is same as in JSF 1.x
faces-config better than annotations (?)
– One of the points of dependency injection is to let you change the concrete
class without changing Java code
• Using annotations in the Java code partially violates that principle
– faces-config.xml lets you specify Map elements
• The annotation does not
Spring is best of all (?)
– For situations that warrant the extra complexity, Spring has nice JSF
integration, so you can directly use Spring configuration files (e.g.,
applicationContext.xml)
http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Managed-Beans-2.pdf
- Pros and Cons of Explicit Bean Declarations
@ManagedBean
– Simpler/faster to start with
– Java developer knows the bean name
• Explicit declarations in faces-config.xml
– Easier for facelets developer to find bean
• If you have a large project with many packages, even knowing the
bean class name (as with @ManagedBean) requires you to search
many packages to find the class
– Can use multiple instances of the same bean class in the same page.
See temperature converter in first PrimeFaces lecture for example.
– Can use same class in different pages with different scopes
– Better understanding of beans used in project
• One central file lists all managed beans
Debugging strategies
– Set PROJECT_STAGE to Development in web.xml
• This is already set in jsf-blank
– Many of the errors cause the process to abort at certain
points. Knowing how far things got is very helpful.
• Use print statements or IDE breakpoints
• Put a print statement in the action controller method
• Put a print statement in the empty constructor
– public MyBean() { System.out.println("MyBean built"); }
– Bean should be instantiated twice for request scope
• Put print statements in the bean setter methods
JSF2-Page-Navigation.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
JSP scripting not supported in facelets
– So, you need a way to indirectly invoke Java
Passing arguments
– Version 2.1 of the EL lets you pass arbitrary arguments to
methods. Works only in Java EE 6 or other servers that
support EL 2.1. Not part of JSF 2 itself.
• E.g, works in Tomcat 7 but not Tomcat 6, even though
JSF 2 works in both
Outputting Simple Bean Properties
Format
– #{varName.propertyName}
– <h:outputText value="#{varName.propertyName}" …/>
• For new JSF 2 code, top version is usually used unless
you need some other attribute of h:outputText (e.g. “id”,
“rendered”, or “escape”)
• Interpretation
– First, find varName
• Search for “varName” in all defined scopes, from most
specific to most general (request, session, application, in
that order for standard Web app scopes). Then look in
managed bean defs and instantiate if found.
– Call getPropertyName and output the result
• This must be a normal zero-arg accessor method. If
boolean, name of method could be is PropertyName
Understanding Getter vs. Setter Method Correspondence
Example
– <h:inputText value="#{myBean.a.b.c.d}"/>
• When displaying form
– Find or instantiate myBean. Call getA. Call getB on
result. Call getC on that result. Call getD on that result. If
non-empty use as initial value of textfield.
• When submitting form
– Find myBean (instantiate new version if in request
scope). Call getA. Call getB on result. Call getC on that
result. Then pass submitted value to the setD method of
that result.
• Point: only final one becomes setter on submission.
• This assumes value passes validation. Discussed later
Equivalent forms
– #{name.property}
• Only legal if “property” would be legal Java variable name
– #{name["property"]}
• Reasons for using bracket notation
– To access arrays, lists, and other collections
• See upcoming slides
– To calculate the property name at request time.
• #{name1[name2]} (no quotes around name2)
– To use names that are illegal as Java variable names
• #{foo["bar-baz"]}
• #{foo["bar.baz"]}
Works for
– Array. Equivalent to
• theArray[index] (getting and setting)
– List. Equivalent to
• theList.get(index) or theList.set(index, submittedVal )
– Map. Equivalent to
• theMap.get(key) or theMap.put(key, submittedVal )
• Equivalent forms (for Maps)
– #{stateCapitals["maryland"]}
– #{stateCapitals.maryland}
– But you can’t use this for lists (numbers are not legal Java
variables names, so #{listVar.2} is illegal). And not all
hash table keys are legal variable names. So, use brackets
EL version 2.2 lets you call regular methods
– Rather than only zero-arg accessor methods
• Syntax
– Basic syntax is straightforward
• #{someBean.someMethod(arg1, arg2)}
– The arguments can also be EL expressions
• Cautions
– Use sparingly: put complexity in Java, not facelets
– Works only in EL 2.2. Not part of JSF 2.0 itself.
• Server must support servlets 3.0
– All Java EE 6 servers automatically do
• So, works in Glassfish 3, JBoss 6, and Tomcat 7.
Fails in Tomcat 6, JBoss 5, and other servlet 2.5 engines
JSF2-Expression-Language.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
Idea
– Store some fixed strings in a simple plain-text file. Load
that file and refer to the strings by the names given in the
file.
• Purpose
– Reuse same strings in multiple pages.
– Update in one fell swoop.
• Notes
– Bean properties are for values that change at runtime.
– Entries in properties files are much simpler strings that
are constant for the life of the application, but either
appear multiple places or might change some time in the
future.
Create a .properties file
• Contains simple keyName=value pairs
• Must be deployed to WEB-INF/classes
• In Eclipse, this means you put it in “src” folder
Declare with resource-bundle in faces-config
– base-name gives base file name relative to “src” (classes)
– var gives scoped variable (Map) that will hold results
• E.g., for WEB-INF/classes/messages.properties
<application>
<resource-bundle>
<base-name>messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
Output messages using normal EL
– #{msgs.keyName}
firstNamePrompt=Enter first name
lastNamePrompt=Enter last name
emailAddressPrompt=Enter email address
This is a single line in actual file. You can break long lines
into multiple lines by putting \ at the end of a line.
• At runtime, this will be
…/WEB-INF/classes/messages1.properties
• faces-config.xml will load this with (inside “application” element)
<resource-bundle>
<base-name>messages1</base-name>
<var>msgs1</var>
</resource-bundle>
• Facelets page will output messages with
– #{msgs1.firstNamePrompt}
Parameterized Messages
Idea
– Store some strings in a simple plain-text file. Load that
file and refer to the strings by the names given in the file.
Allow portions of the strings to be replaced.
• Purpose
– Make strings more flexible by having one string refer to
another.
– Allow runtime values to be inserted into strings.
• Particularly useful for prompts and error messages
• Notes
– These are no longer purely static strings. However, the
basic outline of the string is still fixed, so they are
different from bean properties, which are very dynamic
Create a .properties file in src
– Values contain {0}, {1}, {2}, etc.
– E.g., someName=blah {0} blah {1}
• Reminder: “src” in Eclipse becomes WEB-INF/classes when deployed
Output messages using h:outputFormat
– value gives base message
– Nested f:param gives substitution values. These can be literal
strings or runtime values
– E.g.:
<h:outputFormat value="#{msgs.someName}">
<f:param value="Literal value for 0th entry"/>
<f:param value="#{someBean.calculatedValForEnty1}"/>
</h:outputFormat>
You must define f: namespace
– Since the tag uses a different prefix (f:), you must define
the f: namespace in the <html…> tag at the top
– We did this in some earlier sections when we used
f:selectItems inside of h:selectOneMenu
Example
<!DOCTYPE …>
<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:head>…</h:head>
<h:body>…</h:body>
</html>
Internationalization and Messages
Store some multiple versions of properties file
(msg.properties, msg_es.properties,
msg_es_mx.properties, etc.)
• Base properties file gets loaded (e.g., msg.properties) .
Then one most loosely matching current Locale, if any
(e.g., msg_es.properties), then one more specifically
matching, if any (e.g., msg_es_mx.properties). If same
name occurs in more than one file, later file wins.
Purpose
– Let page be displayed in multiple languages
Use f:view and locale attribute
<f:view locale="#{facesContext.externalContext.requestLocale}">
– Determines locale from browser language settings
– Note: can also set the Locale based on user input
Getting Properties from
Database
• Idea
– Instead of using properties file, it is also possible to use
Java code to get properties (often from a database)
• faces-config.xml
– <message-bundle>
somepackage.SomeCustomBundle
</message-bundle>
• Java
– Extend ResourceBundle
– Override handleGetObject and getKeys
• Details
– http://stackoverflow.com/questions/9080474/
messages-properties-taken-from-db
Deploy one or more .properties files
– In Eclipse, you put .properties file in “src” folder, and it gets deployed to WEB-INF/classes automatically
• Declare with resource-bundle in faces-config
<application>
<resource-bundle>
<base-name>someFile</base-name>
<var>someVar</var>
</resource-bundle> …
</application>
• Output values using normal EL
– #{someVar.someNameFromFile} for simple values
– h:outputFormat for parameterized values
• Set view’s locale if I18N needed
– Extract it from browser setting or user setting
• We’ll cover user settings in section on event handling
– Automatically loads locale-specific resource bundle
JSF2-Properties-Files.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- For option 2 Mastering JavaServer Faces says a JSF implementation will next "look for a context initialization parameter named javax.faces.application.CONFIG_FILES in the web.xml file for one or more JSF configurations that should be loaded. The value of this parameter is a comma delimited list of context relative resource paths (each starting with /). This particular method is useful when you wish to split up a large JSF application into manageable pieces."
Bingo! Exactly what we're looking for. The text then goes onto suggest on how to do this in your web.xml file with the following example:
<context-param>
<param-name>javax.faces.application.CONFIG_FILES</param-name>
<param-value>
/WEB-INF/faces-config1.xml,
/WEB-INF/faces-config2.xml
</param-value>
</context-param>
http://one-size-doesnt-fit-all.blogspot.com/2007/01/using-multiple-faces-configxml-files-in.html
- There are 2 varieties of user interface events
– Events that start back-end processing
– Events that affect only the format of the user interface
JSF categorizes code that handles these as
action controllers and event listeners
– Action controllers handle main form submission
• Fire after bean has been populated (see previous section)
• Fire after validation logic (see upcoming section)
• Return strings that directly affect page navigation
– Event listeners handle UI events
• Often fire before bean has been populated
• Often bypass validation logic
• Never directly affect page navigation
Event Handlers vs. Ajax
However, Ajax is sometimes even better
– Some of the situations where event handlers apply
result in only a small number of elements changing
– In that case, Ajax often yields a more interactive user
experience
• If you need to update the entire page, use event listeners.
If you need to update only part of the page, use Ajax.
JSF2-Event-Handling.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
<h:inputText value="#{bidBean2.keyword}"
required="true"
requiredMessage="You must enter a keyword"
id="keyword"/></td>
<td><h:message for="keyword" styleClass="error"/></td></tr>
Value of requiredMessage can be an EL expression, so you can use properties files for localized error messages. See tutorial section on properties and I18N.
Writing Your Own Validator
Methods
• Facelets
– For input component, specify method name explicitly
• <h:inputText id="someID"
validator="#{someBean.someMethod}"/>
– Use h:message as before
• <h:message for="someID"/>
Summary
• Validation in action controller
– When validation linked to business logic, or when you are
comparing values of multiple fields
• But, the lowest-level and most tedious of the 4 approaches
• Type conversion (and “required”)
– When it is enough to simply enforce types
(counting non-empty as a type)
• Explicit f:validateBlah tags
– When you are checking one field at a time, and want to
enforce values are in certain ranges or satisfy a regex
• Making your own validator methods
– When you are checking one field at a time, but want to
perform complex tests not built into any of the tags
JSF2-Validation.pdf
http://www.coreservlets.com/JSF-Tutorial/jsf2/
Avoiding repetition in facelets pages
– OOP provides good reuse for Java code.
– But what about facelets code?
• Also want to avoid repeating nearly-identical code there
• Very common to have multiple pages that share the same
basic layout and same general look
Inadequacies of jsp:include
– JSF pages normally eschew JSP tags
– Even if you use jsp:include, it has problems
• No real templates or named sections (ala Struts Tiles)
• Can’t easily pass data to included pages
Template file
– Directly insert content that will be used by all clients
– Mark replaceable regions with ui:insert
• Client file
– Use ui:composition to designate template that is used
– Override replaceable regions with ui:define
– Insert snippets with ui:include
• Relative URLs in templates
– Hypertext links: <a href="#{request.contextPath}/…"/>
– Images: <h:graphicImage name="…" library="…"/>
– CSS: <h:outputStylesheet name="…" library="…"/>
– Scripts: <h:outputScript name="…" library="…"/>
JSF2-Facelets-Templating
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- JSF 2.0 added “composite components”
– Reusable, named chunks of facelets code
– Can pass arguments
JSF2-Composite-Components-1
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Wrapping Up JavaScript GUI Elements: Idea
Motivation
– If you need a rich GUI element (slider, popup calendar,
etc.) that is not already part of your JSF library
Options
– Look at existing component libraries
• PrimeFaces, RichFaces, IceFaces, OpenFaces,
Tomahawk, Trinidad, etc.
– Use an element from jQuery UI, Ext/JS, Dojo, YUI etc.
• But wrap it up so that it can be used like a normal JSF
component.
JSF2-Composite-Components-4
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- f:viewParam lets you associate bean
properties with request parameters
– This introduces several new capabilities
• New tags that navigate via GET instead of POST, and
send parameters along with the address
• Sending data from non-JSF forms to JSF pages
• Make results pages bookmarkable
– This is a new feature in JSF 2.0
Motivation
f:viewParam lets you:
– Make links or buttons that pass parameters to pages
• E.g., you could make different links to the same JSF
but specify colors, languages, or simple variables
Make JSF pages accessible from forms in non-JSF apps
• But the forms would normally need to send simple values,
since you lose the strong association with bean properties
in the forms, and you lose JSF’s validation capabilities
– Bookmark results pages
• Use POST-redirect-GET to expose data needed in results
pages as GET parameters. Can save page in favorites.
• f:viewParam does not let you:
– Make h:form use GET instead of POST
– Access any random JSF page with GET
JSF2-View-Params
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- Defining beans in two places
– JSF backing beans in faces-config.xml
– Spring beans in applicationContext.xml
• Defining beans in one place only• Defining beans in one place only
– All beans in applicationContext.xml
What is Spring?
Core module: dependency injection
Lets you define an XML file that specifies which beans– Lets you define an XML file that specifies which beans
are created and what their properties are
• Simplifies OOP by promoting loose coupling between
classes Also called “Inversion of Control” (IoC)
You are Using JSF Already: Why Use Spring?
JSF already supports dependency injection via the
managed-property element of faces-config.xml
• So why use Spring to do what JSF already does?
You might already have beans set up with Spring from gy ppg
other applications
• And you would like to use them without adding new code
Spring is more powerful– Spring is more powerful
• Spring supports more and better dependency injection
features than does faces-config.xml
You are Using Spring Already:
Why Use New Approach?
Issue
– Normal Spring already supports ways to access beans.
• So why add a new way for JSF?
Reasons• Reasons
– You need to access bean definitions from many places
• With desktop Java apps, you can have a single piece of ppp,y gp
code that instantiates the container and gets beans
– I.e., driver class that instantiates ClassPathXmlApplicationContext
and calls getBean
• With JSF apps, each controller wants access to beans
– But you want to instantiate container once only
– You need additional bean scopesYou need additional bean scopes
• Standard Spring supports singleton and prototype
• JSF apps also want request, session, and application
JSF2-Using-Spring
http://www.coreservlets.com/JSF-Tutorial/jsf2/
- If you using myfaces then you need myfaces-api.jar and myfaces-impl.jar in your classpath, which you can download from http://myfaces.apache.org/download.html
Just use the JAR files which are provided/required by the JSF implementation you choose to use. Just download the implementation and read their own installation/users guide if you don't actually need more JAR files (as dependencies).
As of now there are only two major JSF implementations: Mojarra and MyFaces. The number of JAR files may vary per implementation and even version. Ultimately you need to make sure that you have both the JSF API and JSF implementation (which may exist of 2 or even 1 JAR file, depending on impl/version). MyFaces requires more commons-*.jar dependencies while Mojarra doesn't require any additional dependencies.
Since JSF 2.0, Facelets is bundled with the JSF implementation and has replaced JSP as default view technology.
The jsf-api-xxx.jar contains classes that are under packages java package javax.faces
The classes in this jar are implementation of standard API defined by JSF specification
The jsf-impl-xxx.jar contains classes that are under java package com.sun.faces,
which as the java package indicates, is Sun's own class for JSF implementation.
The javax.faces-xxx.jar actually merges the previous two jar files together.
In the Maven repository, it is under org.glassfish groupId.
You will find both javax.faces and com.sun.faces java package inside.
http://stackoverflow.com/questions/15561352/what-is-the-difference-between-javax-faces-2-1-14-jar-from-jsf-api-2-2-0-m05-jar