JSF – Managed Beans

  • Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a java bean managed by JSF framework.

  • The managed bean contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).

  • Managed beans works as Model for UI component.

  • Managed Bean can be accessed from JSF page.

  • In JSF 1.2,a managed bean had to register it in JSF configuration file such as faces-config.xml.

  • From JSF 2.0 onwards, Managed beans can be easily registered using annotations. This approach keeps beans and there registration at one place and it becomes easier to manage.

Using Annotation

@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
	
   @ManagedProperty(value="#{message}")
   private Message message;
   ...
}

@ManagedBean Annotation

@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case it would be helloWorld.

Another important attribute is eager. If eager=”true” then managed bean is created before it is requested for the first time otherwise “lazy” initialization is used in which bean will be created only when it is requested.

Scope Annotations

Scope annotations set the scope into which the managed bean will be placed. If scope is not specified then bean will default to request scope. Each scope is briefly discussed below.

image

 

@ManagedProperty Annotation

JSF is a simple static Dependency Injection(DI) framework.Using @ManagedProperty annotation a managed bean’s property can be injected in another managed bean.

Advertisements

JSF : Life Cycle

A JavaServer Faces page is represented by a tree of UI components, called a view. During the lifecycle, the JavaServer Faces implementation must build the view while considering state saved from a previous submission of the page. When the client submits a page, the JavaServer Faces implementation performs several tasks, such as validating the data input of components in the view and converting input data to types specified on the server side. The JavaServer Faces implementation performs all these tasks as a series of steps in the JavaServer Faces request–response life cycle.

The phases of the JSF application lifecycle are as follows:

  1. Restore view
  2. Apply request values; process events
  3. Process validations; process events
  4. Update model values; process events
  5. Invoke application; process events
  6. Render response

The normal flow of control is shown with solid lines, whereas dashed lines show alternate flows depending on whether a component requests a page redisplay or validation or conversion errors occur.

JSF-Lifecycle

Note : Life – cycle handles two kinds of requests:

  • Initial request: A user requests the page for the first time.
  • Postback: A user submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request.

Phase 1 : Restore view

In the RestoreView phase, JSF classes build the tree of UI components for the incoming request.

  • When a request for a JavaServer Faces page is made, such as when a link or a button is clicked, the JavaServer Faces implementation begins the restore view phase.

  • This is one of the trickiest parts of JSF: The JSF framework controller uses the view ID (typically JSP name) to look up the components for the current view. If the view isn’t available, the JSF controller creates a new one. If the view already exists, the JSF controller uses it. The view contains all the GUI components and there is a great deal of state management by JSF to track the status of the view – typically using HTML hidden fields.
  • If the request for the page is an initial request, the JavaServer Faces implementation creates an empty view during this phase. Lifecycle only executes the restore view and render response phases because there is no user input or actions to process.
  • If the request for the page is a postback, a view corresponding to this page already exists. During this phase, the JavaServer Faces implementation restores the view by using the state information saved on the client or the server. Lifecycle continues to execute the remaining phases.
  • Fortunately this is the phase that requires the least intervention by application code.

Phase 2 : ApplyRequest values

During ApplyRequest values, the request parameters are read and their values are used to set the values of the corresponding UI components. This process is called decoding.

  • If the conversion of the value fails, an error message associated with the component is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors resulting from the process validations phase.
  • If some components on the page have their immediate event handling property is set to true, then the validation, conversion, and events associated with these components takes place in this phase instead of the Process Validations phase. For example, you could have a Cancel button that ignores all values on a form.

Phase 3 : Process validations

The Apply Validations phase triggers calls to all registered validators.

  • The components validate the new values coming from the request against the application’s validation rules.
  • Any input can be scanned by any number of validators.
  • These Validators can be pre-defined or defined by the developer.
  • Any validation errors will abort the request–handling process and skip to rendering the response with validation and conversion error messages.

Phase 4 : Update Model Values

The Update Model phase brings a transfer of state from the UI component tree to any and all backing beans, according to the value expressions defined for the components themselves.

  • It is in this phase that converters are invoked to parse string representations of various values to their proper primitive or object types. If the data cannot be converted to the types specified by the bean properties, the life cycle advances directly to the render response phase so that the page is re-rendered with errors displayed.
  • Note: The difference between this phase and Apply Request Values – that phase moves values from client–side HTML form controls to server–side UI components; while in this phase the information moves from the UI components to the backing beans.

Phase 5 : Invoke Application

The Invoke Application phase handles any application-level events. Typically this takes the form of a call to process the action event generated by the submit button that the user clicked.

  • Application level events handled
  • Application methods invoked
  • Navigation outcome calculated

Phase 6 : Render Response

Finally, Render Response brings several inverse behaviors together in one process:

  • Values are transferred back to the UI components from the bean. Including any modifications that may have been made by the bean itself or by the controller.
  • The UI components save their state – not just their values, but other attributes having to do with the presentation itself. This can happen server–side, but by default state is written into the HTML as hidden input fields and thus returns to the JSF implementation with the next request.
  • If the request is a postback and errors were encountered during the apply request values phase, process validations phase, or update model values phase, the original page is rendered during this phase. If the pages contain message ormessages tags, any queued error messages are displayed on the page.

