Inversion of Control (IoC) with JSF

Standard

Power of containers

Flash back to the early 2000s and this article would be focused on POJOs and how they are transforming the way we organize our logic. But luckily, its 2015 and we don’t need concern ourselves with managing the state of our objects when developing server-side applications. Most likely you are using a version of inversion of control already in your application without knowing it.

Below is a simple example of JSF 2.2 using CDI for bean injection.

To understand the key concepts associated with IoC, consider the above example. The annotation @SessionScoped is providing a length of time for this container managed class to hang around. By definition a session scoped bean maintains its state across more than one JSF view. Since this is the user that is logged onto the site, this bean must be accessible for the duration of them browsing the application. CDI has implemented the definition of a session scoped bean using IoC facets.

There are 3 core key facets of IoC.

  • Manages constructor injection of managed objects – The developer does not need to explicitly instantiate the object. The container would use a default constructor to invoke the object. It should be noted that overriding the default constructor in IoC is possible given unique situations.
  • Dependency Handling – Certain objects can depend on each other to function. The container must have the logic to handle cyclical dependencies.
  • Life cycle and Configuration – Customization of the lifecycle must be provided through annotation or configuration (xml).

Inversion of control (IoC) is a concept that has been implemented in various containers/frameworks such as Spring, JSF, Google Guice, or PicoContainer. These frameworks provide the abilities similar to the above example. Using a framework eliminates the need to write large amounts of boilerplate code. For example; Writing a class to handle application, session, and view scoped logic.

What would it be like without IoC?

Simple answer is… a large headache. Imagine you have a web application. You have to manage a single class that is used by the application. Lets call this our applicationClazz. Now when each new user access the application we need to store there current application context. This user context would have to be stored in our applicationClazz. Then to add functionality, lets assume the site has a login page and stores information in a loginClazz. This login page is specific to each individual user context. So for each user that is using the application, the applicationClazz would have to maintain a map of all the loginClazz’s and maintain an association to the current user context. To make things even more complicated consider how difficult it would become to clean up and managing this application map if you had 20, 50, or 100 classes on your application that had different lifecycles. This is why we use IoC, to do all our heavy lifting.

CDI or Managed Property with JSF?

Prior to JSF 2.0 the annotation @ManagedProperty was widely used. Now mostly @Named is used which is context dependency injection (CDI). Both have support similar life cycles.

The following are a list of the most common CDI scopes used, there duration, and a example use case.

Session Scoped – User’s interaction lasts across multiple HTTP requests. Often used to store a logged in users information for the duration of there time on the site.

Request Scoped – User’s interaction lasts across a single HTTP request. This scope would be best suited for pages that require little to no ajax/form interaction. An example simple example would be a page that displays the date / time. If a ajax request were implemented to refresh the content. Since it is request scoped, a new bean would be created for each ajax request.

Application Scoped – Contents are shared across all users interacting with the web application. Let’s assume you have a dropdown list that will always have the same values no matter the user. The best solution would be to put those values into a application scoped bean so that they are alway sin memory, improving performance.

A Short Summary

The most important thing to take away from this article is; IoC is your friend. It does a lot of the heavy lifting managing classes. CDI give you the tools to quickly create applications using sesssion, request, and application scoped beans. Without it much of your time would be spent managing lifecycles.

Death to the back button in JSF

Standard

The browser back button is notorious for being the most hated browser feature by developers. It posses many design challenges and considerations. This article will cover a few approaches to handling the browser back button, as well as highlighting a way to create your own within a JSF application.

Stateful vs Stateless

When laying out your applications workflow, it is smart to consider how you want the application to flow and look to the end user. In a stateful application you attempt to store as much data in the backing beans, whereas with a stateless approach you load data as pages change. In JSF you have access to different kinds of managed beans. Some types work better for different implementations. Using view scoped and request scoped for a more stateless approach, whereas it would be smarter to use conversation scoped or session scoped for a more stateful approach. Each have there benefits and drawbacks.

