LAB-7001: Using Eclipse to Develop for the GlassFish Server

Expected Duration: 60 minutes

Exercise 2: Introducing Application Development using GlassFish Tools Bundle for Eclipse (30 minutes)

 

This exercise provides an introduction to using the GlassFish Tools Bundle for Eclipse. For more details, please see the GlassFish Tools Bundle For Eclipse User Guide and GlassFish Plugin For Eclipse Documentation.

In this lesson we are going to create some basic Java EE projects using the GlassFish v3 Prelude application server in Eclipse.


Background Information

 

Introducing Application Development Using the Bundle

 

The GlassFish Tools Bundle for Eclipse provides out of the box integration of the Eclipse 3.4.2, GlassFish Application Server versions 2.1 and v3 prelude, and JavaDB configuration.


Steps to Follow

 

Step 1: Creating a Dynamic Web Project

  1. If the tools bundle is not already running, start it.
  2. Click File->New->Dynamic Web Project

  3. Name the project (for example "MyFirstWebApp") and choose the Bundled GlassFish v3 Prelude Server as the target runtime. Finish the wizard. You will see the project files in the Explorer window and the default index.jsp file opened in the editor.

  4. Run the new web project on the server:

    • Select the Run icon from the toolbar
    • Choose the Bundled GlassFish v3 Prelude Server as the server
    • Optionally, you can choose "Always use this server" to streamline subsequent runs

  5. The application is then deployed to the server and opened in the Eclipse web browser.

Step 2: Adding a Servlet which demonstrates session preservation

Session Preservation is a new feature of GlassFish Server v3 Prelude which allows you to retain information about your Sessions across redeployments.

  1. Create a servlet in the project you created in step 1. Right-click on your project, MyFirstWebApp, then click New->Servlet

    Name the servlet (for example "MyServlet") and provide a package name (for example "pkg", then finish the wizard.

  2. Update the contents of the generated boilerplate code for doGet() and doPost() methods. You can copy it from the contents of this sample servlet or you can copy it from the code blocks below.

  3. Your doGet() method should look something like:

              
              /**
               * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
               */
              protected void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                  HttpSession session = request.getSession(true);
                  response.setContentType("text/html");
                  PrintWriter out = response.getWriter();
                  String heading;
                  Integer accessCount = new Integer(0);
                  if (session.isNew()) {
                      heading = "Welcome, Newcomer";
                  } else {
                      heading = "Welcome Back";
                      Integer oldAccessCount =
                          (Integer) session.getAttribute("accessCount");
                      if (oldAccessCount != null) {
                          accessCount =
                              new Integer(oldAccessCount.intValue() + 1);
                      } 
                  } 
                  session.setAttribute("accessCount", accessCount);
    
                  out.println(
                        "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                        "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
                        "<H2>Inforff  sdfmation onYour Session:</H2>\n" +
                        "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                        "<TR BGCOLOR=\"#FFAD70\">\n" +
                        "  <TH>Info Type<TH>Value\n" +
                        "<TR>\n" +
                        "  <TD>ID\n" +
                        "  <TD>" + session.getId() + "\n" +
                        "<TR>\n" +
                        "  <TD>Creation Time is\n" +
                        "  <TD>" + new Date(session.getCreationTime()) + "\n" +
                        "<TR>\n" +
                        "  <TD>Time of Last Access\n" +
                        "  <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
                        "<TR>\n" +
                        "  <TD>Number of Previous Accesses\n" +
                        "  <TD>" + accessCount + "\n" +
                        "</TABLE>\n" +
                        "</BODY></HTML>");
    
              } 
              
  4. Your doPost() method should look something like:

              
              /**
               * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
               */
              protected void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                  doGet(request, response);
              } 
              
  5. Use Eclipse's functionality to add missing imports: Click Source->Organize Imports

  6. Use Eclipse's functionality to correct the indentation: Click Source->Correct Indentation

  7. Deploy the servlet to the server:

    • Save the changes to the servlet. This will automatically deploy the changes to the GlassFish v3 Prelude server.
    • Load the servlet in the web browser by going to http://localhost:8080/MyFirstWebApp/MyServlet

  8. Reload the servlet in the web browser several times. Notice the "Number of Previous Accesses" value counter being incremented with each reload.

  9. Modify the servlet:

    • Notice that there was a typo in the H2 header of the servlet doGet method.
    • Change the text from "Inforff sdfmation onYour Session:" to "Information on Your Session:"

  10. Deploy the servlet changes to the server:

    • Save the changes to the servlet. This will automatically deploy the changes to the GlassFish v3 Prelude server.
    • Reload the servlet in the browser. Notice that in addition to the typo correction, the "Number of Previous Accesses" value does not reset, it continues to be incremented from the previous value.

