jsfmanaged-beanfacescontext

JSF 2.1 - getting FacesContext strategy


I am developing webapp where my MVC controller is JSF 2.1. I have several methods that are based on

FacesContext.getCurrentInstance()

I use this to

examples:

public void addInfoMessage(String title, String description){
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,title, description));
}

and

public void putFlashMessage(String code, String value){
    FacesContext.getCurrentInstance().getExternalContext().getFlash().put(code, value);
}

etc.

I'm just wondering where is proper place to put this methods if I use this on every single managed bean? I consider two options:

a) create class "JSFUtils", where all method are public and static

b) create super class "ManagedBean" with no declared scope and no declared @ManagedBean annotation, but with these public methods. Every managed bean should be child of these class so it will have inherited these methods.


Solution

  • An utility class is the recommended approach. Instead of reinventing your own, you can use an existing JSF utility library, such as OmniFaces which has Faces and Messages utility classes for the purpose.

    String foo = Faces.getRequestParameter("foo");
    Messages.create(summary).detail(detail).add();
    Messages.addGlobalInfo(summary); // Without detail.
    Faces.setFlashAttribute(key, value);
    

    You can indeed also abstract it away as a "super bean", but this is not reusable and you would keep repeating yourself in every JSF project. Also, a class can extend from only one class. So if your bean happen to need to extend from another super class, then you're lost.