Start by determining the applications purpose, this will help when selecting which type of bean to use. For example; when developing a search feature that spans multiple tables in various databases it may become inefficient to load the search results over again if the user presses the back button. Thus, a more stateful scoped bean (conversation scoped, or session scoped) would be smarter choice.

Consider the following workflow:

userSearch.xhtml -> finds a user and clicks -> userDetail.xhml

In a typical stateful workflow we could manage this entire page navigation using a conversation or session scoped bean in JSF. The data that is returned from the user search limits the users content to be shown on the user detail page. It only requires one backing bean to between both pages.

Benefits of a Stateful approach:
  • Additional security requirements are not needed since the user id is hidden.
  • No need to load data again in between views
  • Routes can easily be managed in backing beans using explicit routing
Drawbacks of a Stateful approach:
  • Backing beans can become cluttered
  • Stale data may become a issue
  • Pages are not bookmarkable (important in modern web applications)
  • Relies heavily on POST commands to navigate which is not search engine friendly
  • Memory usage can become an issue with larger / high traffic sites
A better stateless approach

Let’s continue to look at the following workflow, but with a different way to implement it. For this case I am going to assume that the userSearch is efficient.

userSearch.xhtml -> finds a user and clicks -> userDetail.xhml?id=123

Notice the “id?=123” has been added to the user detail page. This represents the id of the user that is expected be loaded. With a stateless implementation the user search page and the user detail page have no knowledge of each other. They would in fact be completely separate backing beans, most likely viewscoped. When the user is shown a list of search results, those links are generated using implicit routing and rendered to the DOM. Hovering over the link would show you the full url path. No need to hit a backing bean to determine routes like when using the stateful approach. The route is predetermined. This is one of the huge benefits to creating views that are stateless.

Benefits of a Stateless approach:
  • Pages are bookmarkable
  • Data is never stale
  • Links do not have to rely on backing beans, they can be generated on the page, SEO friendly
  • Less of a memory hog per session
Drawbacks of a Stateless approach:
  • Have to consider security implications when exposing id’s in the URL.
  • If performing heavy calculation, could hurt server performance.
Stateless with the back button

But how do we handle the back button in JSF applications? Designing your application to use stateless beans enables the ability to bring back the back button into your JSF application.

A typical enterprise application built in JSF will cripple if the back button is pressed. In fact a lot of developers have gone as far as building there own stateful back button to display on the page. This back button functions just like the browser back button, but has additional knowledge to control the stateful views. All of this is not necessary if your views are stateless.

It is my opinion that you should never give JSF too much control over the browser. If you have to implement your own back button within your application, do it so with stateless views. Stateless views by design should all have unique URL’s which you can track. Simply add a preRender event each JSF page which calls this BrowserHistoryController. This controller maintains a page stack of all url’s visited. It has a small amount of intelligence to handle users switching between pressing a on page back button, and the browser back button.

On any of your xhtml pages that you want tracked

Creating your own back link

BrowserHistoryController.java

Use this controller in combination with stateless views and the browser back button should no longer be a issue when coding for your application.

Alternative to p:defaultCommand

Standard

Using the standard JSF h:commandLink has a limitation when wanting to submit the form when the enter button is pressed. This solution uses the javascript keyCode keyboardevent built into browsers. When keyCode 13 (or enter key) is pressed the h:commandLink (which renders a <a> tag) is submitted. This will call its action that has been attached to the component.

This solution is most useful when the Primefaces defaultCommand component is not available.

Calling Bootstrap 3 modal from JSF

Standard

Dialogs or modals can be used in JSF to create more dynamic, and interactive pages. This solution will show how to call a Bootstrap 3 modal from both a JSF commandLink, and a Primefaces commandLink. Each example uses a formId to update the modals content.

JSF h:commandLink

JSF implementation uses an onclick event, which shows the modal, then updates the form inside the modal. While the order of execution can be problamatic in that you could show stale data in your modal for a brief second; this solution will work for most cases.

It also should be noted that using the h:commandLink component requires a backing bean action.

Primefaces p:commandLink

The Primefaces component library has expanded the attributes available in the p:commandLink.  This functions the same as the h:commandLink, but uses less code to accomplish the same task.

Bootstrap modal

The modal is straight forward. A p:commandLink is used to close the modal, and a form is wrapped around all important content that needs to be updated.

Self managing your own modals may be more work than using a prebuilt component like primefaces dialog. But the benefit is that the modal is responsive, and you still have full control over the design.

Implicit vs Explicit navigation in JSF

Standard

The use of navigation cases in JSF is somewhat subjective. This article will briefly discuss the differences, advantages, and disadvantages between implicit vs explicit navigation

Explicit Navigation

Navigation prior to JSF 2.0 required the use of explicit navigation cases. This means you would have to place all navigation rules in a “faces-config.xml” file. Take for example the following navigation rule:

This example above could be used in JSF 1.2 to redirect from step1.xhtml to step2.xhtml. While the following implementation is simple, it fails to address many issues that can arise when developing larger applications.

What are the drawbacks of explicit navigation?

  1. Changing of file names can result in outcomes going to pages that do not exist
  2. A larger overhead especially if your application has complex conditions. This is due to it having to parse the XML to match the result from the action method
  3. Using JSF 1.2 meant navigation rules use a POST for page to page navigation which makes for a horrible user experience. Pages would not be bookmarkable; thus have bad SEO. Note: JSF 2.0 you can specify the <redirect /> attribute to a navigation-case to force a page redirect.

What are the benefits?

  1.  Only one location to find all your rules for navigation; no hunting through backing beans.
  2.  IDE has tools to draw the rules in a GUI. Gives you a visual of your available workflow.

Implicit Navigation

This advancement in JSF 2 made it so there was no need to declar navigation rules. Instead the outcome can be placed in the action attribute. JSF has the logic to find the correct view id. There are 2 ways to use implicit navigation.

Specifying a outcome in a JSF page

This solution is straight forward, you can specify the page name you wish to navigate to. The “xhtml” extension will automatically be appended.

Another option would be to use a h:link would use a get request to invoke a redirect

Specifying a outcome in a Backing Bean

The JSF page calls a backing bean that has a outcome.

Backing bean has a method which returns a string which is the outcome.

What are the drawbacks of implicit navigation?

  1. Your business objects / backing bean logic becomes tied together, and can get messy
  2. Moving pages around can cause a lot of maintenance to update implicit routes.

What are the benefits?

  1. No hunting through a cluttered xml file to find navigation cases.
  2. Less overhead when looking up the outcome for a action.

Why checkboxes in forms are emulated

Standard

If you have ever investigated the Primefaces datatable selection component you will find that the check boxes are not true html checkboxes but emulated with images. The code that is generated by the component looks similar to this.

Why isn’t it making true HTML checkboxes?

The reason for this is implementation all has to do with caching. When a check box is formed in JSF or any other language for that matter it is given a name. If you were to use a JSF datatable and add a checkbox to each row with the same name it would generate the following in each row:

The issue with this is that these names can be reused. If you were to check myForm:0 , then perform an ajax event that removes the selected checkbox item from the list. Then browser would have no recognition of the item being removed. The browser cache will still believe that myForm:0 is checked. This is why the solution multiple checkboxes on the page is to emulate then with CSS.

What if I have to use true HTML checkboxes?

If you MUST use real input checkboxes then your solution is to disable caching on your browser. This can be accomplished using a web filter and modifying response headers.

Bootstrap3 with JSF error handling

Standard

JSF applications often get called ugly, or cookie cutter. The over use of the components and built in CSS creates the standardized look, but lacks flexibility. Using Bootstrap 3 CSS in combination with JSF attributes you can create a modern look. Take for example this salary sample salary calculator program which leverages JSF components.

Bootstrap 3 + JSF

The following code is used to create the amount input area.

This technique uses bindings to get the validation state of the inputText component. More information can about component bindings can be read on my other article “What is a JSF component binding? How can I use it?“. By intermixing both JSF + Bootstrap you can see how simple it is to give your app a modern look.

 

JSF detect session timeouts with web filter

Standard