Step 3: Adding JPA functionality to your project

GlassFish v3 Prelude comes pre-configured with the EclipseLink JPA implementation. This allows you to take advantage of Eclipse's DALI tools.

  1. This section assumes you have set the GlassFish preference to start the database automatically as in Exercise 1. It also assumes you have the server running.
  2. Add the JPA project facet to the project you created in step 1:

    Right-click on your project and choose Properties. In the dialog that comes up, choose the Project Facets node.

    Click the checkbox next to the Java Persistence option

    Click the Further configuration available... link

    In the dialog that pops up, change

    • Platform to EclipseLink
    • Connection to Sample JavaDB Database
    • JPA Implementation to Use Implementation provided by server runtime

    Then hit OK to close the facets dialog

  3. Now we need to add the JDBC driver library to the project:
    • In the project properties dialog, choose the Java Build Path node
    • Click the Libraries tab at the top of the dialog, then the Add Library... button
    • Choose Connectivity Driver Definition, then Next, then DerbyForSampleDB from the combo box
    • Click Finish to close the wizard, then OK to close the properties dialog
  4. Configure the persistence.xml to point at the sample database

    Expand your project in the explorer and find the persistence.xml node under the JPA Content node. Double-click it to open it in the editor.

    Choose the second tab in the bottom of the editor to configure the Connection information

    • Change Transaction Type to Resource Local
    • Click the Populate from Connection... link
    • In the dialog that pops up, choose Sample JavaDB Database, then hit OK
    • Save your changes to the persistence.xml file
  5. Generate Entities from the tables in the bundled sample database:
    • Right-click on your project and choose JPA Tools->Generate Entities...
    • Click the Reconnect... link, then when it is done, choose APP in the Schema combo box
    • In the next page of the wizard, enter a package name ("pkg") and click the Select All button, then finish the wizard

  6. Modify the index.jsp to use the new entities:

    Update the contents of the generated boilerplate code in index.jsp to reference and print some customer data. You can copy it from the code block below.

    Add this below the h1 header block:

    	<h2>Hello Customers:</h2>
    	<%@ page import="java.util.*,javax.persistence.*,pkg.Customer"%>
    	<%!
    	private String getCustomersData() {
    	    EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyFirstWebApp");
    	    EntityManager em = emf.createEntityManager();
    	    Iterator customerIt = em.createQuery("select c from Customer c").getResultList().iterator();
    	    StringBuilder output = new StringBuilder();
    
    	    while (customerIt.hasNext()) {
    	        Customer customer = (Customer)customerIt.next();
    	        output.append("<li>" + customer.getCustomerId() + ": " + customer.getName());
    	    }
    	    return output.toString();
    	}
    	%>
    	<%=getCustomersData() %>
              
  7. Run the modified web project on the server:

    • Select the Run icon from the toolbar


Summary

 

In this exercise, you saw how to develop projects which use a sample of Java EE functionality using Eclipse. You learned about the basics of Dynamic Web Projects, session preservation, and generation of JPA entities.

 

Back to top
Summary