Getting Entitymanager/EJB inside a @FacesConverter/Validator of a WAR-packaged app
I have a JavaEE6-application running on Glassfish v3.0.1 with EJB 3.1 (app is packaged as WAR), and all my EJBs are @LocalBeans. Currently, i'm writing a FacesConverter for use in JSF2, in which i need the EntityManager to get an Entity back from an id.
Now i wonder, which is the best and cleanest way to get the Entitymanager inside the FacesConverter, now that we are on JEE6? Or can i even access an EJB through the Expression Language? And Weld/CDI doesn't work inside a FacesConverter, or开发者_开发问答 does it?
@FacesConverter(value="subscriptionListConverter")
class SubscriptionListConverter extends Converter {
public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
var id:Long = Long.parseLong(value);
// How to get the entitymanager?
return em.find(User.getClass, id);
}
public String getAsString(ctx:FacesContext, comp:UIComponent, value:Object) {...}
}
Sorry i hope this is no duplicate, but most cases i saw where slightly different and didn't help me much.
I am also using manual lookup but I've created an abstract class implementing Converter interface, to extend to different Converters and have a method to get EJBs. To reuse it in different apps I've done the following to get Appname and web module name:
abstract public class Converter implements javax.faces.convert.Converter
{
public Object getManager(String jndiName) throws NamingException
{
ServletContext servletContext = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
Context env = new InitialContext();
String aname = (String)env.lookup("java:app/AppName");
if (aname == null || aname.length() == 0 || servletContext.getContextPath().equals(aname)) //FIXME If deploying war inside an ear, appname equals module name, won't work.
return env.lookup("java:global/" + aname + "/" + jndiName);
else
return env.lookup("java:global/" + aname + servletContext.getContextPath() + "/" + jndiName);
}
}
Ok after some trying around i successfully got an EJB with a manual lookup:
Context ctx = new InitialContext();
UserEJB userEJB = (UserEJB) ctx.lookup("java:global/teachernews/" + UserEJB.class.getName())
Looks okay, but anyway, if there are some other interesting approaches, feel free to post them.
I've just used @EJB to inject them into my converters.
精彩评论