Core JavaServer Faces Chapter 2 Notes..

Lets see!

Definition of a Bean

In the context of JSF, beans store the state of web pages. Bean creation and manipulation is under the control of the JSF implementation. JSF does the following:
        • Creates and discards Beans as needed.
        • Reads Bean Properties when displaying a page.
        • Sets Bean Properties when a form is posted.

What is a Bean Property?

A Bean Property is any attribute of a Bean, that has:
    • A name
    • A type
    • Methods for getting and / or setting the value.

In many situations, getter and setter methods simply manipulate an instance fields. However they may equally carry out some operations such as validation or converstion and so on.

A Bean may have other methods beyond property getter / setters.

Backing Beans

Sometimes it is convenient to design a bean that contains some or all component object of a web form. Such a bean is called a Backing Bean for the web form.

Message Bundles

When you implement a web application, it is a good idea to collect all message strings in a central location. This process makes it easier to keep messages consistent and, crucially, makes it easier to localize your application for other locales.

An example implementation is here.

When you localize a bundle file, you need to add a locale suffix to the file name: an underscore followed by the lowercase, two-letter ISO-639 language code.

Message Bundle files are not encoded in UTF-8! Unicode characters beyond 127 are encoded as \uxxxx escape sequences.

Messages with Variable Parts
currentScore = Your current score is: {0}
 
<h:outputFormat value="#{msgs.currentScore}">
    <f:param value="4"/>
</h:outputFormat> 


Application Locale

1) Let the browser choose the locale. Set the default and supported locales in WEB-INF/faces-config.xml:
<application>
    <!-- Localisation configuration -->
    <locale-config>
        <default-locale>en</default-locale>
        <supported-locale>tr</supported-locale>
    </locale-config>
</application>
When a browser connects to your application, it includes an Accept-Language value in the HTTP header. JSF reads this header and finds the best match among the supported Locales.

2) Modify it based on the users preferred locale. Here is an example. The entire page must be placed between <f:view> tags!

Injecting Managed Beans in JSF

Here is an example:
@ManagedBean
@RequestScoped
public class Bar {
 
    private final String barMessage = "Bar Message!";
 
    public String getBarMessage() {
        return barMessage;
    }
}
 
@ManagedBean
@RequestScoped
public class Foo {
 
    private final String fooMessage = "Foo message!";
 
    @ManagedProperty(value = "#{bar}")
    private Bar bar;
 
    @SuppressWarnings("unused")
    public void setBar(Bar bar) {
        this.bar = bar;
    }
 
    public String getFooMessage() {
        return fooMessage + " " + bar.getBarMessage();
    }
}
A setter must be found!

When you set a managed bean as the property of another, you must make sure that their scopes are compatible. The scope of the property must be no less than that of the containing bean.


Bean Life Cycle Annotations

Using the @PostConstruct and @PreDestroy annotations, you can specify the Bean methods that are automatically called just after a bean has been constructed and just before the Bean goes out of scope.
public class MyBean {
    @PostConstruct
    public void initialize() {
        // initialization code
    }
    @PreDestroy
    public void shutdown() {
        // shutdown code
    }
}

Expression Language Notes

Consider the following code:
<h:inputText value="#{user.name}"/>
When the text field is rendered, the expression user.name is evaluated and the getName method is called.
During decoding, the same expression is evaluated and setName method is called.

Using Brackets 
These have all the same meaning:
    • a.b
    • a["b"]
    • a['b']

One can use the brackets for:
    • When accessing an array or map
    • When accessing a String that contains dot: "#{msgs['hello.world']}"

Evaluating the Expressions for Collection Objects

Calling Methods and Functions
Example:
#{stockQuote.price("ORCL")}
Overloaded methods are not supported. The bean must have a unique method with the given name.
     
JSTL functions library can also be used by including the namespace as follows:
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:fn="http://java.sun.com/jsp/jstl/functions">

Implicit Objects
There are a number of predefined objects, called implicit objects in the JSF Specification.

Example:
#{header["User-Agent"]}
will print for me:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

If the initial term is not one of the predefined objects, the JSF implementation looks for it in the request, view, session, and application scopes, in that order.

In particular, all instantiated managed beans are located in these scope maps. If the search is still not successful, the JSF implementation attempts to construct a managed bean or a resource bundle with the given name.
     
Example:
Given:
@ManagedBean
@SessionScoped
public class UserBean {
}
and:
#{user.password}
The term user is not one of the predefined objects. When it is encountered for the first time, it is not an attribute name in request, view, session, or application scope. Therefore, the JSF implementation locates the managed bean with name user and calls the constructor with no parameters of the corresponding class. Next, it adds an association to the sessionScope map. Finally, it returns the constructed object as the result of the lookup.

When the term user needs to be resolved again in the same session, it is located in the session scope.
 
Composite Expressions 
A limited set of operators can be used inside value expressions:        
  • Arithmetic operators: +, -, *, /, %. The last two operators have alphabetic variants:div and mod.
  • Relational operators <, <=, >, >=, ==, != and their alphabetic variants lt, le, gt, ge, eq, ne.
  • Logical operators &&, || and their alphabetic variants and or not.
  • The empty operator. #{empty aNullReference} is true if aNullReference is null, an array or String of length 0, or a Collection or Map of size 0.
 
Method Expressions
Example:
<h:commandButton action="#{user.checkPassword}"/>



Method Expression Parameters
Example:
<h:commandButton action="#{formBean.move(-1)}"/>
Here, the method must be declared with a parameter:
public String move(int amount);