users@glassfish.java.net

Re: How to use JPA's EntityManager.persist() in a servlet - mine does not

From: <glassfish_at_javadesktop.org>
Date: Wed, 20 Feb 2008 08:26:43 PST

Thank you for your reply.

Here is a version of the servlet that does not work:
----------------------------------------------------------------------------------
package com.xerox.wrc.arundel;

import java.io.IOException;
import javax.persistence.*;
import javax.transaction.*;
import javax.annotation.*;
import javax.naming.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// @PersistenceContext(unitName="HibernateTestPU", name="persistence/em")
public class AddDestination extends ArundelServlet implements javax.servlet.Servlet {
    // @PersistenceUnit
    // private EntityManagerFactory emf;
    @Resource
    private UserTransaction trans;
    
    static final long serialVersionUID = 1L;

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public AddDestination() {
        super();
    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletContext context = getServletContext();

        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        try {
            out.println("<html><head><title>Arundel Add Destination</title></head><body>");
            out.println("<h2>Arundel Add Destination</h2>");

            // list fields


            // form for new destination
            out.println("<form method=POST action=\"AddDestination\">");
            out.println("<table border='1'");
            out.print("<tr><th colspan=\"3\" align=center>Adding Destination</th></tr>");

            out.print("<tr>");
            out.print("<td>Name</td>");
            out.print("<td><input type=\"text\" name=name size=\"30\"</td>");
            out.print("<td>Required</td>");
            out.println("</tr>");
            out.print("<tr>");
            out.print("<td>URL</td>");
            out.print("<td><input type=\"text\" name=url size=\"30\"</td>");
            out.print("<td>Required</td>");
            out.println("</tr>");
            out.print("<tr>");
            out.print("<td>Comment</td>");
            out.print("<td><input type=\"text\" name=comment size=\"30\"</td>");
            out.print("<td>Optional</td>");
            out.println("</tr>");

            out.println("</table>");
            out.println("<input type=\"submit\" value=\"Submit\">");
            out.println("</form>");

        } catch (Exception e) {
            throw new ServletException(e.getMessage());
        }


    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String destination = new String("");
        ServletContext context = getServletContext();

        try {

            response.setContentType("text/html");
            java.io.PrintWriter out = response.getWriter();

            String name = request.getParameter("name");
            String url = request.getParameter("url");
            String comment = request.getParameter("comment");

            if (name == null) {
                out.println("<html><head><title>Arundel Error</title></head><body>");
                out.println("<h2>Error: Name cannot be null</h2>");
                out.println("</body>");
                out.println("</html>");
                return;
            }
            if (url == null) {
                out.println("<html><head><title>Arundel Error</title></head><body>");
                out.println("<h2>Error: URL cannot be null</h2>");
                out.println("</body>");
                out.println("</html>");
                return;
            }
            
            Context ic = new InitialContext();
            EntityManager myEM = (EntityManager) ic.lookup("java:comp/env/persistence/em");
            // EntityManager myEM=emf.createEntityManager();
            
            Destination dest = new Destination();
            dest.setName(name);
            dest.setUrl(url);
            dest.setComment(comment);

            trans.begin();

            // OK, the book says to call persist() to start managing the entity - but it doesn't work
            // em.persist(dest);
            myEM.persist(dest);

            trans.commit();

            String forwardPath = "/ListDestinations";
            RequestDispatcher dispatcher = context.getRequestDispatcher(forwardPath);
            if (dispatcher == null) {
                // context.log("EditDestination: Couldn't get a dispatcher for " + forwardPath);
                // now what?
                throw new ServletException("EditDestination: Couldn't get a dispatcher for " + forwardPath);
            } else {
                dispatcher.forward(request, response);
            }

        } catch (Exception e) {
            context.log(e.getMessage());
            throw new ServletException(e.getMessage());
        }
    }
}
--------------------------------------------------

Here is another version that does not work:

_____________________________

package com.xerox.wrc.arundel;

import java.io.IOException;
import javax.persistence.*;
import javax.transaction.*;
import javax.annotation.*;
import javax.naming.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: EditDestination
 *
 */
@PersistenceContext(unitName="HibernateTestPU", name="persistence/em")
public class AddDestination extends ArundelServlet implements javax.servlet.Servlet {
    // @PersistenceUnit
    // private EntityManagerFactory emf;
    @Resource
    private UserTransaction trans;
    
