Persist Data from a Servlet using an Injected Data Access Object

By Rob Gravelle

Persist Data from a Servlet using an Injected Data Access Object

In the Create a Java Enterprise Application Controller in Eclipse article we developed a Servlet for our Exercises Catalog Java EE application that performed the role of controller in MVC architecture. In today's follow-up, we'll inject a Data Access Object (DAO) as a managed EJB to persist data submitted from a JSP page.

Injecting the Data Access EJB

Open up the ExercisesServlet in the Eclipse Editor and take a look at the doGet() and doPost() stubs. Both the doGet() and doPost() request handlers will call our ExercisesDAO that we created previously, so we need to create an instance of it. We could do that ourselves, but it's a lot easier to let the EJB container manage it for us. All we need to do is include the @EJB annotation in front of (or directly above) the variable declaration:

import javax.ejb.EJB

public class ExercisesServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // Injected DAO EJB:
    @EJB ExercisesDAO exercisesDao;

Display a List of Exercises

The doGet() handler processes incoming GET requests, like the kind that the browser sends to the server to request a page. In our case, the function sets an attribute named "exercises" and populates it with the results of our exerciseDao's getAllExercises() method that we talked about above. The Servlet then brings up the exercises.jsp page with the updated Exercises list and blank entry form, ready to accept another exercise:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Display the list of excercises:
    request.setAttribute("exercises", exercisesDao.getAllExercises());
    request.getRequestDispatcher("/exercises.jsp").forward(request, response);
}

Allowing Entry of New Exercises

The exercises.jsp page uses the POST method to submit form data so that doPost() will handle form submissions. Only the name is required to instantiate a new Exercise, but we also want to store the mainMuscleWorked and otherMusclesWorked. That's done by calling the exerciseDao instance's persist() method, passing in a new Exercise() object. Finally, doGet() is called to refresh the exercise.jsp page with the new exercise added to the list:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Handle a new exercise:
    String name = request.getParameter("name");
    if (name != null) {
        Exercise exercise = new Exercise(name);
        String mainMuscleWorked = request.getParameter("mainMuscleWorked");
        if (mainMuscleWorked != null) {
            exercise.setMainMuscleWorked(mainMuscleWorked);
        }
        String otherMusclesWorked = request.getParameter("otherMusclesWorked");
        if (otherMusclesWorked != null) {
            exercise.setOtherMuscles(otherMusclesWorked);
        }
        exercisesDao.persist(exercise);
    }
    // Display the list of guests:
    doGet(request, response);
}

Code the JSP Page

The last piece of our application is the exercises.jsp that was referenced in the Servlet's doGet() handler above. It provides the View part within the Model-View-Controller (MVC) architecture. It does that by including blocks of server-side code that generates content on the fly. You could say that it's dynamic content, but once it gets forwarded to the browser, it can't be changed again without using a front-end language like JavaScript.

To create the JSP file:

  • Right-click the WebContent node in the Package Explorer view and select New > JSP File from the popup menu. If you don't see that item in the list, select New > Other... instead to open the Wizard Selector dialog. The JSP File item is located under the Web folder.
  • On the New JSP File dialog, assign a name of "exercises.jsp" and click Next >.
  • On the Select JSP Template screen, choose "New JSP file (html)" and click Finish to create the file.

Once the file opens in the editor pane, we can begin coding the page.

Let's start by adding our imports. Just like in a java file, we must import classes that our not part of the java core. We will be needing java.util.List and our Exercise entity class. To import them, include the <%@page %> tag with the import attribute and set it to the two classes that we just mentioned. Separate each class with a comma.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.util.List,com.robgravelle.exercises.entities.Exercise"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Might as well update the page title (where it says "Insert title here").

<title>Exercise Catalog</title>

To keep things simple we'll only be including three fields in the form: the exercise Name, Main Muscle Worked, and Other Muscles Worked. A table helps to format the fields with a tabular layout.

Below the form, there is a server-side code block that fetches the exercises from the request attribute of the same name and displays their names.

<h1>Exercise Catalog</h1>
<form method="POST" action="Exercises.do">
  <table border="0" cellpadding="0" cellspacing="0" summary="Exercise Fields Table">
   <tbody>
     <tr><td>Name: </td><td><input type="text" name="name" /></td></tr>
     <tr><td>Main Muscle Worked: </td><td><input type="text" name="mainMuscleWorked" /></td></tr>
     <tr><td>Other Muscles Worked: </td><td><textarea rows="5" cols="30"></textarea></td></tr>
   </tbody>
  </table>
</form>
<input type="submit" value="Save" />
<hr>
<ol> <%
    @SuppressWarnings("unchecked")
    List<Exercise> exercises = (List<Exercise>)request.getAttribute("exercises");
    if (exercises != null) {
        for (Exercise exercise : exercises) { %>
            <li> <%= exercise %> </li> <%
        }
    } %>
</ol>

Here is the markup for the complete exercises.jsp file:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.util.List,com.robgravelle.exercises.entities.Exercise"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Exercise Catalog</title>
</head>
<body>
<h1>Exercise Catalog</h1>
<form method="POST" action="Exercises.do">
  <table border="0" cellpadding="0" cellspacing="0" summary="Exercise Fields Table">
   <tbody>
     <tr><td> Name: </td><td><input type="text" name="name" /></td></tr>
     <tr><td>Main Muscle Worked: </td><td><input type="text" name="mainMuscleWorked" /></td></tr>
     <tr><td>Other Muscles Worked: </td><td><textarea rows="5" cols="30"></textarea></td></tr>
   </tbody>
  </table>
</form>
<input type="submit" value="Save" />
<hr>
<ol> <%
    @SuppressWarnings("unchecked")
    List<Exercise> exercises = (List<Exercise>)request.getAttribute("exercises");
    if (exercises != null) {
        for (Exercise exercise : exercises) { %>
            <li> <%= exercise %> </li> <%
        }
    } %>
</ol>
</body>
</html>

Running the Application

At last the moment of truth has arrived. While it's true that a Java EE application involves a lot more overhead than your typical Hello World app, we did build an interactive multi-tier Web application! To try it out for yourself:

  • Right-click the WebContent node in the Package Explorer view and select Run As > Run on Server from the popup menu.
  • The first time you run your app, you'll have to select the server. Click the checkbox to always use the same server so that you don't have to select it every time.

Here is what the finished application looks like in the Internal Eclipse Browser:

ex

Conclusion

This series on building a Java EE 6 application in Eclipse gave us a good overview of how version 3 EJBs, JPA, Servlets, JSP Page all work together to create a rich UI experience for the user. In future articles, we'll delve deeper into each of these technologies individually to learn more about what they bring to the table.


Rob Gravelle

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleWebDesign.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses.

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92) and reached the #1 spot in the National Heavy Metal charts on Reverb Nation.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date