Getting Started with Web Applications

Getting Started with Web Applications

A web application is a dynamic extension of a web or application server. There are two types of web applications:

Web Applications

In the Java 2 platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, or web service endpoints. The interaction between a web client and a web application is illustrated in Figure 3–1. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client.

Figure 3–1 Java Web Application Request Handling
Diagram of web application request handling. Clients
and web components communicate using HttpServletRequest and HttpServletResponse.

Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Although servlets and JSP pages can be used interchangeably, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. JSP pages are more appropriate for generating text-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless Markup Language (WML), and XML.

Since the introduction of Java Servlet and JSP technology, additional Java technologies and frameworks for building interactive web applications have been developed. Figure 3–2 illustrates these technologies and their relationships.

Figure 3–2 Java Web Application Technologies
Diagram of web application technologies. JavaServer Pages,
the JSP Standard Tag Library, and JavaServer Faces rest on JavaServlet technology.

Notice that Java Servlet technology is the foundation of all the web application technologies, so you should familiarize yourself with the material in Chapter 4, Java Servlet Technology even if you do not intend to write servlets. Each technology adds a level of abstraction that makes web application prototyping and development faster and the web applications themselves more maintainable, scalable, and robust.

Web components are supported by the services of a runtime platform called a web container. A web container provides services such as request dispatching, security, concurrency, and life-cycle management. It also gives web components access to APIs such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the application is installed, or deployed, to the web container. The configuration information is maintained in a text file in XML format called a web application deployment descriptor (DD). A DD must conform to the schema described in the Java Servlet Specification.

This chapter gives a brief overview of the activities involved in developing web applications. First it summarizes the web application life cycle. Then it describes how to package and deploy very simple web applications on the Application Server. It moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters. It then introduces an example, Duke’s Bookstore, which illustrates all the Java EE web-tier technologies, and describes how to set up the shared components of this example. Finally it discusses how to access databases from web applications and set up the database resources needed to run Duke’s Bookstore.

Web Application Life Cycle

A web application consists of web components, static resource files such as images, and helper classes and libraries. The web container provides many supporting services that enhance the capabilities of web components and make them easier to develop. However, because a web application must take these services into account, the process for creating and running a web application is different from that of traditional stand-alone Java classes.

  1. Develop the web component code.
  2. Develop the web application deployment descriptor.
  3. Compile the web application components and helper classes referenced by the components.
  4. Optionally package the application into a deployable unit.
  5. Deploy the application into a web container.
  6. Access a URL that references the web application.

Developing web component code is covered in the later chapters. Steps 2 through 4 are expanded on in the following sections and illustrated with a Hello, World-style presentation-oriented application. This application allows a user to enter a name into an HTML form (Figure 3–3) and then displays a greeting after the name is submitted (Figure 3–4).

Figure 3–3 Greeting Form
Screen capture of Duke's greeting, "Hello, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.
Figure 3–4 Response
Screen capture of Duke's response, "Hello, Charlie!"

The Hello application contains two web components that generate the greeting and the response. This chapter discusses two versions of the application: a JSP version called hello1, in which the components are implemented by two JSP pages (tut-install/javaeetutorial5/examples/web/hello1/web/index.jsp and tut-install/javaeetutorial5/examples/web/hello1/web/response.jsp) and a servlet version called hello2, in which the components are implemented by two servlet classes (tut-install/javaeetutorial5/examples/web/hello2/src/servlets/GreetingServlet.java and tut-install/javaeetutorial5/examples/web/hello2/src/servlets/ResponseServlet.java). The two versions are used to illustrate tasks involved in packaging, deploying, configuring, and running an application that contains web components. The section Chapter 2, Using the Tutorial Examples explains how to get the code for these examples.

After you install the tutorial bundle, the source code for the examples is in the following directories:

  • tut-install/javaeetutorial5/examples/web/hello1/
  • tut-install/javaeetutorial5/examples/web/hello2/

Web Modules

In the Java EE architecture, web components and static web content files such as images are called web resources. A web module is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.

In addition to web components and web resources, a web module can contain other files:

  • Server-side utility classes (database beans, shopping carts, and so on). Often these classes conform to the JavaBeans component architecture.
  • Client-side classes (applets and utility classes).

A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources, such as images, are stored.

