Question

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

  • put/retrieve values from Flash scope
  • add messages on view
  • get request params map

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.

Was it helpful?

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.

OTHER TIPS

I would recommend a utility class for the purpose simply because you allow the flexibility to extend other useful classes, such as those that have some common logic that you'd like to share across other beans.

Having said that, a JSFUtils class can grow quite cluttered with time with many many methods and can become very unmanageable. It would be better to categorize the util methods and put them in separate static utility classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top