package example; import javax.annotation.Resource; import javax.persistence.*; import javax.servlet.*; import javax.servlet.http.*; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.UserTransaction; import java.io.*; public class RegistrationServlet extends HttpServlet { // This injects the default entity manager factory @PersistenceUnit private EntityManagerFactory emf; // This injects a user transaction object. @Resource private UserTransaction utx; public void service (HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException { try { // begin a tx using utx b'cos we are using JTA EM. utx.begin(); } catch (Exception e) { throw new ServletException(e); } // create an entity manager in service() so that only // this thread uses it. // More over, we create EM after utx.begin(), so that we don't // have to call em.joinTransaction(). EntityManager em = emf.createEntityManager(); try { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println(" New User Registartion " + " "); String name = req.getParameter("name"); String password = req.getParameter("password"); UserCredential credential = new UserCredential(name, password); // em.persist makes the new object as persistent and managed. em.persist(credential); out.println("Successfully created the new user. " + "Click here to login."); out.println(" "); // commit the transaction, // b'cos web container rollbacks unfinished tx at the end of request utx.commit(); } catch (Exception e) { try { utx.rollback(); } catch (Exception ee) { // log the exception and continue } throw new ServletException(e); } finally { // close the em so that provider can release resources. em.close(); } } public void init( ServletConfig config) throws ServletException { super.init(config); } }