The document root contains a subdirectory named WEB-INF, which contains the following files and directories:

  • web.xml: The web application deployment descriptor
  • Tag library descriptor files (see Tag Library Descriptors)
  • classes: A directory that contains server-side classes: servlets, utility classes, and JavaBeans components
  • tags: A directory that contains tag files, which are implementations of tag libraries (see Tag File Location)
  • lib: A directory that contains JAR archives of libraries called by server-side classes

If your web module does not contain any servlets, filter, or listener components then it does not need a web application deployment descriptor. In other words, if your web module only contains JSP pages and static files then you are not required to include a web.xml file. The hello1example, first discussed in Packaging Web Modules, contains only JSP pages and images and therefore does not include a deployment descriptor.

You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/directory.

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a web archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet Specification.

To deploy a WAR on the Application Server, the file must also contain a runtime deployment descriptor. The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Application Server’s resources. The Application Server web application runtime DD is named sun-web.xml and is located in the WEB-INF directory along with the web application DD. The structure of a web module that can be deployed on the Application Server is shown in Figure 3–5.

Figure 3–5 Web Module Structure
Diagram of web module structure. WEB-INF and web pages
are under the root. Under WEB-INF are descriptors and the lib, classes, and
tags directories.

Packaging Web Modules

A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You package a web module into a WAR by executing the jar command in a directory laid out in the format of a web module, by using the Ant utility, or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Ant to build, package, and deploy the sample applications.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
    tut-install/javaeetutorial5/examples/web/
  3. Select the hello1 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. In the Projects tab, right-click the hello1 project and select Build.
  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello1/.
  2. Type ant. This command will spawn any necessary compilations, copy files to the tut-install/javaeetutorial5/examples/web/hello1/build/ directory, create the WAR file, and copy it to the tut-install/javaeetutorial5/examples/web/hello1/dist/ directory.

Deploying a WAR File

You can deploy a WAR file to the Application Server in a few ways:

  • Copying the WAR into the domain-dir/autodeploy/ directory.
  • Using the Admin Console.
  • By running asadmin or ant to deploy the WAR.
  • Using NetBeans IDE.

All these methods are described briefly in this chapter; however, throughout the tutorial, you will use ant and NetBeans IDE for packaging and deploying.

Setting the Context Root

context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.

In a packaged web module for deployment on the Application Server, the context root is stored in sun-web.xml.

  1. Expand your project tree in the Projects pane of NetBeans IDE.
  2. Expand the Web Pages and WEB-INF nodes of your project.
  3. Double-click sun-web.xml.
  4. In the editor pane, click Edit As XML.
  5. Edit the context root, which is enclosed by the context-root element.

Deploying a Packaged Web Module

If you have deployed the hello1 application, before proceeding with this section, undeploy the application by following one of the procedures described in Undeploying Web Modules.

Deploying with the Admin Console

  1. Expand the Applications node.
  2. Select the Web Applications node.
  3. Click the Deploy button.
  4. Select the radio button labeled “Package file to be uploaded to the Application Server.”
  5. Type the full path to the WAR file (or click on Browse to find it), and then click the OK button.
  6. Click Next.
  7. Type the application name.
  8. Type the context root.
  9. Select the Enabled box.
  10. Click the Finish button.

Deploying with asadmin

To deploy a WAR with asadmin, open a terminal window or command prompt and execute


asadmin deploy full-path-to-war-file

Deploying with Ant

To deploy a WAR with the Ant tool, open a terminal window or command prompt in the directory where you built and packaged the WAR, and execute


ant deploy

Deploying with NetBeans IDE

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to your project and open it.
  3. In the Projects tab, right-click the project and select Undeploy and Deploy.

Testing Deployed Web Modules

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello1.

  1. Open a web browser.
  2. Enter the following URL in the web address box:
    http://localhost:8080/hello1
  3. Enter your name, and click Submit.

The application should display the name you submitted as shown in Figure 3–3 and Figure 3–4.

Listing Deployed Web Modules

The Application Server provides two ways to view the deployed web modules: the Admin Console and the asadmin command.

  1. Open the URL http://localhost:4848/asadmin in a browser.
  2. Expand the nodes Applications->Web Applications.

Use the asadmin command as follows:


asadmin list-components

Updating Web Modules

  1. Recompile any modified classes.
  2. If you have deployed a packaged web module, update any modified components in the WAR.
  3. Redeploy the module.
  4. Reload the URL in the client.

Updating a Packaged Web Module

This section describes how to update the hello1 web module that you packaged.