When working with JSF 2.0 you will encounter a situation in which the user’s session times out and ajax requests fail. The response on a ajax request will be a viewExpiredException. However, the root cause is the session has expired. They are essentially stuck on the page and are forced to reload.

The solution:

Using a WebFilter the user can gracefully be redirected to a view expired exception page. This solution is accomplished by checking if the users session is valid, and if the context path is within our required conditions, finally if it is a ajax request it overwrites the default JSF response with our own custom xml response that tells the browser to redirect to the view expired exception page.

Note: This fix is required due to a bug that is set to be resolved in JSF 2.3 release: https://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-790

Primefaces render kit html5 attributes

Standard

When using JSF 2.0 / 2.1 the need for using passthrough elements may occur. However, the passthrough element library is not compatible until JSF 2.2. The following solution uses a custom renderer so that primefaces 5.x can implement HTML5 attributes that you define.

Define your attributes

This first class is use to define which attributes we want to be able to pass through. The static string attributes is the name of these attributes.

The method above called writeAttributes does exactly what means. It writes the attribute(s) pass on the UIComponent to the current facesContext. The attributes that it is checking for are those of which you have defined.

You can add as many attributes to the array as needed. Make sure the attributes you do add are not already apart of the primefaces existing component, otherwise the values would be rendered twice.

Create a inputText renderer

To utilize the class above it requires extending the InputTextRenderer class in Primefaces. By default you must override the encodeEnd method. This is where all the magic happens. The method starts by calling the Html5DataAttributes class above. That writes out our custom attributes, it then concludes by calling the classes super. That assures that the existing component attributes in Primefaces will still be rendered.

It should be noted that this is specifically only for the p:inputText component. You can create more renderers as you need them. Ex: CommandButtonRenderer

Register the renderer class

The last step is to tell primefaces where the new render class is located. This is accomplished by places the following in your faces-config.xml.

The render-type is the base class that primefaces uses for rendering the component. The component-family is the location of all similar components. The render-class is the new class we have created to handle inputText rendering.

How do I use it?

It is pretty simple, when calling p:inputText specify your custom attribute

What is I have JSF 2.2? 

Then don’t waste your time on what was described above. You can use the built in passthrough library

Read more on javadoc

What is a JSF component binding? How can I use it?

Standard

One of the more flexible features of Java Server Faces is the ability to use bindings within a view. Most developers omit the binding attribute and rely on a component libraries magic to display errors to the end user. Using the JSF binding component it is possible to specify the binding view component name for the UIComponent in the java backing bean. This binding refers to an instance of UIComponent in the EL scope allowing you to access certain properties #{mybinding.clientId}, #{mybinding.value},  #{mybinding.valid},  #{mybinding.submittedValue}

For example, lets assume you have a selectOneMenu with a list of items. These items are U.S states, then below you have a inputText area where the end user enters his/her city. We do not want to allow them to enter a city that is not in a state.

The problem can be solved using bindings. Consider this solution that binds the selected state value to the city entered. When submitted the validator will have access to both components.

The View

Backing validator

Using bindings as described provides a solution for more complex validation requirements.

Using bindings with Bootstrap 3

Arguably the most popular css library out is Boostrap 3. It provides a sleek look to web pages. Using component bindings you can easily marry JSF with Bootstrap CSS. This is because components have a isValid EL expression attached to them.

For example lets assume you have a inputText that requires a min length of 4 and a max of 6. If outside of that requirement you want the field to be marked as invalid.

To highlight invalid fields use the binding component together with a form-group. The form-group has a has-error CSS class that will highlight the field inside. Once the inputText validation fails and refreshes the screen it will call the EL expression #{name.valid} and render the has-error class.

Whats the difference between #{mybinding.value} and  #{mybinding.submittedValue}?

This can be answered by understanding that the order of components matters. JSF will process your components in the order they appear in the view. The backing javascript for JSF does this. So for example if I was to swap the order of my state / city example so that the selectOneMenu came after the city inputText I would need to use the bindings submittedValue as ordering would cause the binding to be empty on the validator.