0

I have a helper class, which is neither a stateful managed bean, nor a stateless EJB, nor an entity mapped to a table via JPA or Hibernate. It is simply a collection of static methods that do simple things like return date formats and similar.

Given that, in order for a Java class to be visible inside a JSF, that class must be annotated in a way that the container assigns as visible to JSFs, is there a way to annotate a helper class that does not match any of the standard JSF visible categories so that it becomes visible? An alternative, of course, is to have a conduit method in the managed bean that passes the call from the JSF to the helper class but I prefer not to clutter my managed bean if I can call it directly from the JSF. I understand that doing this with a stateless EJB from a JSF would be considered an anti-pattern but the methods in the class I wish to use are all very simple and non-transactional.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
amphibient
  • 25,192
  • 44
  • 130
  • 215

1 Answers1

3

Mark your class as @ApplicationScoped. Make sure it has a public no-arg constructor and that this class doesn't have state and its methods are thread safe.

E.g.

Managed bean (pure JSF)

//this is important
import javax.faces.bean.ApplicationScoped;

@ManagedBean
@ApplicationScoped
public class Utility {
    public static String foo(String another) {
        return "hello " + another;
    }
}

CDI version

//this is important
import javax.enterprise.context.ApplicationScoped;

@Named
@ApplicationScoped
public class Utility {
    public static String foo(String another) {
        return "hello " + another;
    }
}

View

<h:outputText value="#{utility.foo('amphibient')}" />
Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
  • ApplicationScoped. from `javax.enterprise.context` or `javax.faces.bean` ? I tried both and I'm still not seeing it in the JSF, not showing in the drop down in JBoss Dev Studio – amphibient Jul 14 '15 at 16:07
  • i can't find a way to actually give a name by which to call it in the JSF. e.g. in a managed bean, it would be `@ManagedBean(name="myManagedBean")` and then to call `getFoo` in the JSF, I would do `myManagedBean.foo`. how do I either refer to a non-nicknamed class or assign a JSF name to it ? – amphibient Jul 14 '15 at 16:24
  • OK. I didn't get the `@ManagedBean` part. – amphibient Jul 14 '15 at 16:30
  • it works. i used `javax.enterprise.context`. we do use CDI and JSF, i didn't know the terms were mutually exclusive – amphibient Jul 14 '15 at 16:38
  • one more question: how does `@ApplicationScoped` make the bean different from other regular backing beans that are not annotated as that ? – amphibient Jul 14 '15 at 16:39
  • The terms are not mutually exclusive, but the annotations are. – Luiggi Mendoza Jul 14 '15 at 16:39
  • 1
    Answer updated to show the difference in annotations between JSF and CDI. – Luiggi Mendoza Jul 14 '15 at 16:42