First, change the greeting in the file tut-install/javaeetutorial5/examples/web/hello1/web/index.jsp to

<h2>Hi, my name is Duke. What’s yours?</h2>

To update the project in NetBeans IDE:

  • Right-click on the project and select Build.
  • Right-click on the project and select Undeploy and Deploy.

To update the project using the Ant build tool:

  • Type ant to copy the modified JSP page into the build directory.
  • Type ant deploy to deploy the WAR file.

To view the modified module, reload the URL in the browser.

You should see the screen in Figure 3–6 in the browser.

Figure 3–6 New Greeting
Screen capture of Duke's new greeting, "Hi, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed JSP or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/j2ee-modules/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment, because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid and the client must restart the session.

  1. Select the Applications Server node.
  2. Select the Advanced tab.
  3. Check the Reload Enabled box to enable dynamic reloading.
  4. Enter a number of seconds in the Reload Poll Interval field to set the interval at which applications and modules are checked for code changes and dynamically reloaded.
  5. Click the Save button.
  1. Create an empty file named .reload at the root of the module:
    domain-dir/applications/j2ee-modules/context-root/.reload
  2. Explicitly update the .reload file’s time stamp each time you make these changes. On UNIX, execute
    touch .reload

For JSP pages, changes are reloaded automatically at a frequency set in the Reload Poll Interval field. To disable dynamic reloading of JSP pages, set the Reload Poll Interval field value to –1.

Undeploying Web Modules

You can undeploy web modules in four ways: you can use NetBeans IDE, the Admin Console, the asadmin command, or the Ant tool.

  1. Ensure the Sun Java System Application Server is running.
  2. In the Runtime window, expand the Sun Java System Application Server instance and the node containing the application or module.
  3. Right-click the application or module and choose Undeploy.
  1. Open the URL http://localhost:4848/asadmin in a browser.
  2. Expand the Applications node.
  3. Select Web Applications.
  4. Click the check box next to the module you wish to undeploy.
  5. Click the Undeploy button.

Use the asadmin command as follows:


asadmin undeploy context-root

To use the Ant tool, execute the following command in the directory where you built and packaged the WAR:


ant undeploy

Configuring Web Applications

Web applications are configured by means of elements contained in the web application deployment descriptor.

The following sections give a brief introduction to the web application features you will usually want to configure. A number of security parameters can be specified; these are covered in Chapter 30, Securing Web Applications.

In the following sections, examples demonstrate procedures for configuring the Hello, World application. If Hello, World does not use a specific configuration feature, the section gives references to other examples that illustrate how to specify the deployment descriptor element.

Mapping URLs to Web Components

When a request is received by the web container it must determine which web component should handle the request. It does so by mapping the URL path contained in the request to a web application and a web component. A URL path contains the context root and an alias:


http://host:port/context-root/alias

Setting the Component Alias

The alias identifies the web component that should handle a request. The alias path must start with a forward slash (/) and end with a string or a wildcard expression with an extension (for example, *.jsp). Since web containers automatically map an alias that ends with *.jsp, you do not have to specify an alias for a JSP page unless you wish to refer to the page by a name other than its file name.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. Expand the project tree in the Projects pane.
  7. Expand the Web pages node and then the WEB-INF node in the project tree.
  8. Double-click the web.xml file inside the WEB-INF node.

The following steps describe how to make the necessary edits to the web.xml file, including how to set the display name and how to map the servlet components. Because the edits are already in the file, you can just use the steps to view the settings.

  1. Click General at the top of the editor to open the general view.
  2. Enter hello2 in the Display Name field.
  1. Click Servlets at the top of the editor to open the servlets view.
  2. Click Add Servlet.
  3. In the Add Servlet dialog, enter GreetingServlet in the Servlet Name field.
  4. Enter servlets.GreetingServlet in the Servlet Class field.
  5. Enter /greeting in the URL Pattern field.
  6. Click OK.
  7. Repeat the preceding steps, except enter ResponseServlet as the servlet name, servlets.ResponseServlet as the servlet class, and /response as the URL pattern.

If you are not using NetBeans IDE, you can add these settings using a text editor.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. In the Projects tab, right-click the hello2 project and select Build.
  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello2/.
  2. Type ant. This target will build the WAR file and copy it to the tut-install/javaeetutorial5/examples/web/hello2/dist/directory.

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select Undeploy and Deploy.

