EJB Injection in JSP with Java EE 7

User suexec asked ##java about accessing an EJB from a JSP template.
User dreamreal (i.e., your author) put together a simple application (rather imaginatively called “suexec-war” ) to explore the possibilities. The application was built from Adam Bien‘s minimalistic Java EE 7 Maven archetype, deployed into Wildfly 10.0.
It turns out that to the best of my understanding, injection of an EJB into a JSP is simply unsupported. The JSP can use JNDI to acquire an EJB via JNDI (see source) but the CDI injection never worked.

Next, I wrote a simple servlet (called, of all things, TestServlet.java). Here, the @EJB MyEJB ejb worked like a charm.

To render, I used the Handlebars template library just for kicks; Freemarker (or even JSP itself) would have worked just as well, but I wanted to play with something different.
The process would have been the same no matter what templating library was chosen: you’d take the values you wanted to render and store them somewhere such that the rendering engine could access them. In my case, I could have built a composite object (or even asked Handlebars to call the greet() method itself, using the ejb value) but I was aiming for simplicity rather than optimal behavior, following whaley’s “Make it work, make it pretty, make it fast” principle (from “Suffering-oriented programming” )- this is rough code, meant to serve more as a smoke test than an actual example of a great application, so I left off at “make it work,” leaving even “make it pretty” to others.
Comments and improvements welcomed.

Leave a Reply