• No results found

Create a ServletContextListener to do Initialization

In document Java Web Programming with Eclipse (Page 119-124)

We need to set the DataSource in the DataAccessObject class before the servlets start handling requests. We will do this from a class called Init whose contextInitialized method is called when the publisher web applica-tion is loaded by the Web container. For this purpose, create a new class in the publisher.web package called Init that implements the ServletCon-textListener class. The complete code for this class is given in Figure 11.2.

package publisher.web;

public class Init implements ServletContextListener {

private Logger logger = Logger.getLogger(this.getClass());

public void contextDestroyed(ServletContextEvent sce) { }

119

private void contextInitialized2(ServletContext servletContext) throws Exception {

InitialContext enc = new InitialContext();

Context compContext = (Context) enc.lookup("java:comp/env");

DataSource dataSource = (DataSource) compContext.lookup("datasource");

NewsFeedServlet.setDataSource(dataSource);

}

public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext();

try {

Figure 11.2: Class Init

We have already configured the web container to create a data source for the publisher web application. In order to access this data source, we use the Java Naming and Directory Interface (JNDI) to obtain a reference to the DataSource object created by the container. In the contextInitialized2 method shown above, the first thing we do is create an instance of Initial-Context. This is the starting point to locate resources provided through JNDI. In the next line, we narrow the context by calling the lookup method with the name java:comp/env. We named the resulting context enc because it represents the environment naming context (ENC). We then perform a lookup through the ENC on the name datasource to obtain a reference to the data source.

In order for Tomcat to call the contextInitialized method of your Init class, we need to add a listener element to the application’s deployment descriptor. Add the following listener element as a child to the web-app element in the deployment descriptor web.xml.

<listener>

<listener-class>publisher.web.Init</listener-class>

</listener>

Later, we will use the Init class to perform other initializations for the web application.

Depending on your version of Tomcat, you may also need to add the fol-lowing to the deployment descriptor. This is not needed for Tomcat version 6.

<resource-ref>

<description>dataSource</description>

<res-ref-name>datasource</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

11.7 Test

Make the publisher application reload its deployment descriptor by stoping and starting it through the manager application. Then go to

http://localhost:8080/website/home to verify that the website application can still obtain the news feed from the publisher application.

text

11.8 Exercises

(1) Anticipating problems

Introduce the following errors into the code and describe the effects.

• Omit the listener element from the deployment descriptor.

• Inside Init, replace compContext.lookup("datasource");

with compContext.lookup("badsource");

• Inside Init, fail to set the data source in the news feed servlet.

Introduce an additional error of your choosing and describe the effects.

Chapter 12

Data Access Objects

12.1 Objectives

1. Understand how to abstract interaction with the database though the creation of data access objects

2. Understand the basic operations provided by all data access objects 3. Implement the find and findAll methods of the news item data access

object class

4. Learn how and why to create critical sections in multi-threaded Java programs

5. Understand the princple of minimizing visibility and why it is a best practice

6. Learn about the role of an object relational mapping library in a web development project

12.2 Overview

In the previous chapter we showed how to access the database directly from servlet code. This architecture is illustrated in Figure 12.1.

The problem with this approach is that code to interact with the database tends to grow and becomes mixed with logic that directly deals with solving the problem at hand. Also, the code that is used is similar from one in-stance to the next, giving rise to code duplication. To solve these problems,

Figure 12.1: Servlet Based System With Direct Access To The Database

Figure 12.2: Servlet Based System With Object Oriented Approach To Per-sistence

we improve the architecture by defining persistent classes with their corre-sponding data access objects (DAOs). This allows us to express application logic in terms of manipulation of business objects such as NewsItem and User rather than operating on separate data fields taken from columns in the database. Figure 12.2 illustrates the revised arhitecture.

Normally, code devoted to managing the persistent state of objects com-prises a large percentage of the total code. Because this type of code can be generalized, libraries have been developed that provide developers with a framework to implement object persistence in their applications. These frameworks are referred to as object-relational mapping (ORM) frameworks because they provide the means to move data represented as objects in code into, and out of, relational databases. Two well-known open source ORM frameworks include Hibernate and iBatis. Use of an ORM persistence frame-work is outside the scope of this book. In this book, we look at a simple approach to implementing object persistence. However, as a real applica-tion would grow, our simple approach would become more complex, so that adoption of an ORM framework would be more cost-effective in the long run.

In this section, you will define a class called NewsItem that represents individual news items that are stored in the database. The news item class is considered to be persistent because the news item data in the database continues to exist between restarts of the web application. It is also referred to as a business object, or domain object, because it corresponds directly to

In document Java Web Programming with Eclipse (Page 119-124)