    static final long serialVersionUID = 1L;

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public AddDestination() {
        super();
    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ServletContext context = getServletContext();

        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();

        try {
            out.println("<html><head><title>Arundel Add Destination</title></head><body>");
            out.println("<h2>Arundel Add Destination</h2>");

            // list fields


            // form for new destination
            out.println("<form method=POST action=\"AddDestination\">");
            out.println("<table border='1'");
            out.print("<tr><th colspan=\"3\" align=center>Adding Destination</th></tr>");

            out.print("<tr>");
            out.print("<td>Name</td>");
            out.print("<td><input type=\"text\" name=name size=\"30\"</td>");
            out.print("<td>Required</td>");
            out.println("</tr>");
            out.print("<tr>");
            out.print("<td>URL</td>");
            out.print("<td><input type=\"text\" name=url size=\"30\"</td>");
            out.print("<td>Required</td>");
            out.println("</tr>");
            out.print("<tr>");
            out.print("<td>Comment</td>");
            out.print("<td><input type=\"text\" name=comment size=\"30\"</td>");
            out.print("<td>Optional</td>");
            out.println("</tr>");

            out.println("</table>");
            out.println("<input type=\"submit\" value=\"Submit\">");
            out.println("</form>");

        } catch (Exception e) {
            throw new ServletException(e.getMessage());
        }


    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String destination = new String("");
        ServletContext context = getServletContext();

        try {

            response.setContentType("text/html");
            java.io.PrintWriter out = response.getWriter();

            String name = request.getParameter("name");
            String url = request.getParameter("url");
            String comment = request.getParameter("comment");

            if (name == null) {
                out.println("<html><head><title>Arundel Error</title></head><body>");
                out.println("<h2>Error: Name cannot be null</h2>");
                out.println("</body>");
                out.println("</html>");
                return;
            }
            if (url == null) {
                out.println("<html><head><title>Arundel Error</title></head><body>");
                out.println("<h2>Error: URL cannot be null</h2>");
                out.println("</body>");
                out.println("</html>");
                return;
            }
            
            Context ic = new InitialContext();
            EntityManager myEM = (EntityManager) ic.lookup("java:comp/env/persistence/em");
            // EntityManager myEM=emf.createEntityManager();
            
            Destination dest = new Destination();
            dest.setName(name);
            dest.setUrl(url);
            dest.setComment(comment);

            trans.begin();

            // OK, the book says to call persist() to start managing the entity - but it doesn't work
            // em.persist(dest);
            myEM.persist(dest);

            trans.commit();

            String forwardPath = "/ListDestinations";
            RequestDispatcher dispatcher = context.getRequestDispatcher(forwardPath);
            if (dispatcher == null) {
                // context.log("EditDestination: Couldn't get a dispatcher for " + forwardPath);
                // now what?
                throw new ServletException("EditDestination: Couldn't get a dispatcher for " + forwardPath);
            } else {
                dispatcher.forward(request, response);
            }

        } catch (Exception e) {
            context.log(e.getMessage());
            throw new ServletException(e.getMessage());
        }
    }
}
 -------------------------------------------

Here is persistence.xml:

--------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="HibernateTestPU" transaction-type="JTA">
    <jta-data-source>jdbc/arundel</jta-data-source>
    <class>com.xerox.wrc.arundel.Destination</class>
    <class>com.xerox.wrc.arundel.Policy</class>
    <class>com.xerox.wrc.arundel.Policyconf</class>
    <class>com.xerox.wrc.arundel.Service</class>
    <class>com.xerox.wrc.arundel.Serviceparameter</class>
  </persistence-unit>
</persistence>

-------------------------------------------------

Here is web.xml:

-----------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>ListDestinations</servlet-name>
        <servlet-class>com.xerox.wrc.arundel.ListDestinations</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ArundelServlet</servlet-name>
        <servlet-class>com.xerox.wrc.arundel.ArundelServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ShowDestination</servlet-name>
        <servlet-class>com.xerox.wrc.arundel.ShowDestination</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>EditDestination</servlet-name>
        <servlet-class>com.xerox.wrc.arundel.EditDestination</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>AddDestination</servlet-name>
        <servlet-class>com.xerox.wrc.arundel.AddDestination</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ListDestinations</servlet-name>
        <url-pattern>/ListDestinations</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ArundelServlet</servlet-name>
        <url-pattern>/ArundelServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ShowDestination</servlet-name>
        <url-pattern>/ShowDestination</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>EditDestination</servlet-name>
        <url-pattern>/EditDestination</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AddDestination</servlet-name>
        <url-pattern>/AddDestination</url-pattern>
    </servlet-mapping>
    <persistence-context-ref>
        <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
        <persistence-unit-name>HibernateTestPU</persistence-unit-name>
    </persistence-context-ref>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        </welcome-file-list>
    </web-app>

----------------------------------------------------------------------
[Message sent by forum member 'bclyon' (bclyon)]

http://forums.java.net/jive/thread.jspa?messageID=259943