To deploy the example using Ant, type ant deploy. The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown at the end of this section.

To run the application, first deploy the web module, and then open the URL http://localhost:8080/hello2/greeting in a browser.

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the web container will use for appending to a request for a URL (called a valid partial request) that is not mapped to a web component.

For example, suppose you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or JSP page, the file host:port/webapp/directory/welcome.html is returned to the client.

If a web container receives a valid partial request, the web container examines the welcome file list and appends to the partial request each welcome file in the order specified and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource in the WAR that matches.

If no welcome file is specified, the Application Server will use a file named index.XXX, where XXX can be html or jsp, as the default welcome file. If there is no welcome file and no file named index.XXX, the Application Server returns a directory listing.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Do one of the following, making sure that the JSP pages you specify are actually included in the WAR file:
    1. Click Pages at the top of the editor pane and enter the names of the JSP pages that act as welcome files in the Welcome Files field.
    2. Click XML at the top of the editor pane, specify the JSP pages using welcome-file elements and include these elements inside a welcome-file-list element. The welcome-file element defines the JSP page to be used as the welcome page.The example discussed in Encapsulating Reusable Content Using Tag Files has a welcome file.

Setting Initialization Parameters

The web components in a web module share an object that represents their application context (see Accessing the Web Context). You can pass initialization parameters to the context or to a web component.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click General at the top of the editor pane.
  6. Select the Context Parameters node.
  7. Click Add.
  8. In the Add Context Parameter dialog, do the following:
    1. Enter the name that specifies the context object in the Param Name field.
    2. Enter the parameter to pass to the context object in the Param Value field.
    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the context object
  • A param-value element that specifies the parameter to pass to the context object
  • A context-param element that encloses the previous two elements

For a sample context parameter, see the example discussed in The Example JSP Pages.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click Servlets at the top of the editor pane.
  6. After entering the servlet’s name, class, and URL pattern, click the Add button under the Initialization Parameters table.
  7. In the Add Initialization Parameter dialog:
    1. Enter the name of the parameter in the Param Name field.
    2. Enter the parameter’s value in the Param Value Field.
    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the name of the initialization parameter
  • A param-value element that specifies the value of the initialization parameter
  • An init-param element that encloses the previous two elements

Mapping Errors to Error Screens

When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component (see Handling Servlet Errors) and any type of error screen.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click Pages at the top of the editor pane.
  6. Expand the Error Pages node.
  7. Click Add.
  8. In the Add Error Page dialog:
    1. Click Browse to locate the page that you want to act as the error page.
    2. Enter the HTTP status code that will cause the error page to be opened in the Error Code field.
    3. Enter the exception that will cause the error page to load in the Exception Type field.
    4. Click OK.

Alternatively, you can click XML at the top of the editor pane and enter the error page mapping by hand using the following elements:

  • An exception-type element specifying either the exception or the HTTP status code that will cause the error page to be opened.
  • A location element that specifies the name of a web resource to be invoked when the status code or exception is returned. The name should have a leading forward slash (/).
  • An error-page element that encloses the previous two elements.

You can have multiple error-page elements in your deployment descriptor. Each one of the elements identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements.


Note –

You can also define error screens for a JSP page contained in a WAR. If error screens are defined for both the WAR and a JSP page, the JSP page’s error page takes precedence. See Handling JSP Page Errors.


For a sample error page mapping, see the example discussed in The Example Servlets.

Declaring Resource References

If your web component uses objects such as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required.

Although resource injection using annotations can be more convenient for the developer, there are some restrictions from using it in web applications. First, you can only inject resources into container-managed objects. This is because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into objects such as simple JavaBeans components. However, JavaServer Faces managed beans are managed by the container; therefore, they can accept resource injections.

Additionally, JSP pages cannot accept resource injections. This is because the information represented by annotations must be available at deployment time, but the JSP page is compiled after that; therefore, the annotation will not be seen when it is needed. Those components that can accept resource injections are listed in Table 3–1.

This section describes how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 25, Persistence in the Web Tier describes how web applications use annotations supported by the Java Persistence API. Chapter 30, Securing Web Applicationsdescribes how to use annotations to specify information about securing web applications.Table 3–1 Web Components That Accept Resource Injections

