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.

(KCDC) Kansas City Developers Conference 2015

Standard

The following presentation was given at kcdc.info on June 25, 2015

Topic: Building a more responsive design with JSF + Bootstrap 3

Modern web design has placed an emphasis on lightweight, responsive oriented design. Utilizing libraries such as Bootstrap 3 CSS / Javascript as well as font awesome one can create elegant designs, quickly and efficiently. We’ll dive into some best practices I’ve extract from solving real world problems when merging JSF with Bootstrap 3. Areas of emphasis would be error handling, responsive modals, and utilizing HTML5 data attributes to make job easier.

I would like to thank all the people that attended my presentation. It was a great opportunity to be around so many other excellent developers.

Presentation slides can be found online here (KCDC Presentation).

 

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.

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.

 

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

How to use conditional stylesheets or javascript with JSF

Standard

A annoying part of JSF is that it will strip out all of your conditional statements. These conditional references are needed for IE bug fixes 99% of the time. The solution is a simple hack using the outputText component. This will treat the html entities as strings and convert them.

For example this outputText will render the html5shiv cdn.

Results

Now once rendered the browser will be able to correctly interpret your conditional statements.

JSF Bootstrap style validation

Standard

In this example, I provide a solution to the problem of needing to display errors specific to a form on a page. This solution was developed due to the need to have multiple forms on the same page, while maintaining a simple way to display errors belonging to there ID’s. The point of this article is to show you how to make a simple profile page for submitting a first and last name that is validated.

The most important class is the FacesUtil.java which provides methods for queuing / retrieving facesMessages based on each inputs DOM id. I have defined 3 types for displaying errors based on the bootstrap 3 message classes (success, warning, and danger).

Interfacing with the FacesUtil.java class is a viewScoped bean called viewProfile.java. This bean extends the methods of the FacesUtil class and is where our submit action lives. It also defines the first and last name that will be submitted from our profile page.

The final page is the actual JSF view. It is simple to display all errors from the faces util class through the viewProfile bean. On inputText I have defined a validateLength and a requireMessage. These have been set to required. If those validation requirements are not met, the error will be displayed in the panelGroup block below. The FacesUtil class has the logic to grab all manually queued messages as well as messages queue from validation inputs.

 

Omitted are the bootstrap CDN’s libraries. A full working version of this code can be found on Github.