//fix this /
Hint: Check the
HttpServlet API in
the Java EE 6 API.
In the last issue, Arun Gupta, a Java
evangelist at Oracle, posed a challenge about the
CDI specification and asked readers for a fix.
2 THE CODE
The correct answer is #2: “beans.xml” is required
to enable injection. The CDI specification requires
Consider the following piece of code to have database access
within a Servlet:
“beans.xml” in the WEB-INF directory in order for bean injection
to work. So even though the code is fine, a missing file did not
allow the EJB injection to go through.
@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {JAVA IN ACTION
@PersistenceContext
EntityManager em;
And now, for Guptas latest challenge.
1 THE PROBLEM
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
// Invoke methods on Entity Manager
}
}Java EE 6 allows you to create Web applications very
3 WHAT S THE FIX?
easily using annotations on POJOs. A POJO can be
Is this code guaranteed to work in a multithreaded environment?
easily converted to a Servlet by adding @WebServlet
1) Of course. All the samples are written this way.
ABOUT US
and extending HttpServlet. A POJO becomes a JPA
2) No. Servlets are re-entrant, and EntityManager is not thread-
safe. Instead inject as
bean by adding @Entity. Each method of a Java class
@PersistenceUnit EntityManagerFactory em;
becomes implicitly transactional by adding @Stateless.
and then get EntityManager within the doGet() method.
Following the convention-over-configuration paradigm,
the deployment descriptors are optional for most of the
3) Database access in Servlets must be done through EJBs only. The
correct way is to move the database code in an EJB, inject the
EJB in this Servlet, and invoke methods on the EJB.
common cases.
4) EntityManager injection will not work in Servlets. Instead use
Persistence.createEntityManager to obtain EntityManager in the
doGet() method and then invoke operations on it.
blog
GOT THE ANSWER?
PHOTOGRAPH BY MARGOT HARTFORD
ART BY I-HUA CHEN
Look for the answer in the next issue. Or submit your own code challenge!