Component Interface/Class 
Servlets javax.servlet.Servlet
Servlet Filters javax.servlet.ServletFilter
Event Listeners javax.servlet.ServletContextListenerjavax.servlet.ServletContextAttributeListenerjavax.servlet.ServletRequestListenerjavax.servlet.ServletRequestAttributeListenerjavax.servlet.http.HttpSessionListenerjavax.servlet.http.HttpSessionAttributeListenerjavax.servlet.http.HttpSessionBindingListener
Taglib Listeners Same as above 
Taglib Tag Handlers javax.servlet.jsp.tagext.JspTag
Managed Beans Plain Old Java Objects 

Declaring a Reference to a Resource

The @Resource annotation is used to declare a reference to a resource such as a data source, an enterprise bean, or an environment entry. This annotation is equivalent to declaring a resource-ref element in the deployment descriptor.

The @Resource annotation is specified on a class, method or field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database:

@Resource javax.sql.DataSource catalogDS;
public getProductsByCategory() {
    // get a connection and execute the query
    Connection conn = catalogDS.getConnection();
    ..
}

The container injects this data source prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name catalogDS and the type, javax.sql.DataSource.

If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example:

@Resources ({
    @Resource (name="myDB" type=java.sql.DataSource),
    @Resource(name="myMQ" type=javax.jms.ConnectionFactory)
})

The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 25, Persistence in the Web Tier describes these annotations and the use of the Java Persistence API in web applications.

Declaring a Reference to a Web Service

The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRefannotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file:

...
import javax.xml.ws.WebServiceRef;
...
public class ResponseServlet extends HTTPServlet {
@WebServiceRef(wsdlLocation=
    "http://localhost:8080/helloservice/hello?wsdl")
static HelloService service;

Duke’s Bookstore Examples

In Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications a common example, Duke’s Bookstore, is used to illustrate the elements of Java Servlet technology, JavaServer Pages technology, the JSP Standard Tag Library, and JavaServer Faces technology. The example emulates a simple online shopping application. It provides a book catalog from which users can select books and add them to a shopping cart. Users can view and modify the shopping cart. When users are finished shopping, they can purchase the books in the cart.

The Duke’s Bookstore examples share common classes and a database schema. These files are located in the directory tut-install/javaeetutorial5/examples/web/bookstore/. The common classes are packaged into a JAR. Each of the Duke’s Bookstore examples must include this JAR file in their WAR files. The process that builds and packages each application also builds and packages the common JAR file and includes it in the example WAR file.

The next section describes how to create the bookstore database tables and resources required to run the examples.

Accessing Databases from Web Applications

Data that is shared between web components and is persistent between invocations of a web application is usually maintained in a database. To maintain a catalog of books, the Duke’s Bookstore examples described in Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications use the Java DB database included with the Application Server.

To access the data in a database, web applications use the new Java Persistence API (see Chapter 24, Introduction to the Java Persistence API). See Chapter 25, Persistence in the Web Tier to learn how the Duke’s Bookstore applications use this API to access the book data.

To run the Duke’s Bookstore applications, you need to first populate the database with the book data and create a data source in the application server. The rest of this section explains how to perform these tasks.

Populating the Example Database

  1. In a terminal window, go to the books directory or any one of the bookstore1 through bookstore6 example directories.
  2. Start the Java DB database server. For instructions, see Starting and Stopping the Java DB Database Server. You don’t have to do this if you are using NetBeans IDE. It starts the database server automatically.
  3. Type ant create-tables. This task runs a command to read the file tutorial.sql and execute the SQL commands contained in the file.
  4. At the end of the processing, you should see the following output:

[sql]

181 of 181 SQL statements executed successfully

When you are running create-tables, don’t worry if you see a message that an SQL statement failed. This usually happens the first time you run the command because it always tries to delete an existing database table first before it creates a new one. The first time through, there is no table yet, of course.

Creating a Data Source in the Application Server

A DataSource object has a set of properties that identify and describe the real world data source that it represents. These properties include information such as the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on.

Data sources in the Application Server implement connection pooling. To define the Duke’s Bookstore data source, you use the installed Derby connection pool named DerbyPool.

  1. Expand the Resources node.
  2. Expand the JDBC node.
  3. Select the JDBC Resources node.
  4. Click the New… button.
  5. Type jdbc/BookDB in the JNDI Name field.
  6. Choose DerbyPool for the Pool Name.
  7. Click OK.

Further Information about Web Applications

For more information on web applications, see:

Comments

comments

Close Menu
Show Buttons
Hide Buttons