Process Events

In this phase, any events that occurred during the previous phase are handled.

  • Each Process Events phase gives the application a chance to handle any events (for example, validation failures) that occurred during the previous phase.

JSF : Architecture

 

A JSF application is similar to any other Java technology-based web application; it runs in a Java servlet container, and contains

  • JavaBeans components as models containing application-specific functionality and data

  • A custom tag library for representing event handlers and validators

  • A custom tag library for rendering UI components

  • UI components represented as stateful objects on the server

  • Server-side helper classes

  • Validators, event handlers, and navigation handlers

  • Application configuration resource file for configuring application resources

JSF Architecture

There are controllers which can be used to perform user actions.UI can be created by web page authors and the business logic can be utilized by managed beans.

JSF provides several mechanisms for rendering an individual component. It is upto the web page designer to pick the desired representation, and the application developer doesn’t need to know which mechanism was used to render a JSF UI component.

JSF : MVC Design Pattern in JSF

JSF technology is a framework for developing, building server side User Interface Components and using them in a web application.JSF technology is based on the Model View Controller (MVC) architecture for separating logic from presentation.

MVC Design Pattern in JSF

MVC design pattern designs an application using three separate modules:

image

Purpose of MVC design pattern is to separate model and presentation to enable developers to set focus on their core skills and collaborate more clearly.

Web Designers have to concentrate only on view layer rather than model and controller layer. Developers can change the code for model and typically need not to change view layer.Controllers are used to process user actions. In this process layer model and views may be changed.

JSF : Benefits of JSF

JSF reduces the effort in creating and maintaining applications which will run on a Java application server and will render application UI on to a target client.JSF facilitates Web application development by

  • proving reusable UI components

  • making easy data transfer between UI components

  • managing UI state across multiple server requests

  • enabling implementation of custom components

  • wiring client side event to server side application code

JSF : What is Java Server Faces (JSF)

A complete web application requires a web framework to generate HTML pages, receive user input, and manage the navigation flow. The consensus among most web developers is that a Model-View-Controller (MVC) architecture is the best for web frameworks. In an MVC framework, the controller takes user input and decides which view to show next; The view renders the HTML page for the browser; The model encapsulates data captured from the web form and to be displayed on the web page.

20110510-jsf-logo.tiff

Shield developers from the messy HTML / JavaScript / CSS details

Enterprise Java developers have long embraced ORM solutions, which automatically generate relational database access code from the data model component in the application. JSF is the “ORM solution for the web layer”. It automatically generates HTML / JavaScript / CSS code from well formed UI components.

A JSF application primarily contains two types of components — both are easy to use and conforming to the POJO philosophy.

  • A JSF page is composed of XML tags. Each tag element corresponds to a UI component in JSF. As a web developer, you do not need to deal with the HTML markup or JavaScript details, as they are all generated from the JSF component tags. Since each UI component is self-contained and has well-defined behavior (i.e., it understand how to render itself and how to handle its data), JSF provides a very POJO-like experience for developing web UI.

  • Dynamic data on JSF pages and forms are modeled in POJOs known as JSF backing beans. The backing bean lifecycle is managed by the JSF server. For instance, a backing bean can have a session scope to track a user session. A backing bean can be dependency injected into another bean via an XML configuration file, and it can be injected into a JSF UI component via the JSF Expression Language (EL). The backing bean also provides the integration points between the web UI and the EJB3 business components.

The componentized UI and POJO data model make it easy to support JSF in IDE tools. In fact, many Java IDEs now support drag-and-drop UI designers for JSF. The JSF component model also allows third party vendors to develop and sell reusable UI component libraries. Those component libraries make it easy for server-side developers to take advantage of the latest browser technology without the need to mess with JavaScripts and such.

The JSF request model is powerful and easy to extend. Technologies like Facelets and Seam have been developed on top of JSF, providing even richer development environments. While competing frameworks all have nice features, JSF seems to be the easiest to extend. We expect even more innovative extensions in the near future, clearly making JSF the framework of choice for most EE projects.

As being a MVC (Model-View-Controller) framework, JSF provides the FacesServlet as the sole request-response Controller. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for View and a Javabean class as Model. The JSF components are been used to bind the view with the model (such as your ASP.NET web control does) and the FacesServlet uses the JSF component tree to do all the work.

JSF is a component based MVC framework which is built on top of the Servlet API and providescomponents in flavor of taglibs which can be used in JSP or any other Java based view technology such as Facelets.

There are many web frameworks available. JavaServer Faces (JSF), is the standard Java EE web framework . You will find it similar/alternative if you might be knowing about any of these below web frame work:
Struts
WebWork (Struts Action2)
Shale (Struts-JSF)
SpringMVC
Wicket
Tapestry
Stripes
Flex
Open Laszlo

 

Botton line : JSF is the “ORM solution for the web layer ie Java based web UI framework.”