Enterprise Java Beans :P

How to create a project 

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu.
  2. Select Enterprise Application from the Java EE category and click Next.

Creating the Entity Class

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. From the Persistence category, select Entity Class and click Next.
  3. Type ejb for the Package.
  4. Leave the Primary Key Type as Long in the New Entity Class wizard.
  5. Select Create Persistence Unit. Click Next.
  6.  Keep the default Persistence Unit Name.
  7. For the Persistence Provider, choose EclipseLink (JPA2.0)(default).
  8. For the Data Source, choose a data source (for example, select jdbc/sample if you want to use JavaDB)
 Inside the class put these variables 


     private String title;

     private String body;

     
     then also generate their getters and setters  

Creating the Message-Driven Bean

  1. Right-click the EJB module in the Projects window and choose New > Other to open the New File wizard.
  2. From the Enterprise JavaBeans category, select the Message-Driven Bean file type. Click Next.
  3. Type NewMessage for the EJB Name.
  4. Select ejb from the Package drop-down list.
  5. Click the Add button next to the Project Destination field to open the Add Message Destination
  6. dialog box.
  7. In the Add Message Destination dialog box, type jms/NewMessage and select Queue for the
  8. destination type. Click OK.
  9. Confirm that the project destination is correct. Click Finish.
 Add this line soon after the class deceleration
    
    @Resource
    private MessageDrivenContext mdc; 

  after that select insert code and call Use Entity Manager

  change the persist method to change the name to save

  add this code to onMessage
  
  ObjectMessage msg = null;
  try {
    if (message instanceof ObjectMessage) {
           msg = (ObjectMessage) message;
           NewsEntity e = (NewsEntity) msg.getObject();
           save(e);
    }
 } catch (JMSException e) {
     e.printStackTrace();
     mdc.setRollbackOnly();
 } catch (Throwable te) {
     te.printStackTrace();
}

Creating the Session Facade


create the session facade, perform the following steps:
1. Right-click the EJB module and choose New > Other.
2. From the Persistence category, select Session Beans for Entity Classes. Click Next.
3. Select ejb.NewsEntity from the list of available entity classes and click Add to move the
class to the Selected Entity Classes pane. Click Next.
4. Check that the Package is set to ejb. Click Finish.


Coding the Web Module

ListNews Servelet

   right click -> insert Code -> callEnterpriseBean and select the facade in ejb package   

    @EJB
    private NewsFacade newsFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ListNews</title>");
            out.println("</head>");
            out.println("<body>");
            List news = newsFacade.findAll();
            for (int i = 0; i < news.size(); i++) {
                News e = (News) news.get(i);

                out.println(e.getTitle() + "-" + e.getBody());
                out.println("<a href='EditMessage?id=" + e.getId() + "'>edit</a>");
                out.println("<a href='DeleteMessage?id=" + e.getId() + "'>delete</a>");
                out.println("<br/>");
            }
            out.println("<br/>");
            out.println("<a href='PostMessage'>Add new message</a>");
            out.println("</body>");
            out.println("</html>");
        }
    }


postMessage Servlet - using MessageDrivenBean

Only add the bold codes at correct places

@WebServlet(name="PostMessage", urlPatterns={"/PostMessage"})
public class PostMessage extends HttpServlet {

        @Resource(mappedName="jms/NewMessageFactory")
        private ConnectionFactory connectionFactory;
        @Resource(mappedName="jms/NewMessage")

        private Queue queue;

        response.setContentType("text/html;charset=UTF-8");
        // Add the following code to send the JMS message
       String title=request.getParameter("title");
       String body=request.getParameter("body");
       if ((title!=null) && (body!=null)) {
       try {
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer =
        session.createProducer(queue);
        ObjectMessage message = session.createObjectMessage();
        // here we create NewsEntity, that will be sent in JMS message
        NewsEntity e = new NewsEntity();
        e.setTitle(title);
        e.setBody(body);
        message.setObject(e);
        messageProducer.send(message);
        messageProducer.close();
        connection.close();
        response.sendRedirect("ListNews");
        } catch (JMSException ex) {
          ex.printStackTrace();
        }
        }

       out.println("Servlet PostMessage at " + request.getContextPath() +"</h1>");
       // The following code adds the form to the web page
       out.println("<form>");
       out.println("Title: <input type='text' name='title'><br/>");
       out.println("Message: <textarea name='body'></textarea><br/>");
       out.println("<input type='submit'><br/>");
       out.println("</form>");

       out.println("</body>");

PostMessage Servlet - using facade 



    @EJB
    private NewsEntityFacade entityFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JMSException {
        response.setContentType("text/html;charset=UTF-8");

        String title = request.getParameter("title");
        String body = request.getParameter("body");
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setTitle(title);
            e.setBody(body);

            entityFacade.create(e);

            response.sendRedirect("ListNews");
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet PostMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet PostMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            out.println("Title: <input type='text' name='title'><br/>");
            out.println("Message: <textarea name='body'></textarea><br/>");
            out.println("<input type='submit'><br/>");
            
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }


DeleteMessage Servlet


    @EJB
    private NewsEntityFacade newsEntityFacade;

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String title = request.getParameter("title");
        String body = request.getParameter("body");
        Long _id = Long.parseLong(request.getParameter("id"));
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setId(_id);
            e.setTitle(title);
            e.setBody(body);
            
            newsEntityFacade.remove(e);
            
            response.sendRedirect("ListNews");
        }
        
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet DeleteMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet DeleteMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            NewsEntity news = newsEntityFacade.find(_id);
            out.println("Title: <input type='text' name='title' value='" + news.getTitle() + "'><br/>");
            out.println("Body: <input type='text' name='body' value='" + news.getBody() + "'><br/>");
            out.println("<input type='hidden' name='id' value='" + _id + "'/>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }


Edit Message Servelet


    @EJB
    private NewsEntityFacade newsEntityFacade;

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Long _id = Long.parseLong(request.getParameter("id"));
        
        String title = request.getParameter("title");
        String body = request.getParameter("body");
        
        if ((title != null) && (body != null)) {
            NewsEntity e = new NewsEntity();
            e.setId(_id);
            e.setTitle(title);
            e.setBody(body);

            newsEntityFacade.edit(e);

            response.sendRedirect("ListNews");
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet EditMessage</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet EditMessage at " + request.getContextPath() + "</h1>");
            out.println("<form>");
            NewsEntity news = newsEntityFacade.find(_id);
            out.println("Title: <input type='text' name='title' value='" + news.getTitle() + "'><br/>");
            out.println("Body: <input type='text' name='body' value='" + news.getBody() + "'><br/>");
            out.println("<input type='hidden' name='id' value='" + _id + "'/>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        }
    }



No comments:

Post a Comment