July 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Adding Business Logic to an ObjectDB / JPA App, Page 2

  • April 6, 2012
  • By Leonard Anghel
  • Send Email »
  • More Articles »

Developing an EJB Session Bean

It is time to add some business logic to our application. Start with the database operations that will be placed into an EJB session bean. Begin by generating an empty EJB session bean, as follows:

  1. Under project main node, right-click on the Source Packages and select New | Session Bean. If Session Bean is not present, then select Other, and under Categories, select J2EE. In the right tab, you will see the Session Bean option.
  2. In the New Session Bean wizard, type "atpDAO" as the session bean name, and press Finish.

Now, the generated stateless bean code should be replaced by the code below. We have a method to persist data into database, named persist(), and one for getting all the records from the database, named getAllPlayers():

 package ATP;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

@Stateless
public class atpDAO {

// Injected database connection:
@PersistenceContext private EntityManager em;

// Stores a new player
public void persist(Player player) {
em.persist(player);
}

// Retrieves all the players
public List<Player> getAllPlayers() {
TypedQuery<Player> query = em.createQuery("SELECT p FROM Player p ORDER BY p.id", Player.class);
return query.getResultList();
}

}

Using this approach has multiple advantages because the application server will manage the instantiation of the EJB class and inject an instance of the EJB class into the Servlet (see next section), prepare an EntityManager automatically and inject it into the em field (because it is annotated with the @PersistenceContext annotation), and handle transactions automatically using JTA. There's no need to wrap every operation that modifies the database with transaction begin and commit. For this, you need an application server that supports EJB, such as GlassFish or JBoss, and not a Servlet container, such as Tomcat and Jetty. I tested it on GlassFish v3, which comes bundled with NetBeans IDE.

Developing a Servlet Class to Manage HTTP Requests

Next, you need a component to deal with Web requests and to communicate with the EJB component. A Servlet can be a good choice in this case. To create one, you need to follow next steps:

  1. Under project main node, right-click on the Source Packages and select New | Servlet.If Servlet is not present, then select Other, and under Categories, select Web.In the right tab, you will see the Servlet option.
  2. In the New Servlet wizard, type "atpServlet" as the Servlet name, and ATP as the package. Click Finish.


ObjectDB JPA NetBeans
Click here for larger image

Figure 7. Creating a New Servlet

Now, the Servlet content must be replaced with the content below:

 package ATP;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

// Injected DAO EJB
@EJB
atpDAO ejbDao;

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

String name = request.getParameter("name");
String country = request.getParameter("country");
String sranking = request.getParameter("ranking");
String spoints = request.getParameter("points");
String photo = request.getParameter("photo");

if ((name != null) && (country != null) && (sranking != null) && (spoints != null) && (photo != null)) {
int ranking = Integer.valueOf(sranking);
int points = Integer.valueOf(spoints);
ejbDao.persist(new Player(name, country, ranking, points, photo));
}

// Display the list of guests:
request.setAttribute("players", ejbDao.getAllPlayers());
request.getRequestDispatcher("/atp.jsp").forward(request, response);
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Notice that the database operations are performed by the atpDao session bean, which is automatically instantiated and injected by the application server into the ejbDao field, because that field is marked with the @EJB annotation. Now, when your Servlet receive a HTTP request, it checks to see if this is a request for storing a new ATP player into the ObjectDB database. If the player's parameters were set, then the EJB business method persist()method is called for storing the new player. After that, the Servlet call the EJB getAllPlayers() business method, and forwards control to a JSP page that renders the ATP players as you can see in the next section. If a new player was inserted then it will be displayed by the JSP.

Developing a JSP Page for Output Rendering

The final component of your Web application is a JSP page that renders ATP players on screen. For this, you need to follow next steps:

  1. Under project main node, right-click on the Web Pages and select New | JSP. If JSP is not present, then select Other, and under Categories, select Web. In the right tab, you will see the JSP option.
  2. Type atp as the JSP name, and press Finish.


ObjectDB JPA NetBeans
Click here for larger image

Figure 8. Creating a New JSP Page

Next, replace the default generated code with the code below:

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*,ATP.Player"%>
<!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=UTF-8">
<title>ATP Men's Rankings</title>
</head>
<body>
<table align="center">
<tr>
<%
List<Player> players = (List<Player>) request.getAttribute("players");
if (players != null) {
for (Player player : players) {
%>
<td>
<table>
<tr>
<td rowspan="5">
<img src="images/<%= player.getImg()%>" alt="">
</td>
</tr>
<tr>
<td>
Ranking:<b> <%= player.getRanking()%> </b>
</td>
</tr>
<tr>
<td>
ATP points:<b> <%= player.getPoints()%> </b>
</td>
</tr>
<tr>
<td>
Name:<b> <%= player.getName()%> </b>
</td>
</tr>
<tr>
<td>
Country:<b> <%= player.getCountry()%> </b>
</td>
</tr>
</table>
</td>
<%
}
%>
<%
}
%>
</tr>
</table>
<form method="POST" action="atpServlet">
<table align="center">
<tr>
<td colspan="2">
Insert a new player:
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>
Country:
</td>
<td>
<input type="text" name="country" />
</td>
</tr>
<tr>
<td>
Ranking:
</td>
<td>
<input type="text" name="ranking" />
</td>
</tr>
<tr>
<td>
Points:
</td>
<td>
<input type="text" name="points" />
</td>
</tr>
<tr>
<td>
Photo:
</td>
<td>
<input type="text" name="photo" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add" />
</td>
</tr>
</table>
</form>
</body>
</html>

On the top side of the Web browser window, the JSP renders the current players from the database. On the bottom side, it renders a form for storing a new player. When you store a new player, you need to specify the name of an image file that represents a player's photo. Normally, that photo should be uploaded, but since this is not relevant here, you can use the photos from /images folder where they were stored manually.

A final adjustment should be made - under the Web Pages node, you have the application start page, called index.jsp. Just edit it and add a forward to your Servlet, like below:

 ...
<body>
<jsp:forward page="atpServlet" />
</body>
...

Running the Application

Running the application is very simple! Make sure that atpPlayers is the main project and click the big green Run button from NetBeans toolbar, or press F6. After GlassFish is started and the application is successfully deployed, the browser should automatically open. In Figures 9 and 10, you can see two screenshots of your application.

ObjectDB JPA NetBeans
Screenshot 1 of Your Application
ObjectDB JPA NetBeans
Screenshot 2 of Your Application

Browsing the ObjectDB Databases

You can browse the ObjectDB databases by using the ObjectDB Explorer tool available in /bin folder of ObjectDB location, as explorer.exe. Double-click it to launch the application, and navigate to the atp.odb database. If you use the same paths as in this article, then atp.odb is in D:\app\atpPlayers\build\web\WEB-INF\db folder. In figure 11 you can see how I have browsed it:


ObjectDB JPA NetBeans
Click here for larger image

Figure 11. Browsing atp.odb with ObjectDB Explorer Tool

You can find out more about ObjectDB tools at ObjectDB.com.

Summary

In this article, you have learned how to develop a Web application based on ObjectDB and JPA. You saw how to download and configure ObjectDB, how to query an ObjectDB database and how to browse a database content using ObjectDB tools.


Tags: NetBeans, object database, JPA

Originally published on http://www.developer.com.

Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel