The NetBeans E-commerce Tutorial - Introduction

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

Welcome to the NetBeans E-commerce Tutorial. In this multi-part tutorial, you learn how to create a simple yet effective e-commerce application that demonstrates various important features of Java web and EE development. In doing so, you'll familiarize yourself with the NetBeans IDE and become capable of applying it to your own development purposes.

Taking the time to master the IDE will ultimately lead you to become more efficient and versatile as a developer. While you work through the tutorial units, you'll learn how to make best use of the IDE's facilities and tools. These include:

  • Editor support for different languages: syntax highlighting, code completion, API documentation support, keyboard shortcuts, refactoring capabilities, and code templates
  • Window system: Projects, Files and Services windows, the Tasks window, Javadoc window, HTTP Monitor, Navigator and Palette
  • Integration with other services: automatic deployment to a registered server, database connectivity, browser interoperability
  • Development tools: Debugger, Profiler, HTTP Server Monitor, Local History support, and a graphical Diff Viewer

The tutorial is modular in fashion, with each unit focusing on specific concepts, technologies, and features of the IDE. You can successfully follow a tutorial unit on its own using the provided setup instructions and application snapshots (from Unit 5 onward). However, you'll get the most benefit by working through all units consecutively, from beginning to end. This will also help to illustrate the development process.

Unit 3, Setting up the Development Environment introduces you to the NetBeans IDE. In it, you create a Java web project which is the basis for the work you undertake in later tutorial units. In Unit 4, Designing the Data Model, you primarily work with MySQL WorkBench, a visual database design tool, to create a data model for the application. Each successive tutorial unit provides you with a project snapshot that corresponds to the project's beginning state for that given unit. This enables you to work through a single tutorial unit outside of the E-commerce Tutorial's larger context. To use these snapshots, download them to your computer and open them in the IDE using the Open Project wizard (Ctrl-Shift-O; ⌘-Shift-O on Mac).

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.

The remainder of this unit covers some information relevant to the tutorial, as well as basic concepts necessary for Java EE development. Make sure you understand the concepts outlined below before proceeding with development.



About this Tutorial

Who this Tutorial is for

The content of this tutorial caters to four demographics:

  • Java developers interested in expanding their skill set to include Java EE technologies
  • Newcomers to the NetBeans IDE wanting to try out its development environment
  • Web developers wanting to see how Java compares to other web-based technologies
  • Students wanting to understand the nuts and bolts a simple e-commerce application, and how its development could apply to a real-world use-case

If you fall into any of these categories, this tutorial will be helpful to you. Depending on your background, you may find that certain tutorial units are more difficult to grasp than others. Understanding how technologies work is key to leveraging the IDE for your purposes. Therefore, if you are really interested in learning the technologies involved, you may find that this tutorial works best as a companion to the Java EE Tutorial. For each tutorial unit, make best use of the provided links to relevant areas in the Java EE Tutorial, as well as to other useful resources.

What this Tutorial Covers

The application that you develop in this tutorial involves numerous concepts, technologies, and tooling components:

  • Concepts
    • Front-end development
    • Web application project structure
    • Data modeling
    • Database connectivity
    • Object-relational mapping
    • Session management
    • Transactional business logic
    • Client and server-side validation
    • Localization
    • Web application security
    • Design patterns, including Model-View-Controller (MVC) and Session Facade
  • Technologies
    • HTML, CSS, and JavaScript technologies
    • Servlet and JavaServer Pages (JSP) technologies
    • Enterprise JavaBeans (EJB) technology
    • Java Persistence API (JPA)
    • The JavaServer Pages Standard Tag Library (JSTL)
    • Java Database Connectivity (JDBC)
  • Development Tools
    • NetBeans IDE
    • GlassFish, a Java EE application server
    • MySQL, a relational database management server (RDBMS)
    • MySQL WorkBench, a visual database design tool

What is an E-commerce Application?

The term e-commerce, as we think of it today, refers to the buying and selling of goods or services over the Internet. For example, you may think of Amazon, which provides online shopping for various product categories, such as books, music, and electronics. This form of e-commerce is known as electronic retailing, or e-tailing, and usually involves the transportation of physical items. It is also referred to as business-to-customer, or B2C. Other well-known forms include:

  • Consumer-to-consumer (C2C): Transactions taking place between individuals, usually through a third-party site such as an online auction. A typical example of C2C commerce is eBay.
  • Business-to-business (B2B): Trade occurring between businesses, e.g., between a retailer and wholesaler, or between a wholesaler and manufacturer.
  • Business-to-government (B2G): Trade occurring between businesses and government agencies.

This tutorial focuses on business-to-customer (B2C) e-commerce, and applies the typical scenario of a small retail store seeking to create a website enabling customers to shop online. Software that accommodates a B2C scenario generally consists of two components:

  1. Store Front: The website that is accessed by customers, enabling them to purchase goods over the Internet. Data from the store catalog is typically maintained in a database, and pages requiring this data are generated dynamically.
  2. Administration Console: A password-protected area that is accessed over a secure connection by store staff for purposes of online management. This typically involves CRUD (create read update delete) access to the store catalog, management of discounts, shipping and payment options, and review of customer orders.

What is Java?

In the computer software industry, the term "Java" refers to the Java Platform as well as the Java Programming Language.

Java as a Programming Language

The Java language was conceptualized by James Gosling, who began work on the project in 1991. The language was created with the following 5 design principles[1] in mind:

  1. Simple, Object-Oriented, and Familiar: Java contains a small, consistent core of fundamental concepts that can be grasped quickly. It was originally modeled after the then popular C++ language, so that programmers could easily migrate to Java. Also, it adheres to an object-oriented paradigm; systems are comprised of encapsulated objects that communicate by passing messages to one another.
  2. Robust and Secure: The language includes compile-time and run-time checking to ensure that errors are identified quickly. It also contains network and file-access security features so that distributed applications are not compromised by intrusion or corruption.
  3. Architecture Neutral and Portable: One of Java's primary advantages is its portability. Applications can be easily transferred from one platform to another with minimum or no modifications. The slogan "Write once, run anywhere" accompanied the Java 1.0 release in 1995, and refers to the cross-platform benefits of the language.
  4. High Performance: Applications run quickly and efficiently due to various low-level features, such as enabling the Java interpreter to run independently from the run-time environment, and applying an automatic garbage collector to free unused memory.
  5. Interpreted, Threaded, and Dynamic: With Java, a developer's source code is compiled into an intermediate, interpreted form known as bytecode. The bytecode instructional set refers to the machine language used by the Java Virtual Machine (JVM). With a suitable interpreter, this language can then be translated into native code for the platform it is run on. Multithreading capabilities are supported primarily by means of the Thread class, enabling numerous tasks to occur simultaneously. The language and run-time system are dynamic in that applications can adapt to environment changes during execution.

If you'd like to learn more about the Java language, see the Java Tutorials.

Java as a Platform

The Java Platform signifies a software-based platform that is comprised of two parts:

  • The Java Virtual Machine (JVM): The JVM is an engine that executes instructions generated by the Java compiler. The JVM can be thought of as an instance of the Java Runtime Environment, or JRE, and is embedded in various products, such as web browsers, servers, and operating systems.
  • The Java Application Programming Interface (API): Prewritten code, organized into packages of similar topics. For instance, the Applet and AWT packages include classes for creating fonts, menus, and buttons.

The Java Development Kit, or JDK, refers to the Java SE Edition, while other kits are referred to as "SDK", a generic term for "software development kit." For example, the Java EE SDK.[2]

You can see a visual representation of the Java platform by viewing the conceptual diagram of component technologies provided in the JDK Documentation. As shown below, the diagram is interactive, enabling you click on components to learn more about individual technologies.
Diagram of JDK 6

As the diagram indicates, the JDK includes the Java Runtime Environment (JRE). You require the JRE to run software, and you require the JDK to develop software. Both can be acquired from Java SE Downloads.

The Java platform comes in several editions, such as Java SE (Standard Edition), Java ME (Micro Edition), and Java EE (Enterprise Edition).

Java EE

The Java Platform, Enterprise Edition (Java EE) builds upon the Java SE platform and provides a set of technologies for developing and running portable, robust, scalable, reliable and secure server-side applications.

EE technologies are loosely divided into two categories:

Depending on your needs, you may want to use certain technologies from either category. For example, this tutorial makes use of Servlet, JSP/EL, and JSTL "web" technologies, as well as EJB and JPA "enterprise" technologies.

Java EE currently dominates the market, especially in the financial sector. The following diagram is taken from an independent survey for European markets performed in 2007.

Survey Java EE vs .Net

For a recent, informal comparison of Java EE to .NET, see the blog post Java EE or .NET - An Almost Unbiased Opinion by a well-known member of the Java EE community.

What's the Difference Between...?

There are many abbreviations and acronyms to parse. If you're new to all of this and find the above explanation somewhat confusing, the following resources can help explain what the differences are between some of the commonly used terminology.


What is the Java Community Process?

The Java Community Process (JCP) is a program that manages the development of standard technical specifications for Java technology. The JCP catalogs Java Specification Requests (JSRs), which are formal proposals that document the technologies which are to be added to the Java platform. JSRs are run by an Expert Group, which typically comprises representatives of companies that are stakeholders in the industry. The JCP enables Java technology to grow and adapt according to the needs and trends of the community.

The JSRs of technologies used and referred to in this tutorial include the following:

You can use the JCP website to search for individual JSRs. You can also view all current EE technologies (Java EE 6) at:

Java EE 5 technologies are listed at:

A JSR's final release provides a reference implementation, which is a free implementation of the technology. In this tutorial, you utilize these implementations to develop the sample e-commerce application. For example, the GlassFish v3 application server, which is included in the standard Java download bundle for NetBeans 6.8, is the reference implementation of the Java EE 6 platform specification (JSR 316). As a reference implementation for the Java EE platform, it includes reference implementations for the technologies included in the platform, such as Servlet, EJB and JPA technologies.


Why use an IDE?

Firstly, the term IDE stands for integrated development environment. The purpose of an IDE has traditionally been to maximize a developer's productivity by providing tools and support such as:

  • a source code editor
  • a compiler and build automation tools
  • a window system for viewing projects and project artifacts
  • integration with other commonly-used services
  • debugging support
  • profiling support

Consider what would be necessary if you wanted to create a Java-based web application manually. After installing the Java Development Kit (JDK), you would need to set up your development environment by performing the following steps.[3]

  1. Set your PATH environment variable to point to the JDK installation.
  2. Download and configure a server that implements the technologies you plan to use.
  3. Create a development directory where you plan to create and work on the web application(s). Furthermore, you are responsible for setting up the application directory structure so that it can be understood by the server. (For example, see Java BluePrints: Strategy for Web Applications for a recommended structure.)
  4. Set your CLASSPATH environment variable to include the development directory, as well as any required JAR files.
  5. Establish a deployment method, i.e., a way to copy resources from your development directory to the server's deployment area.
  6. Bookmark or install relevant API documentation.

For educative purposes, it is worthwhile to create and run a Java web project manually so that you are aware the necessary steps involved. But eventually, you'll want to consider using tools that reduce or eliminate the need to perform tedious or repetitious tasks, thereby enabling you to focus on developing code that solves specific business needs. An IDE streamlines the process outlined above. As demonstrated in Unit 3, Setting up the Development Environment, you'll install NetBeans IDE with the GlassFish application server, and be able to set up a web application project with a conventional directory structure using a simple 3-step wizard. Furthermore, the IDE provides provides built-in API documentation which you can either call up as you code in the editor, or maintain open in an external window.

An IDE also typically handles project compilation and deployment in a way that is transparent to you as a developer. For example, the web project that you create in NetBeans includes an Ant build script that is used to compile, clean, package and deploy the project. This means that you can run your project from the IDE, and it will automatically be compiled and deployed, then open in your default browser. Taking this a step further, many IDEs support a Deploy on on Save feature. In other words, whenever you save changes to your project, the deployed version on your server is automatically updated. You can simply switch to the browser and refresh the page to view changes.

IDEs also provide templates for various file types, and often enable you to add them to your project by suggesting common locations and including default configuration information where necessary.

Aside from the "basic support" described above, IDEs typically provide interfaces to external tools and services (e.g., application and database servers, web services, debugging and profiling facilities, and collaboration tools) which are indispensable to your work if Java development is your profession.

Finally, IDEs usually provide enhanced editor support. The editor is where you likely spend most of your time working, and IDE editors typically include syntax highlighting, refactoring capabilites, keyboard shortcuts, code completion, hints and error messages, all aiming to help you work more efficiently and intelligently.


Why use NetBeans?

The NetBeans IDE is a free, open-source integrated development environment written entirely in Java. It offers a range of tools for create professional desktop, enterprise, web, and mobile applications with the Java language, C/C++, and even scripting languages such as PHP, JavaScript, Groovy, and Ruby.

People are saying great things about NetBeans. For a list of testimonials, see NetBeans IDE Testimonials. Many developers are migrating their applications to NetBeans from other IDEs. For reasons why, read Real Stories From People Switching to NetBeans IDE.

The IDE provides many features for web development, and several advantages over other IDEs. Here are several noteworthy points:

  • Works Out of the Box: Simply download, install, and run the IDE. With its small download size, installation is a breeze. The IDE runs on many platforms including Windows, Linux, Mac OS X and Solaris. All IDE tools and features are fully integrated - no need to hunt for plug-ins - and they work together when you launch the IDE.
  • Free and Open Source: When you use the NetBeans IDE, you join a vibrant, open source community with thousands of users ready to help and contribute. There are discussions on the NetBeans project mailing lists, blogs on Planet NetBeans, and helpful FAQs and tutorials on the community wiki.
  • Profiling and Debugging Tools: With NetBeans IDE profiler, you get real time insight into memory usage and potential performance bottlenecks. Furthermore, you can instrument specific parts of code to avoid performance degradation during profiling. The HeapWalker tool helps you evaluate Java heap contents and find memory leaks.
  • Customizable Projects: Through the NetBeans IDE build process, which relies on industry standards such as Apache Ant, make, Maven, and rake - rather than a proprietary build process - you can easily customize projects and add functionality. You can build, run, and deploy projects to servers outside of the IDE.
  • Collaboration Tools: The IDE provides built-in support for version control systems such as CVS, Subversion, and Mercurial.
  • Extensive Documentation: There's a wealth of tips and instructions contained in the IDE's built-in help set. Simply press F1 (fn-F1 on Mac) on a component in the IDE to invoke the help set. Also, the IDE's official knowledge base provides hundreds of online tutorials, articles and screencasts that are continuously being updated.

For a more extensive list of reasons why you should consider choosing NetBeans, see NetBeans IDE Connects Developers.


See Also


References

  1. ^ The white paper, The Java Language Environment, outlines the 5 design principles.
  2. ^ Current version names and numbers are defined in Java SE 6, Platform Name and Version Numbers.
  3. ^ These steps are loosely based on those outlined in Chapter 2: Server Setup and Configuration, from Core Servlets and JavaServer Pages, by Marty Hall and Larry Brown. This book is freely available in PDF format from: http://pdf.coreservlets.com/




The NetBeans E-commerce Tutorial - Designing the Application

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

The application that you design in this tutorial is based on a real-world scenario. After being introduced to the tutorial scenario, you consolidate a high-level list of customer requirements. You then prepare a diagram of the application's business process flow, and a series of mockups which help both you and your customer get a clearer picture of how the final application will look to an end-user. Finally, you break down the customer requirements into a set of implementation tasks, and structure your application so that the responsibilities and interactions among functional components are clearly defined.

This tutorial unit discusses the MVC (Model-View-Controller) design pattern. After investigating the benefits that this pattern offers, you set about mapping JSP, Servlet, and other technologies to the MVC architecture, and draft a diagram that illustrates the components of the application in terms of MVC.

This unit makes various references to Designing Enterprise Applications with the J2EE Platform, Second Edition. This book contains guidelines promoted by Java BluePrints.

Although this tutorial unit does not require use of the NetBeans IDE, it is essential because it lays the groundwork for tasks that will be covered in the following units.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



The Scenario

This tutorial is based on the following scenario. Although this is a fictitious scenario, it demonstrates how the software you are about to develop can be applied to real-world business needs. It also serves as a platform from which you can derive customer requirements. Customer requirements should be established as clearly as possible before any design or implementation begins.



Gathering Customer Requirements

The initial phase of any project involves gathering information before making any design or implementation decisions. In its most common form, this involves direct and frequent communication with a customer. Based on the provided scenario, the Affable Bean staff have communicated to you that the application you are to create should fulfill the following requirements:

  1. An online representation of the products that are sold in the physical store. There are four categories (dairy, meats, bakery, fruit & veg), and four products for each category, which online shoppers can browse. Details are provided for each product (i.e., name, image, description, price).
  2. Shopping cart functionality, which includes the ability to:
    • add items to a virtual shopping cart.
    • remove items from the shopping cart.
    • update item quantities in the shopping cart.
    • view a summary of all items and quantities in the shopping cart.
    • place an order and make payment through a secure checkout process.
  3. An administration console, enabling staff to view customer orders.
  4. Security, in the form of protecting sensitive customer data while it is transferred over the Internet, and preventing unauthorized access to the administration console.
  5. Language support for both English and Czech. (Website only)

The company staff are able to provide you with product and category images, descriptions and price details, as well as any website graphics that are to be used. The staff are also able to provide all text and language translations for the website.

There are many practices and methods devoted to software development management. Agile software development is one methodology that encourages frequent customer inspection, and places importance on adaptation during the development cycle. Although this is outside the scope of this tutorial, each tutorial unit concludes with a functional piece of software that could be presented to a customer for further communication and feedback.


Preparing Mockups

After gathering customer requirements, you work with the Affable Bean staff to gain a clearer picture of how they expect the website to look and behave. You create a use-case that describes how the application will be used and encapsulates its behavior:



You also begin creating mockups. There are numerous ways to go about this task. For example, you could use storyboard software, or create a set of wireframes to relay the relationships between pages. Another common method is known as paper prototyping, where you collaborate with the customer by sketching ideas on paper.

In this scenario, we've produced mockups of the primary pages the user expects see when navigating through the website. When we later discuss the MVC design pattern, you'll note that these pages map to the views used by the application.

Mockup of welcome page

welcome page

The welcome page is the website's home page, and entry point for the application. It introduces the business and service to the user, and enables the user to navigate to any of the four product categories.

Mockup of category page

category page

The category page provides a listing of all products within the selected category. From this page, a user is able to view all product information, and add any of the listed products to his or her shopping cart. A user can also navigate to any of the provided categories.

Mockup of cart page

cart page

The cart page lists all items held in the user's shopping cart. It displays product details for each item, and tallies the subtotal for the items in the cart. From this page, a user can:

  • Clear all items in his or her cart
    (Clicking 'clear cart' causes the 'proceed to checkout' buttons and shopping cart table to disappear.)
  • Update the quantity for any listed item
    (The price and quantity are updated; the subtotal is recalculated. If user sets quantity to '0', the product table row is removed.)
  • Return to the previous category by clicking 'continue shopping'
  • Proceed to checkout
Mockup of checkout page

checkout page

The checkout page collects information from the customer using a form. This page also displays purchase conditions, and summarizes the order by providing calculations for the total cost.

The user is able to send personal details over a secure channel.

Mockup of confirmation page

confirmation page

The confirmation page returns a message to the customer confirming that the order was successfully recorded. An order reference number is provided to the customer, as well as a summary listing order details.

Order summary and customer personal details are returned over a secure channel.

Also, you agree with staff on the following rules, which apply to multiple pages:

  • The user is able to proceed to checkout from any page, provided that:
    • The shopping cart is not empty
    • The user is not already on the checkout page
    • The user has not already checked out (i.e., is on the confirmation page)
  • From all pages, the user is able to:
    • View the status of his or her shopping cart (if it is not empty)
    • Return to the welcome page by clicking the logo image
  • The user is able to select the language (English or Czech) to view the page in for all pages except the confirmation page.

Note: Although not presented here, you would equally need to work with the client to produce use-cases and mockups, and establish rules for the administration console. The NetBeans E-commerce Tutorial focuses on developing the store front (i.e., the website). However, Unit 11, Securing the Application demonstrates how to create a login mechanism to access the administration console. Also, you can examine the provided implementation of the administration console by downloading the completed application.

The Business Process Flow

To help consolidate the relationships between the proposed mockups and better illustrate the functionality that each page should provide, you prepare a diagram that demonstrates the process flow of the application.

The diagram displays the visual and functional components of each page, and highlights the primary actions available to the user in order to navigate through the site to complete a purchase.

Process-flow diagram of the AffableBean application

Determining the Architecture

Before you start coding, let's examine the ways in which you can architect the project. Specifically, you need to outline the responsibilities among functional components, and determine how they will interact with each other.

When you work with JSP technologies, you can code all of your business logic into JSP pages using scriptlets. Scriptlets are snippets of Java code enclosed in <% %> tags. As you may already be aware, JSP pages are compiled into servlets before they are run, so Java code is perfectly valid in JSP pages. However, there are several reasons why this practice should be avoided, especially when working in large projects. Some reasons are outlined in Designing Enterprise Applications with the J2EE Platform, Second Edition as follows:[1]

  • Scriptlet code is not reusable: Scriptlet code appears in exactly one place: the JSP page that defines it. If the same logic is needed elsewhere, it must be either included (decreasing readability) or copied and pasted into the new context.
  • Scriptlets mix logic with presentation: Scriptlets are islands of program code in a sea of presentation code. Changing either requires some understanding of what the other is doing to avoid breaking the relationship between the two. Scriptlets can easily confuse the intent of a JSP page by expressing program logic within the presentation.
  • Scriptlets break developer role separation: Because scriptlets mingle programming and Web content, Web page designers need to know either how to program or which parts of their pages to avoid modifying.
  • Scriptlets make JSP pages difficult to read and to maintain: JSP pages with scriptlets mix structured tags with JSP page delimiters and Java language code.
  • Scriptlet code is difficult to test: Unit testing of scriptlet code is virtually impossible. Because scriptlets are embedded in JSP pages, the only way to execute them is to execute the page and test the results.

There are various design patterns already in existence which provide considerable benefits when applied. One such pattern is the MVC (Model-View-Controller) paradigm, which divides your application into three interoperable components:[2]

  • Model: Represents the business data and any business logic that govern access to and modification of the data. The model notifies views when it changes and lets the view query the model about its state. It also lets the controller access application functionality encapsulated by the model.
  • View: The view renders the contents of a model. It gets data from the model and specifies how that data should be presented. It updates data presentation when the model changes. A view also forwards user input to a controller.
  • Controller: The controller defines application behavior. It dispatches user requests and selects views for presentation. It interprets user inputs and maps them into actions to be performed by the model. In a web application, user inputs are HTTP GET and POST requests. A controller selects the next view to display based on the user interactions and the outcome of the model operations.
Diagram of the MVC pattern

Adhering to the MVC design pattern provides you with numerous benefits:

  • Separation of design concerns: Because of the decoupling of presentation, control, and data persistence and behavior, the application becomes more flexible; modifications to one component have minimal impact on other components. You can, for example, create new views without needing to rewrite the model.
  • More easily maintainable and extensible: Good structure can reduce code complexity. As such, code duplication is minimized.
  • Promotes division of labor: Developers with different skill sets are able to focus on their core skills and collaborate through clearly defined interfaces.

Note: When JSP technology was first introduced in 1999, the early specifications included a description of two model architectures: Model 1 and Model 2. Model 1 involves implementing business logic directly within JSP pages, whereas Model 2 applies the MVC pattern. For more information on Model 1 and Model 2 architectures, see Designing Enterprise Applications with the J2EE Platform, section 4.4.1: Structuring the Web Tier.

You can apply the MVC pattern to the application that you develop for the Affable Bean company. You can use a servlet as a controller to handle incoming requests. The pages from the business process flow diagram can be mapped to views. Finally, the business data, which will be maintained in a database, can be accessed and modified in the application using EJB session beans with JPA entity classes. These components represent the model.

MVC diagram of the AffableBean application


Planning the Project

In order to plan the project, you need to extrapolate functional tasks from the customer requirements. The tasks that we produce will structure the implementation plan for the project, and form the outline for tutorial units that follow. In practice, the more capable you are of identifying tasks and the work they entail, the better you'll be able to stick to the schedule that you and your customer agree upon. Therefore, begin with a high-level task list, then try to drill down from these tasks dividing each task into multiple sub-tasks, and possibly dividing sub-tasks further until each list item represents a single unit of work.

  • Set up the development environment
    • Register the development server in the IDE
    • Create a web project in the IDE
    • Run the web project from the IDE (test compilation, deployment, run capabilities, and ensure interoperability between IDE, server and browser)
    • Register the database server in the IDE
    • Establish a connection to the database server from the IDE
    • Create a database instance on the database server
  • Prepare the data model for the application
    • Create an entity-relationship diagram (use a visual database design tool)
      • Identify objects
      • Create a schema
      • Create entities
      • Add entity properties
      • Identify relationships between entities
        • One-to-Many relationships
        • Many-to-Many relationships
    • Forward-engineer the entity-relationship diagram into an SQL script
    • Run the script on the database server to generate the schema
  • Create front-end project files
    • Stylesheet
    • Placeholders for JSP pages (requires implementing HTML and CSS content to get pages to display like mockups)
      • welcome page
      • category page
      • cart page
      • checkout page
      • confirmation page
  • Organize the application front-end
    • Place JSP pages in the application's WEB-INF directory
    • Create page header and footer
    • Remove instances of code duplication (header and footer code from JSP pages)
    • Register header and footer includes with the web deployment descriptor
  • Create a controller servlet
    • Create mappings for views in deployment descriptor
    • Create skeleton code in servlet to handle client requests
  • Connect the application to the database
    • Add sample data to the database
    • Create data source and connection pool on server
    • Test data source (ping connection pool)
    • Ensure that views can access data from the database
      • Add database driver JAR to server
      • Create a resource reference to the data source in the application
      • Query the database from a JSP page
    • Set any necessary application-wide parameters
    • Code database-access and conditional logic in views that do not require user session (welcome, category)
  • Develop the business logic
    • Set up the model
      • Create JPA entity classes from database tables
      • Create and configure persistence unit
      • Create EJB stateless bean facades for entity classes
    • Integrate EJB model with views
      • Integrate EJB facades in controller servlet
      • Modify views to use data from scoped variables (instead of any JSTL <sql> queries)
    • Create shopping cart functionality
      • Create Java classes to hold temporary data (ShoppingCart, ShoppingCartItem)
      • Integrate code for HttpSession object into controller servlet
      • Add session-related actions to controller servlet
      • Create shopping cart widget in page header
      • Integrate session-related data into views (cart, checkout)
      • Apply JSTL <c:url> tags to enable url-rewriting in the event that user has disabled cookies
      • Configure session time-out in web deployment descriptor
      • Add logic to controller servlet handle requests in the event of session time-out
    • Integrate transactional logic
      • Create code to extract and validate user data from checkout form
      • Create an EJB stateless session bean to handle inserting orders and customers into database
      • Implement logic to query the database on newly-created orders
      • Implement order and customer details display in confirmation page
  • Add language support
    • Create a properties file containing messages for all text in the application
      • default language (English)
      • English
      • Czech
    • Register a localization context parameter in deployment descriptor
    • Add logic to view that sets page language based on language value saved in user's session
    • Apply <fmt:message> tags to all text contained in view
    • Factor out English description from database (optional), use resource bundles instead
  • Create administration console
    • Create new artifacts
      • Views
        • login
        • welcome
        • error
      • Controller servlet
    • Create login functionality
      • Create interface
      • Add actions to controller servlet
      • Configure login functionality in deployment descriptor
    • Implement admin functionality (in welcome page)
      • For viewing order details
      • For viewing customer details
  • Secure the application
    • Configure SSL connection for checkout, confirmation views, and administration console
      • Enable SSL on server
      • Register security settings in deployment descriptor
    • Create user roles and permissions for administration console
      • Create security roles on server
      • Declare security roles, constraints in deployment descriptor

See Also


References

  1. ^ For a more extensive list, see Designing Enterprise Applications with the J2EE Platform, section 4.2.6.8: Using Custom Tags to Avoid Scriptlets.
  2. ^ For more information on the MVC pattern, see Designing Enterprise Applications with the J2EE Platform, section 11.1.1: Model-View-Controller Architecture.




The NetBeans E-commerce Tutorial - Setting up the Development Environment

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

The following steps describe how to set up your development environment. In the process, you'll learn about some of the primary windows of the IDE and understand how the IDE uses an Ant build script to perform common actions on your project. By the end of this tutorial unit, you'll have created a web application project, and confirmed that you can successfully build the project, deploy it to your development server, and run it from the IDE.

You also learn how to connect the IDE to a MySQL database server, create database instances, and connect to database instances from the IDE's Services window. In this unit, you create a new database named affablebean, which you will use throughout the tutorial.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.

Creating a Web Project

  1. Start the NetBeans IDE. If you are running the IDE for the first time, you will see the IDE's Start Page.
    NetBeans IDE Start Page
  2. Click the New Project ( New Project icon ) button (Ctrl-Shift-N; ⌘-Shift-N on Mac) to create a new Java web project. The New Project wizard opens to guide you through the process. Under Categories choose Java Web, then under Projects choose Web Application.
    New Project wizard
  3. Click Next.
  4. In Step 2: Name and Location, name the project AffableBean. In this step, you can also designate the location on your computer where the project will reside. By default, the IDE creates a NetBeansProjects folder in your home directory. If you'd like to change the location, enter the path in the Project Location text field.
  5. Click Next.
  6. In Step 3: Server and Settings, specify GlassFish v3 as the server to which your project will be deployed during development. Since you've included GlassFish v3 in your NetBeans installation, you'll see that GlassFish v3 is listed in the Server drop-down field.

    If you wanted to deploy to a server that isn't yet registered with the IDE, you would click the Add button, and step through the Add Server Instance wizard. You can view all servers registered with the IDE from the Servers window (Choose Tools > Servers from the main menu).

  7. For Java EE Version, select Java EE 6 Web.

    The application that you create makes use of various Java EE 6 features, namely servlet annotations (new in the Servlet 3.0 Specification), and EJBs used directly in servlet containers (new in the EJB 3.1 Specification). Both Servlet 3.0 and EJB 3.1 are part of the Java EE 6 platform, therefore you require an EE-6 compliant server such as GlassFish v3 to work through this tutorial. For more information, see About Specifications and Implementations.
  8. Make sure that the 'Enable Contexts and Dependency Injection' option is deselected. This option is specific to the Contexts and Dependency Injection (CDI) technology, specified by JSR-299, and is not used in this tutorial. For more information, see Getting Started with Contexts and Dependency Injection and JSF 2.0.
    New Web Application wizard, Step 3: Server and Settings

    Note that by default the context path for the application is the name of the project. This is the path at which your application can be accessed after it is deployed to the server. For example, GlassFish uses 8080 as its default port number, so during development you'll be able to access the project in a browser window from:
    http://localhost:8080/AffableBean/
  9. Click Finish. The IDE generates a skeleton project named AffableBean that adheres to the J2EE Blueprints conventions for web application structure. The IDE displays various windows in its default layout.
    NetBeans IDE - default layout
  10. Examine the IDE's default layout. Here's a brief overview of the displayed windows and tabs:
    • The Editor: The editor (Ctrl-0; ⌘-0 on Mac) is the central component of the IDE, and is likely where you'll spend most of your time. The editor automatically adapts to the language you are working in, providing documentation support, code-completion, hints and error messages specific to the technology you are coding in.
    • Projects window: The Projects window (Ctrl-1; ⌘-1 on Mac) is the entry point to your project sources. It provides a logical view of important project contents, and groups files together based on their function (e.g., Configuration Files). When right-clicking file nodes within the Projects window, you can call actions common to your development tasks (i.e., Build, Clean, Deploy, Run).
    • Files window: The Files window (Ctrl-2; ⌘-2 on Mac) provides a directory-based view of your project. That is, it enables you to view the structure of your project, as it exists in your computer's file system. From this window, you can view all files pertaining to your project, including the Ant build script, (build.xml), and files required by the IDE to handle the project (contained in the nbproject folder). If you've run your project, you can see the location of compiled Java files (build folder). If you've explicitly built your project (by choosing Build, or Clean and Build, from the project node's right-click menu in the Projects window), you can view the project's distributable WAR file (contained in the dist folder).
    • Navigator: The Navigator (Ctrl-7; ⌘-7 on Mac) provides a structural overview of the file opened in the editor. For example, if an HTML web page is displayed, the Navigator lists tag nodes in a way that corresponds to the page's Document Object Model (DOM). If a Java class is opened in the editor, the Navigator displays the properties and methods pertaining to that class. You can use the Navigator to navigate to items within the editor. For example, when you double-click a node in the Navigator, your cursor is taken directly to that element in the editor.
    • Tasks window: The Tasks window (Ctrl-6; ⌘-6 on Mac) automatically scans your code and lists lines with compile errors, quick fixes, and style warnings. For Java classes, it also lists commented lines containing words such as 'TODO' or 'FIXME'.
    • Services window: The Services window (Ctrl-5; ⌘-5 on Mac) provides an interface for managing servers, web services, databases and database connections, as well as other services relating to team development.
    • Output window: (Not displayed) The Output window (Ctrl-4; ⌘-4 on Mac) automatically displays when you call an action that invokes a service, generally from an outside resource such as a server, and can mirror server log files. With web projects, it also enables you to view information related to Ant tasks (e.g., Build, Clean and Build, Clean).
    • Palette: (Not displayed) The Palette (Ctrl-Shift-8; ⌘-Shift-8 on Mac) provides various handy code snippets that you can drag and drop into the editor. Many of the snippets included in the Palette are also accessible by invoking code completion in the editor, as will later be demonstrated.

    Note: All of the IDE's windows can be accessed from the Window menu item.

Running the Web Project

  1. Run the new AffableBean project. In the Projects window, you can do this by right-clicking the project node and choosing Run, otherwise, click the Run Project ( Run Project icon ) button (F6; fn-F6 on Mac) in the IDE's main toolbar.

    A browser window opens to display the project's welcome page.
    Project welcome page displayed in browser
    So what just happened? When you run a web project, the IDE invokes the run Ant target in your project's build script. You can investigate by opening your project's build.xml file in the editor.
  2. Switch to the Files window (Ctrl-2; ⌘-2 on Mac), expand the project node and double-click the build.xml file contained in your project. When the build.xml file opens in the editor, the Navigator lists all Ant targets available to the script.
    Navigator displaying Ant targets for build.xml

    Normal Ant targets are displayed using the general target ( Normal Ant target icon ) icon. The emphasized Ant target ( Emphasized Ant target icon ) icon merely indicates that the target includes a description, which is displayed as a tooltip (as shown in the above image). For more information, see Creating Java Projects in Developing Applications with NetBeans IDE.

  3. Double-click the run target. The build-impl.xml file opens in the editor and displays the target definition.
    <target depends="run-deploy,run-display-browser" description="Deploy to server and show in browser." name="run"/>
    Why did the build-impl.xml file open when we clicked on a target from build.xml? If you switch back to build.xml (press Ctrl-Tab) and examine the file contents, you'll see the following line:
    <import file="nbproject/build-impl.xml"/>

    The project's build script is basically an empty file that imports NetBeans-defined targets from nbproject/build-impl.xml.

    You can freely edit your project's standard build.xml script by adding new targets or overriding existing NetBeans-defined targets. However, you should not edit the build-impl.xml file.

    You can see from the run target's definition that it depends on the following targets:
    • run-deploy
    • run-display-browser
    Both of these targets in turn depend on other targets, which you can examine elsewhere in the build-impl.xml file. But essentially, the following actions take place when the run target is invoked:
    1. The project gets compiled.
    2. A WAR file is created.
    3. The server starts (if it is not already running).
    4. The WAR file gets deployed to the designated server.
    5. The browser opens to display the server's URL and application's context path.

    Consult the official Ant Manual for more information on using Ant.

  4. To generate a distributable WAR file for your project, choose Clean and Build Project (or Clean and Build Main Project) from the IDE's Run menu.
  5. In the Files window (Ctrl-2; ⌘-2 on Mac) expand the project node. The dist folder contains the project WAR file. The build folder contains your compiled project.
    Files window

    Note: If you clean the project (In the Projects window, choose Clean from the project node's right-click menu), both of these folders are removed.

  6. Switch to the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers > GlassFish Server 3 > Applications node.
    Services window - GlassFish v3

    Note: "GlassFish v3" is the default server name for NetBeans 6.8 users.

    The green arrow icon on the GlassFish server node ( GlassFish server node in Services window ) indicates that the server is running. The Applications folder lists all deployed applications; you can see that the AffableBean application has been successfully deployed.

At this stage, you've created a Java web project in the IDE, and have confirmed that it can be successfully built and deployed to your development server, and opened in a browser when run.


Communicating with the Database Server

Once you've downloaded and installed the MySQL database server, you can connect to it from the IDE. A default installation uses 'root' and '' (an empty string) as the user account and password to connect to the database server. However, due to connectivity issues with GlassFish, it is recommended that you use an account with a non-empty password.[1] The following instructions demonstrate how to run the database server and change the password for the root account to 'nbuser' from the MySQL command-line. The 'root' / 'nbuser' combination is used throughout the NetBeans E-commerce Tutorial. With the database server running and properly configured, you register it in the IDE and create a database instance.

Note: The command-line instructions below assume that you have added the mysql command to your PATH environment variable. (If you haven't, you'll receive a 'mysql: command not found' error when entering mysql commands in your command-line.)

If you haven't added mysql to your PATH, you can instead call the command by entering the full path to your MySQL installation's bin directory. For example, if the mysql command is located on your computer at /usr/local/mysql/bin, you would enter the following:

shell> /usr/local/mysql/bin/mysql -u root

For more information, see the offical MySQL Reference Manual:


Perform the following steps.

Check if the MySQL Server is Running

Before connecting to the MySQL server from the IDE, you need to make sure the server is running. One way to do this is by using the mysqladmin client's ping command.

  1. Open a command-line prompt and type in the following:
    shell> mysqladmin ping
    If the server is running, you will see output similar to the following:
    mysqld is alive
    If the server is not running, you'll see output similar to the following:
    mysqladmin: connect to server at 'localhost' failed
    error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock'
    Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!

Start the Database Server

In the event that your MySQL server is not running, you can start it from the command-line. See 2.13.1.2. Starting and Stopping MySQL Automatically for a brief, cross-platform overview. The following steps provide general guidance depending on your operating system.

Unix-like systems:

For Unix-like systems, it is recommended to start the MySQL server by invoking mysqld_safe.

  1. Open a command-line prompt and run the mysqld_safe command:
    shell> sudo ./mysqld_safe
    You will see output similar to the following:
    090906 02:14:37 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data

Windows:

The MySQL Windows installer enables you to install the database server as a Windows service, whereby MySQL starts and stops automatically with the operating system. If you need to start the database manually, run the mysqld command from the installation directory's bin folder.

  1. Open a Windows console window (from the Start menu, choose Run and type cmd in the text field). A command-line window displays.
  2. Enter this command (The indicated path assumes you have installed version 5.1 to the default install location):
    C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld"

For more information, refer to the official MySQL Reference Manual: 2.4.5.5. Starting MySQL from the Windows Command Line.

Change the Password

To set the root account's password to 'nbuser', perform the following steps.

  1. Open a command-line prompt and type in the following:
    shell> mysql -u root
    mysql> UPDATE mysql.user SET Password = PASSWORD('nbuser') WHERE User = 'root';
    mysql> FLUSH PRIVILEGES;

For more information, see the official MySQL Reference Manual: 2.13.2. Securing the Initial MySQL Accounts.

Register the Server in the IDE

The IDE's Services window enables you to connect to the server, start and stop the server, view database instances and the data they contain, as well as run an external administration tool on the server.

  1. In the Services window, right-click the Databases node and choose Register MySQL Server.
    Services window - right-click options on Databases node
    In the MySQL Server Properties dialog, under the Basic Properties tab, you can see the default settings for the MySQL server installation. These are:
    • Server Host Name: localhost
    • Server Port Number: 3306
    • Administrator User Name: root
    • Administrator Password: nbuser
  2. Select the Save Password option.
    MySQL Server Properties dialog
  3. Click OK. The IDE connects to your MySQL database server, and lists database instances that are maintained by the server. If you expand the Drivers node, you can also see that the IDE contains the Connector/J JDBC driver for MySQL.
    Services window - MySQL Server
    The application server (i.e., GlassFish) requires the driver to enable communication between your Java code and the the MySQL database. Because the IDE already contains the Connector/J driver, you do not need to download it. Furthermore, as will later be demonstrated, you can specify in your server settings to enable JDBC driver deployment so that the driver will be automatically deployed to GlassFish if it is missing on the server.

    Steps 4-7 below are optional. You can configure the IDE to start and stop the MySQL server, as well as run an external administration tool on the server.
  4. Right-click the MySQL server node and choose Properties. In the MySQL Server Properties dialog, select the Admin Properties tab.
  5. In the 'Path/URL to admin tool' field, enter the path on your computer to the executable file of a database administration tool, such as MySQL Administrator. The MySQL Administrator is included in the MySQL GUI Tools bundle.
  6. In the 'Path to start command' field, type in the path to the MySQL start command (i.e., mysqld or mysqld_safe, depending on your operating system. (See Start the Database Server above.)

    Note: For Unix-like systems, you may find that you can only invoke the start command with root or administrative privileges. To overcome this, you can create a script (using GKSu for Linux and Solaris, osascript for Mac) that will accomplish this task. For more information, see this blog post.

  7. In the 'Path to stop command' field, enter the path to the MySQL stop command (i.e., mysqladmin shutdown). Because the command requires a user account with shutdown privileges, you must enter username/password credentials in the Arguments field. For example:
    • Arguments: -u root -pnbuser shutdown

After you have set the fields listed under the Advanced Properties tab, you can:

  • Start the MySQL server: Right-click the MySQL server node and choose Start.
  • Stop the MySQL server: Right-click the MySQL server node and choose Stop.
  • Run the external administration tool: Right-click the MySQL server node and choose Run Administration Tool.

Create a Database Instance

  1. Create the database instance which you will use in this tutorial. To do so, right-click the MySQL Server node and choose Create Database.
  2. In the dialog that displays, type in affablebean. Select the 'Grant Full Access to' option, then select from the drop-down field. This enables the root account on the localhost host access to the database. Later, when you create a connection pool on the server, you'll need to provide the root account and nbuser password as username/password credentials in order to grant the server access to the database.
    Create MySQL Database dialog
  3. Click OK. When you do so, the database named affablebean is created, and a connection to the database is automatically established. Connections are displayed in the Services window using a connection node ( Database connection node ).

    Note: Connection nodes are persisted in the Services window. If you restart the IDE, the connection node displays with a jagged line ( Database connection node - disconnected ), indicating that the connection is broken. To reconnect to a database, make sure that the database server is running, then right-click the node and choose Connect.

  4. Expand the connection node for the affablebean database. The connection contains the database's default schema (affablebean), and within that are nodes for tables, views, and procedures. Currently these are empty since we haven't created anything yet.
    Services window - Database connection for 'affablebean'

At this stage, you've connected to the MySQL server from the IDE and have created a new database named affablebean which you'll use throughout the tutorial. Also, you've created a Java web project in the IDE, and have confirmed that it can be successfully built and deployed to your development server, and opened in a browser when run. Now that your development environment is ready, you can begin drafting the application's data model.


See Also


References

  1. ^ Using GlassFish v3, you can create a connection pool to a MySQL database server using an empty password. GlassFish Open Source Edition 3.0.1, included with NetBeans IDE 6.9, does not enable a connection using an empty password. See GlassFish Issue 12221.




The NetBeans E-commerce Tutorial - Designing the Data Model

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

This tutorial unit focuses on data modeling, or the process of creating a conceptual model of your storage system by identifying and defining the entities that your system requires, and their relationships to one another. The data model should contain all the logical and physical design parameters required to generate a script using the Data Definition Language (DDL), which can then be used to create a database.[1]

In this unit, you work primarily with MySQL Workbench, a graphical tool that enables you to create data models, reverse-engineer SQL scripts into visual representations, forward-engineer data models into database schemata, and synchronize models with a running MySQL database server.

You begin by creating an entity-relationship diagram to represent the data model for the AffableBean application. When you have completed identifying and defining all entities and the relationships that bind them, you use Workbench to forward-engineer and run a DDL script that converts the data model into a database schema. Finally, you connect to the new schema from the NetBeans IDE.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
MySQL database server version 5.1
MySQL Workbench version 5.1 or 5.2

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • You can download the complete DDL script that MySQL Workbench generates from the entity-relationship diagram you create in this tutorial: affablebean_schema_creation.sql.

Identifying Entities for the Data Model

In the real world, you may not have the luxury of designing the data model for your application. For example, your task may be to develop an application on top of an existing database system. Provided you do not have a data model to base your application on, creating one should be one of the first design steps you take before embarking on development. Creating a data model involves identifying the objects, or entities, required by your system and defining the relationships between them.

To begin identifying the entities we need for the data model, re-examine the use-case presented in Designing the Application. Search for commonly-occurring nouns. For example:



The text highlighted above in bold indicates the candidates that we can consider for the data model. Upon closer inspection, you may deduce that the shopping cart does not need to be included, since the data it provides (i.e., products and their quantities) is equally offered by a customer order once it is processed. In fact, as will be demonstrated in Unit 8, Managing Sessions, the shopping cart merely serves as a mechanism that retains a user session temporarily while the customer shops online. We can therefore settle on the following list:

  • customer
  • category
  • product
  • order

With these four entities, we can begin constructing an entity-relationship diagram (ERD).

Note: In this tutorial, we create a database schema from the ERD, then use the IDE's EclipseLink support to generate JPA entity classes from the existing database. (EclipseLink and the Java Persistence API (JPA) are covered in Unit 7, Adding Entity Classes and Session Beans.) This approach is described as bottom up development. An equally viable alternative is the top down approach.

  • Top down: In top down development, you start with an existing Java implementation of the domain model, and have complete freedom with respect to the design of the database schema. You must create mapping metadata (i.e., annotations used in JPA entity classes), and can optionally use a persistence tool to automatically generate the schema.
  • Bottom up: Bottom up development begins with an existing database schema. In this case, the easiest way to proceed is to use forward-engineering tools to extract metadata from the schema and generate annotated Java source code (JPA entity classes).

For more information on top down and bottom up design strategies, see Data modeling: Modeling methodologies [Wikipedia].


Creating an Entity-Relationship Diagram

Start by running MySQL Workbench. In this exercise, you use Workbench to design an entity-relationship diagram for the AffableBean application.

Note: The following instructions work for MySQL Workbench versions 5.1 and 5.2. The images used in this tutorial are taken from version 5.2. There are slight differences in the graphical interface between versions, however the functionality remains consistent. Because version 5.2 incorporates a query editor (previously MySQL Query Browser), as well as a server administration interface (previously MySQL Administrator), you are presented with the Home screen when opening the application (shown below).

If you are working in Workbench 5.2, click Create New EER Model beneath the Data Modeling heading in the Home screen.

Creating the affablebean Schema

  1. In the default interface, begin by creating a new schema which will be used with the AffableBean application. Click the plus ( Plus icon ) icon located to the right of the Physical Schemata heading.

    A new panel opens in the bottom region of the interface, enabling you to specify settings for the new schema.
    New schema panel displays in bottom region of interface
  2. Enter the following settings for the new schema:
    • Schema Name: affablebean
    • Default Collation: utf8 - utf8_unicode_ci
    • Comments: Schema used with the AffableBean application
    Settings for 'affablebean' schema
    The new schema is created, and becomes listed under the Catalog tab in the right region of the Workbench interface.

    For an explanation of character sets and collations, see the MySQL Server Manual: 9.1.1. Character Sets and Collations in General.

Creating Entities

Start by creating a new entity-relationship diagram in MySQL Workbench. You can drag-and-drop entity tables onto the canvas.

  1. Under the EER Diagrams heading in WorkBench, double-click the Add Diagram ( Add Diagram icon ) icon. A new EER Diagram opens displaying an empty canvas.

    'EER' stands for Enhanced Entity-Relationship.
    New EER Diagram displayed an empty canvas
  2. Click the New Table ( New Table icon ) icon located in the left margin, then hover your mouse onto the canvas and click again. A new table displays on the canvas.
    New entity table displayed on canvas
  3. Double-click the table. The Table editor opens in the bottom region of the interface, allowing you to configure settings for the table.

    Note: The terms 'table' and 'entity' are nearly synonymous in this tutorial unit. From the point of view of a database schema, you are creating tables. From a data modeling perspective, you are creating entities. Likewise, the columns that you later create for each table correspond to entity properties.

  4. In the Table editor, rename the table to one of the nouns you identified from the use-case above. Optionally add a comment describing the purpose of the table. For example:
    • Name: customer
    • Engine: InnoDB
    • Comments: maintains customer details
    Customer table displayed on canvas

    The InnoDB engine provides foreign key support, which is utilized in this tutorial. Later, under Forward-Engineering to the Database, you set the default storage engine used in Workbench to InnoDB.

  5. Under the Catalog tab in the left region of WorkBench (right region for version 5.1), expand the affablebean > Tables node. The customer table now displays.
    Catalog tab displaying new customer table

    More importantly, note that the new customer table is now included in the affablebean schema. Because the affablebean schema was selected when you created the new EER diagram, any changes you make to the diagram are automatically bound to the schema.

  6. Repeat steps 2 - 4 above to add tables to the canvas for the remaining nouns you identified in the use-case above. Before naming your tables however, there is one important consideration which you should take into account. Certain keywords hold special meaning for the SQL dialect used by the MySQL server. Unfortunately, 'order' is one of them. (For example, 'order' can be used in an ORDER BY statement.) Therefore, instead of naming your table 'order', name it 'customer_order' instead. At this stage, don't worry about arranging the tables on the canvas in any special order.

    For a list of reserved words used by the MySQL server, refer to the official manual: 2.2. Reserved Words in MySQL 5.1.

    All tables displayed on canvas

Adding Entity Properties

Now that you've added entities to the canvas, you need to specify their properties. Entity properties correspond to the columns defined in a database table. For example, consider the customer entity. In regard to the AffableBean application, what aspects of a customer would need to be persisted to the database? These would likely be all of the information gathered in the checkout page's customer details form, as well as some association to the processed order.

When adding properties, you need to determine the most appropriate data type for each property. MySQL supports a number of data types in several categories: numeric types, date and time types, and string (character) types. Refer to the official manual for a summary of data types within each category: 10.1. Data Type Overview. In this tutorial, the data types have been chosen for you. Choosing the appropriate data type plays a significant role in optimizing storage on your database server. For more information see:

The following steps describe how you can use MySQL Workbench to add properties to an existing entity in your ERD. As with most of the initial design steps, determining the entity properties would call for careful consideration of the business problem that needs to be solved, and could require hours of analysis as well as numerous consultations with the client.

  1. Double-click the customer table heading to bring up the Table editor in WorkBench.
  2. In the Table editor click the Columns tab, then click inside the displayed table to edit the first column. Enter the following details:
    Column Datatype PK (Primary Key) NN (Not Null) UN (Unsigned) AI (Autoincrement)
    id INT
    Customer entity's id column specified
  3. Continue working in the customer table by adding the following VARCHAR columns. These columns should be self-explanatory, and represent data that would need to be captured for the Affable Bean business to process a customer order and send a shipment of groceries to the customer address.
    Column Datatype NN (Not Null)
    name VARCHAR(45)
    email VARCHAR(45)
    phone VARCHAR(45)
    address VARCHAR(45)
    city_region VARCHAR(2)
    cc_number VARCHAR(19)

    For an explanation of the VARCHAR data type, see the MySQL Reference Manual: 10.4.1. The CHAR and VARCHAR Types.
    Customer entity's varchar columns specified
  4. With the customer table selected on the canvas, choose Arrange > Reset Object Size to resize the table so that all columns are visible on the canvas. Also click the Indexes row so that any table indexes are also visible. (This includes primary and foreign keys, which becomes useful when you begin creating relationships between tables later in the exercise.)

    When you finish, the customer entity looks as follows.
    'customer' table displayed on EER canvas with columns
  5. Follow the steps outlined above to create columns for the remaining tables.

    category

    Column Datatype PK NN UN AI
    id TINYINT
    name VARCHAR(45)      

    customer_order

    Column Datatype PK NN UN AI Default
    id INT  
    amount DECIMAL(6,2)        
    date_created TIMESTAMP       CURRENT_TIMESTAMP
    confirmation_number INT      

    product

    Column Datatype PK NN UN AI Default
    id INT  
    name VARCHAR(45)        
    price DECIMAL(5,2)        
    description TINYTEXT          
    last_update TIMESTAMP       CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

    For details on the TIMESTAMP data type, see the MySQL Reference Manual: 10.3.1.1. TIMESTAMP Properties.


    When you finish, your canvas will look similar to the following.
    'customer', 'category', 'product', and 'order' tables displayed on EER canvas

Identifying Relationships

So far, the entity-relationship diagram contains several entities, but lacks any relationships between them. The data model that we are creating must also indicate whether objects are aware of (i.e., contain references to) one another. If one object contains a reference to another object, this is known as a unidirectional relationship. Likewise, if both objects refer to each other, this is called a bidirectional relationship.

References correlate to foreign keys in the database schema. You will note that, as you begin linking tables together, foreign keys are added as new columns in the tables being linked.

Two other pieces of information are also commonly relayed in an ERD: cardinality (i.e., multiplicity) and ordinality (i.e., optionality). These are discussed below, as you begin adding relationships to entities on the canvas. In order to complete the ERD, you essentially need to create two one-to-many relationships, and one many-to-many relationship. Details follow.

Creating One-To-Many Relationships

Examine the four objects currently on the canvas while considering the business problem. You can deduce the following two one-to-many relationships:

  • A category must contain one or more products
  • A customer must have placed one or more orders

Incorporate these two relationships into the ERD. You can download a copy of the MySQL Workbench project that contains the four entities required for the following steps: affablebean.mwb.

  1. In the left margin, click the 1:n Non-Identifying Relationship ( 1:n Non-Identifying Relationship button ) button. This enables you to create a one-to-many relationship.
  2. Click the product table, then click the category table. The first table you click will contain the foreign key reference to the second table. Here, we want the product table to contain a reference to category. In the image below, you see that a new column, category_id, has been added to the product table, and that a foreign key index, fk_product_category has been added to the table's indexes.
    'Product-category relationship displayed on EER canvas

    Since foreign keys must be of the same data type as the columns they reference, notice that category_id is of type TINYINT, similar to the category table's primary key.

    The entity-relationship diagram in this tutorial uses Crow's Foot notation. You can alter the relationship notation in WorkBench by choosing Model > Relationship Notation.
  3. Double-click the relationship (i.e., click the dashed line between the two entities). The Relationship editor opens in the bottom region of the interface.
  4. Change the default caption to 'belongs to'. In other words, "product x belongs to category y." Note that this is a unidirectional relationship: A product object contains a reference to the category it belongs to, but the related category object does not contain any references to the products it contains.
  5. Click the Foreign Key tab in the Relationship editor. You see the following display.
    'Relationship editor - Foreign Key tab
    Under the Foreign key tab, you can modify a relationship's:
    • cardinality: whether the relationship between two objects is one-to-one or one-to-many.
    • ordinality: whether a reference between entities must exist in order to maintain the integrity of the model. (Toggle the Mandatory checkbox for either side.)
    • type: (i.e., identifying or non-identifying). A non-identifying relationship, such as this one, refers to the fact that the child object (product) can be identified independently of the parent (category). An identifying relationship means that the child cannot be uniquely identified without the parent. An example of this is demonstrated later, when you create a many-to-many relationship between the product and order tables.
  6. Click the 1:n Non-Identifying Relationship ( 1:n Non-Identifying Relationship button ) button. In the following steps, you create a one-to-many relationship between the customer and customer_order objects.
  7. Click the order table first (this table will contain the foreign key), then click the customer table. A relationship is formed between the two tables.
  8. Click the link between the two tables, and in the Relationship editor that displays, change the default caption to 'is placed by'. The relationship now reads, "customer order x is placed by customer y."
    'Order-customer relationship displayed on EER canvas

    You can click and drag tables on the canvas into whatever position makes the most sense for your model. In the image above, the order table has been moved to the left of customer.

Creating Many-To-Many Relationships

Many-to-many relationships occur when both sides of a relationship can have numerous references to related objects. For example, imagine the Affable Bean business offered products that could be listed under multiple categories, such as cherry ice cream, sausage rolls, or avocado soufflé. The data model would have to account for this by including a many-to-many relationship between product and category, since a category contains multiple products, and a product can belong to multiple categories.

In order to implement a many-to-many relationship in a database, it is necessary to break the relationship down into two one-to-many relationships. In doing so, a third table is created containing the primary keys of the two original tables. The product - category relationship described above might look as follows in the data model.

'Product-category many-to-many relationship displayed on EER canvas

Now, consider how the application will persist customer orders. The customer_order entity already contains necessary properties, such as the date it is created, its confirmation number, amount, and a reference to the customer who placed it. However, there currently is no indication of the products contained in the order, nor their quantities. You can resolve this by creating a many-to-many relationship between customer_order and product. This way, to determine which products are contained in a given order, the application's business logic can query the new table that arises from the many-to-many relationship, and search for all records that match an order_id. Because customers can specify quantities for products in their shopping carts, we can also add a quantity column to the table.

  1. In the left margin, click the n:m Identifying Relationship ( n:m Identifying Relationship button ) button. This enables you to create a many-to-many relationship.
  2. Click the customer_order table, then click the product table. A new table appears, named customer_order_has_product.

    Recall that an identifying relationship means that the child cannot be uniquely identified without the parent. Identifying relationships are indicated on the Workbench canvas by a solid line linking two tables. Here, the customer_order_has_product table forms an identifying relationship with its two parent tables, customer_order and product. A record contained in the customer_order_has_product table requires references from both tables in order to exist.

  3. Arrange the tables according to the following image. The many-to-many relationship is highlighted below.
    ERD containing a many-to-many relationship
    The new customer_order_has_product table contains two foreign keys, fk_customer_order_has_product_customer_order and fk_customer_order_has_product_product, which reference the primary keys of the customer_order and product tables, respectively. These two foreign keys form a composite primary key for the customer_order_has_product table.
  4. Change the name of the new customer_order_has_product table to 'ordered_product'. Double-click the customer_order_has_product table to open the Table editor. Enter ordered_product into the Name field.
  5. Rename the foreign key indexes to correspond to the new table name. In the ordered_product's Table editor, click the Foreign Keys tab. Then, click into both foreign key entries and replace 'customer_order_has_product' with 'ordered_product'. When you finish, the two entries should read:
    • fk_ordered_product_customer_order
    • fk_ordered_product_product
    Foreign Keys tab in Table editor
  6. Double-click the lines between the two objects and delete the default captions in the Relationship editor.
  7. Create a quantity column in the ordered_product table. To do so, click the Columns tab in the ordered_product's Table editor. Enter the following details.
    Column Datatype NN (Not Null) UN (Unsigned) Default
    quantity SMALLINT 1
    Table editor - 'order_has_product' table

You have now completed the ERD (entity-relationship diagram). This diagram represents the data model for the AffableBean application. As will later be demonstrated, the JPA entity classes that you create will be derived from the entities existing in the data model.

Complete AffableBean ERD

Choose View > Toggle Grid to disable the canvas grid. You can also create notes for your diagram using the New Text Object ( New Text Object button ) button in the left margin.


Forward-Engineering to the Database

To incorporate the data model you created into the MySQL database, you can employ WorkBench to forward-engineer the diagram into an SQL script (more precisely, a DDL script) to generate the schema. The wizard that you use also enables you to immediately run the script on your database server.

Important: Make sure your MySQL database server is running. Steps describing how to setup and run the database are provided in Setting up the Development Environment: Communicating with the Database Server.

  1. Set the default storage engine used in Workbench to InnoDB. Choose Tools > Options (MySQLWorkbench > Preferences on Mac) to open the Workbench Preferences window. Click the MySQL tab, then select InnoDB as the default storage engine.
    Workbench Preferences window - MySQL tab
    The InnoDB engine provides foreign key support, which is utilized in this tutorial.
  2. Click OK to exit the Preferences window.
  3. Choose Database > Forward Engineer from the main menu.
  4. In the first panel of the Forward Engineer to Database wizard, select 'DROP Objects Before Each CREATE Object', and 'Generate DROP SCHEMA'.
    Forward Engineer wizard
    These DROP options are convenient for prototyping - if you need to make changes to the schema or schema tables, the script will first delete (i.e., drop) these items before recreating them. (If you attempt to create items on the MySQL server that already exist, the server will flag an error.)
  5. Click Continue. In Select Objects to Forward Engineer panel, note that the Export MySQL Table Objects option is selected by default. Click the Show Filter button and note that all five tables in the affablebean schema are included.
  6. Click Continue. In the Review SQL Script panel, you can examine the SQL script that has been generated based on the data model. Optionally, click Save to File to save the script to a location on your computer.

    Note: In examining the script, you may notice that the following variables are set at the top of the file:

    SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
    SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
    SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

    For an explanation of what these variables are, and their purpose in the script, see the official Workbench manual: Chapter 11. MySQL Workbench FAQ.

  7. Click Continue. In the Connection Options panel, set the parameters for connecting to the running MySQL server.
    • Hostname: 127.0.0.1 (or localhost)
    • Port: 3306
    • Username: root
    • Password: nbuser
    (The parameters you set should correspond to those from Setting up the Development Environment: Communicating with the Database Server.)
  8. Click Execute. In the final panel of the wizard, you receive confirmation that the wizard was able to connect to and execute the script successfully.
  9. Click Close to exit the wizard.

The affablebean schema is now created and exists on your MySQL server. In the next step, you connect to the schema, or database, from the IDE. At this stage you may ask, "What's the difference between a schema and a database?" In fact, the MySQL command CREATE SCHEMA is a synonym for CREATE DATABASE. (See 12.1.10. CREATE DATABASE Syntax.) Think of a schema as a blueprint that defines the contents of the database, including tables, relationships, views, etc. A database implements the schema by containing data in a way that adheres to the structure of the schema. This is similar to the object-oriented world of Java classes and objects. A class defines an object. When a program runs however, objects (i.e., class instances) are created, managed, and eventually destroyed as the program runs its course.


Connecting to the Database from the IDE

Now that the affablebean schema exists on your MySQL server, ensure that you can view the tables you created in the ERD from the IDE's Services window.

Important: Make sure that you have followed the steps outlined in Setting up the Development Environment: Communicating with the Database Server. This heading describes how to run the MySQL database server, register it with the IDE, create a database instance, and form a connection to the instance from the IDE.

  1. In the IDE, open the Services window (Ctrl-5; ⌘-5 on Mac) and locate the database connection node ( Database connection node ) for the affablebean database instance you created in the previous tutorial unit.
  2. Refresh the connection to the affablebean database. To do so, right-click the connection node and choose Refresh.
  3. Expand the Tables node. You can now see the five tables defined by the schema.
  4. Expand any of the table nodes. Each table contains the columns and indexes that you created when working in MySQL Workbench.
    Forward Engineer wizard

The IDE is now connected to a database that uses the schema you created for the AffableBean application. From the IDE, you can now view any table data you create in the database, as well as directly modify, add and delete data. You will explore some of these options later, in Connecting the Application to the Database, after you've added sample data to the database.


See Also


References

  1. ^ Data Definition Language (DDL) is a subset of the SQL language and includes statements such as CREATE TABLE, DROP, and ALTER. Other subsets include Data Manipulation Language (DML), and Data Control Language (DCL). For more information, see Data Definition Language [Wikipedia].




The NetBeans E-commerce Tutorial - Preparing the Page Views and Controller Servlet

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

This tutorial unit demonstrates how to create project files in the IDE, and introduces you to some of the facilities available for HTML and CSS development. After creating necessary project files, you begin organizing the front-end of the application. That is, you'll place JSP files in their proper locations within the project structure, create a header and footer which will be applied to all views, and set up the controller servlet to handle incoming requests.

In this unit, you also create a web deployment descriptor (web.xml file) for the application. You can use the deployment descriptor to specify configuration information which is read by the server during deployment. Although the Servlet 3.0 Specification, included in Java EE 6, enables you to use class annotations in place of XML, you may still require the deployment descriptor to configure certain elements of your application. Specifically, in this unit you add directives for the header and footer and specify which files they will be applied to.

One of the goals of this tutorial unit is to create JSP pages that correspond to the views specified in the application design. Referring back to the page mockups and process flow diagram, you begin implementing page layouts according to the mockups by creating placeholders for all visual and functional components. This unit provides a guide for implementing the layout of the welcome page. You can apply the outlined steps to create the other pages on your own, or download project snapshot 1, which provides completed layouts for all pages.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.

Creating Project Files

To create new files for your project, access the IDE's File wizard. You can click the New File ( New File button ) button, press Ctrl-N (⌘-N on Mac), or in the Projects window, right-click the folder node that will contain the new file, and choose New > [file-type]. In the following sub-sections, create JSP pages and a stylesheet for the project.

Creating JSP Pages

Begin working in the project by creating JSP pages that correspond to the views displayed in the process flow diagram.

The index.jsp page that was generated by the IDE will become the project's welcome page. Create JSP pages for the four remaining views and, for now, place them in the project's webroot with index.jsp.

  1. Click the New File ( New File button ) button to open the File wizard.
  2. Select the Web category, then select JSP and click Next.
  3. Name the file 'category'. Note that the Location field is set to Web Pages, indicating that the file will be created in the project's webroot. This corresponds to the project's web folder, which you can later verify in the IDE's Files window.
  4. Click Finish. The IDE generates the new JSP page and opens it in the editor.
  5. Repeat steps 1 - 4 above to create the remaining cart.jsp, checkout.jsp, confirmation.jsp pages.

    When you finish, your Projects window will look as follows:
    Projects window displaying 'view' folder and JSP pages

Creating a Stylesheet

Create a CSS file to contain all styles specific to the application.

  1. In the Projects window, right-click the Web Pages node and choose New > Folder.
  2. In the New Folder wizard, name the folder 'css' and click Finish.
  3. Right-click the new css folder and choose New > Cascading Style Sheet. (If the Cascading Style Sheet item is not listed, choose Other. In the File wizard, select the Web category, then select Cascading Style Sheet and choose Next.)
  4. Name the stylesheet affablebean, then click Finish.

    When you finish, you'll see the affablebean.css file displayed in your Projects window.
    Projects window displaying 'affablebean.css' stylesheet

Implementing HTML and CSS content

The purpose of this section is to design the page views so that they begin to mirror the provided page mockups. As such, they'll serve as a scaffolding which you can use to insert dynamic content during later stages of project development. To do so, you'll utilize the IDE's HTML and CSS editors, along with several CSS support windows.

Browser compatibility note: This tutorial uses Firefox 3 and does not guarantee that page view markup is compatible with other modern browsers. Naturally, when working with front-end web technologies (HTML, CSS, JavaScript) you would need take measures to ensure that your web pages render properly in the browsers and browser versions that you expect visitors to your site will be using (typically Internet Explorer, Firefox, Safari, Chrome, and Opera). When working in the IDE, you can set the browser you want your application to open in. Choose Tools > Options (NetBeans > Preferences on Mac), and under the General tab in the Options window, select the browser you want to use from the Web Browser drop-down. The IDE detects browsers installed to their default locations. If a browser installed on your computer is not displayed, click the Edit button and register the browser manually.

Preparing the display of your web pages is usually an iterative process which you would fine-tune with regular feedback from the customer. The following steps are designed to introduce you to the facilities provided by the IDE, and demonstrate how to get started using the welcome page mockup as an example.

  1. In the Projects window, double-click index.jsp to open it in the editor.
  2. Begin by creating <div> tags for the main areas of the page. You can create five tags altogether: four for main areas (header, footer, left column, and right column), and the fifth to contain the others. Remove any content within the <body> tags and replace with the following. (New code is shown in bold.)
    <body>
        <div id="main">
            <div id="header">
                header
            </div>
    
            <div id="indexLeftColumn">
                left column
            </div>
    
            <div id="indexRightColumn">
                right column
            </div>
    
            <div id="footer">
                footer
            </div>
        </div>
    </body>
  3. Add a reference to the stylesheet in the page's head, and change the title text.
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="css/affablebean.css">
        <title>The Affable Bean</title>
    </head>
  4. Open the affablebean.css stylesheet in the editor. Begin creating style rules for the <div> IDs you just created.
    • Use the width and height properties to create space for each area.
    • Use the background property to discern the areas when you view the page.
    • In order to horizontally center the four areas in the page, you can include margin: 20px auto to the body rule. (20px applies to the top and bottom; auto creates equal spacing to the left and right.) Then include float: left to the left and right columns.
    • The footer requires clear: left so that its top border displays after the bottom borders of any left-floating areas above it (i.e., the left and right columns).
    body {
        font-family: Arial, Helvetica, sans-serif;
        width: 850px;
        text-align: center;
        margin: 20px auto;
    }
    
    #main { background: #eee }
    
    #header {
        height: 250px;
        background: #aaa;
    }
    
    #footer {
        height: 60px;
        clear: left;
        background: #aaa;
    }
    
    #indexLeftColumn {
        height: 400px;
        width: 350px;
        float: left;
        background: #ccc;
    }
    
    #indexRightColumn {
        height: 400px;
        width: 500px;
        float: left;
        background: #eee;
    }
  5. Click the Run Project ( Run Project button ) button in the IDE's main toolbar. Project files that contain changes are automatically saved, any Java code in the project compiles, the project is packaged and deployed to GlassFish, and your browser opens to display the current state of the welcome page.
    Welcome page displayed in browser
  6. Now, begin creating placeholders for page components within each of the four visible areas. Start with the header. Reviewing the welcome page mockup, the header should contain the following components:
    • logo
    • logo text
    • shopping cart widget
    • language toggle
    Make the following changes to the index.jsp file. (New code shown in bold.)
    <div id="header">
        <div id="widgetBar">
    
            <div class="headerWidget">
                [ language toggle ]
            </div>
    
            <div class="headerWidget">
                [ shopping cart widget ]
            </div>
    
        </div>
    
        <a href="#">
            <img src="#" id="logo" alt="Affable Bean logo">
        </a>
    
        <img src="#" id="logoText" alt="the affable bean">
    </div>
    In the above code, you use a <div id="widgetBar"> element to contain the the language toggle and shopping cart widget.


  7. In the stylesheet, create rules for the new IDs and classes. Add the following rules beneath the header rule. (New code shown in bold.)
    #header {
        height: 250px;
        background: #aaa;
    }
    
    #logo {
        height: 155px;
        width: 155px;
        float: left;
        margin-left: 30px;
        margin-top: -20px;
    }
    
    #logoText {
        float: left;
        margin: 20px 0 0 70px;
        /* font styles apply to text within alt tags */
        font-family: 'American Typewriter', Courier, monospace;
        font-size: 50px;
        color: #333;
    }
    
    #widgetBar {
        height: 50px;
        width: 850px;
        float: right;
        background: #ccc;
    }
    
    .headerWidget {
        width: 194px;
        margin: 20px 2px;
        font-size: small;
        float: right;
        line-height: 25px;
        background: #aaa;
    }
    For the logo rule, you apply margin-left and margin-top properties to position the component on the page.

    If there are properties in the above code that you are unfamiliar with, position your cursor on the given property and press Ctrl-Space to invoke a pop-up window that provides documentation support.
    Documentation window for CSS support

    To see how a property is affecting your page, you can comment it out, then refresh the page in the browser. To comment out code, position your cursor on a line, or highlight a block of code, then press Ctrl-/ (⌘-/ on Mac).

  8. Save (Ctrl-S; ⌘-S on Mac) the index.jsp and affablebean.css files, then switch to your browser and refresh the page to view its current state.

    Note: The IDE's 'Deploy on Save' facility is automatically activated for Java web projects. This means that every time you save a file, the file is automatically compiled (i.e., if it is a Java class or JSP page) and the project is newly packaged and deployed to your server. Therefore, when you make HTML or CSS changes, you don't need to explicitly rerun the project to view the updated version in a browser. Simply save your file(s), then switch to the browser and refresh the page.

    Welcome page displayed in browser
    By following the previous steps, you are probably able to see a pattern emerging. For each area on the page, you perform three steps.
    1. Create the structure in HTML.
    2. Create a set of styles to define the appearance.
    3. View the page to examine the results of your changes.
    Following these three steps, let's implement the components in the remaining areas.
  9. Create placeholders for components in the right column. According to the welcome page mockup, the right column contains four evenly-spaced boxes.

    Create the structure for the four boxes. Insert the following code between the <div id="indexRightColumn"> tags. (New code shown in bold.)
    <div id="indexRightColumn">
        <div class="categoryBox">
            <a href="#">
                <span class="categoryLabelText">dairy</span>
            </a>
        </div>
        <div class="categoryBox">
            <a href="#">
                <span class="categoryLabelText">meats</span>
            </a>
        </div>
        <div class="categoryBox">
            <a href="#">
                <span class="categoryLabelText">bakery</span>
            </a>
        </div>
        <div class="categoryBox">
            <a href="#">
                <span class="categoryLabelText">fruit & veg</span>
            </a>
        </div>
    </div>
  10. Add style rules to affablebean.css for the new categoryBox and categoryLabelText classes. (New code shown in bold.)
    #indexRightColumn {
        height: 400px;
        width: 500px;
        float: left;
        background: #eee;
    }
    
    .categoryBox {
        height: 176px;
        width: 212px;
        margin: 21px 14px 6px;
        float: inherit;
        background: #ccc;
    }
    
    .categoryLabelText {
        line-height: 150%;
        font-size: x-large;
    }

  11. Save (Ctrl-S; ⌘-S on Mac) the index.jsp and affablebean.css files, then switch to your browser and refresh the page to view its current state.
    Welcome page displayed in browser
  12. The left column and footer only require placeholders for static text, so let's implement both simultaneously.

    Insert the following code between the <div id="indexLefttColumn"> and <div id="footer"> tags. (New code shown in bold.)
    <div id="indexLeftColumn">
        <div id="welcomeText">
            <p>[ welcome text ]</p>
        </div>
    </div>
    
    ...
    
    <div id="footer">
        <hr>
        <p id="footerText">[ footer text ]</p>
    </div>
  13. Make changes to the affablebean.css stylesheet. It's not necessary to account for all new IDs and classes - you can fine-tune the appearance at a later point when you receive text and images from the customer.

    The horizontal rule (<hr>) tag runs the full length of its containing element (<div id="footer"). Therefore, to shorten it in accordance with the mockup image, you can adjust the width of <div id="footer">. (New code shown in bold.)
    #footer {
        height: 60px;
        width: 350px;
        clear: left;
        background: #aaa;
    }
    
    hr {
        border: 0;
        background-color: #333;
        height: 1px;
        margin: 0 25px;
        width: 300px;
    }
  14. Save (Ctrl-S; ⌘-S on Mac) the index.jsp and affablebean.css files, then switch to your browser and refresh the page to view its current state.
    Welcome page displayed in browser
    The welcome page is complete. You've created all necessary placeholders for components that will exist on the page.

You've now completed the initial design of the application's welcome page. All placeholders for page components exist. Later in the tutorial, when you begin to apply dynamic logic to the page views, you can simply plug JSTL and EL expressions into these placeholders.

The task remains for you to implement the initial design for the other pages based on the mockups. To accomplish this, follow the pattern outlined above, namely:

  1. Create <div> tags for the main page areas.
  2. Iterate through each area and perform three steps:
    1. Create the structure in HTML.
    2. Create a set of styles to define the appearance.
    3. View the page to examine the results of your changes.

Be sure to take advantage of the HTML and CSS support that the IDE provides for you. Some tips and tricks are outlined below. If you just want to grab the code for the remaining pages and proceed with the tutorial, you can download snapshot 1 of the AffableBean project. Images of initial mockup implementations for the remaining pages are included here.

category page

Category page displayed in browser

cart page

Cart page displayed in browser

checkout page

Checkout page displayed in browser

confirmation page

Confirmation page displayed in browser

Note: The background colors for each page area only serve to help you position elements while developing the application. Eventually, you'll want to remove them from the stylesheet and apply a background color more suitable for the application. You can do this by adjusting the background rule for the main class:

#main { background: #f7f7e9 }

Tips and Tricks

The IDE's editor provides many facilities that help you to work more efficiently. If you familiarize yourself with keyboard shortcuts and buttons in the editor toolbar, you can increase your productivity. The following list of tips applies to the editor for HTML and CSS files. To view more keyboard shortcuts, open the IDE's Keyboard Shortcuts Card by choosing Help > Keyboard Shortcuts Card from the main menu.

  • Code completion: When you type in tags and attributes, suggestions for code completion automatically appear in a pop-up box. Pressing Enter completes the suggested tag.
  • Format your code: Right-click in the editor and choose Format.
  • Toggle line numbers: Right-click in the left margin and choose Show Line Numbers.
  • Find occurrences: Highlight a block of text, and press Ctrl-F (⌘-F on Mac). All matches become highlighted in the editor. To toggle highlighting, press the Toggle Highlight Search ( Toggle Highlight Search button ) button (Ctrl-Shift-H) in the editor's toolbar.
  • Create a bookmark: Press the Toggle Bookmark ( Toggle Bookmark button ) button (Ctrl-Shift-M) to create a bookmark in the editor's left margin. Wherever you are in the file, you can then jump to the bookmark by pressing the Previous/Next Bookmark buttons in the editors's toolbar.
  • Copy a code snippet up or down: Highlight a code snippet, then press Ctrl-Shift-Up/Down.
  • Highlight opening and closing tags: Place your cursor on either the opening or closing tag, and both are highlighted in yellow.

Placing JSP Pages in WEB-INF

Looking back at the page mockups that were created, you can see that the welcome page should look the same whenever it is requested, for whomever requests it. That is, the content that displays on the welcome page is not determined by a user's session. (Sessions are discussed in Unit 8, Managing Sessions.) Notice however that all other pages do need some form of user-specific information to display properly. For example, the category page requires that the user select a category in order to display, and the cart page needs to know all items currently held in a shopper's cart. These pages will not render properly if the server isn't able to associate user-specific information with an incoming request. Therefore, we do not want these pages to be accessed directly from a browser's address bar. The project's WEB-INF folder can be used for this purpose: any resources contained in the WEB-INF folder are not directly accessible from a browser.

Create a new folder named view, and place it in the WEB-INF folder. Then move all JSP pages other than the welcome page into this new folder.

  1. In the Projects window, right-click the WEB-INF node and choose New > Folder.
  2. In the New Folder wizard, name the folder view and click Finish. Notice that a new folder node appears in the Projects window.
  3. Move the category.jsp, cart.jsp, checkout.jsp, and confirmation.jsp pages into the view folder.

    You can do this by clicking on cart.jsp to select it, then Shift-clicking on confirmation.jsp. This selects the four files. Then, with the four files selected, click and drag them into the WEB-INF/view folder.
    Projects window displaying JSP pages being dragged into 'view' folder

To demonstrate that these pages are no longer accessible from a browser, click the Run Project ( Run Project button ) button to run the project. When the application displays in your browser, enter the full path to any of these files in the address bar. For example, type in:

http://localhost:8080/AffableBean/WEB-INF/view/category.jsp

You receive an HTTP Status 404 message, indicating that the resource is not available.


Creating a Header and Footer

Looking at the page mockups, it is easy to see that all of the five views share identical content; at the top, they contain the company logo, a language toggle, and other widgets associated with shopping cart functionality. At the bottom, they contain some text with Privacy Policy and Contact links. Rather than including this code in each page source file, we can factor it out into two JSP fragments: a header and a footer. We'll then include the fragment files into page views whenever they need to be rendered.

For these fragments, let's create a new folder named jspf, and place it within WEB-INF.

  1. In the Projects window, right-click the WEB-INF node and choose New > Folder.
  2. In the New Folder wizard, name the folder jspf and click Finish.

    Menu items provided by the IDE are often context-sensitive. For example, because you right-clicked the WEB-INF node, when the New Folder wizard displayed, web/WEB-INF was automatically entered in the Parent Folder field. Likewise, when you right-click a node in the Projects window and choose New, the list of file types is partially determined by your previous selections.

  3. Create two JSP segments: header.jspf and footer.jspf. To do so, right-click the newly created jspf folder and choose New > JSP. In the New JSP wizard, enter the file name, and under Options, select the Create as a JSP Segment option, then click Finish.

    When you finish, you'll see header.jspf and footer.jspf displayed in your Projects window:
    Projects window displaying JSP fragments

    Now, you can copy the header code from any of the JSP pages and paste it into the header.jspf file. Likewise, you can copy the footer code from any of the JSP pages and paste it into the footer.jspf file. When you finish this task, you can remove the header and footer code from all of the JSP pages.
  4. Copy the header code from any of the JSP pages and paste it into the header.jspf file. The header should include the page doctype and the opening <html>, <head>, and <body> tags through to the closing tag for the <div id="header"> element. Be sure to include placeholders for the shopping cart widget, language toggle, and 'proceed to checkout' button used along the top of page views. After you paste code into header.jspf, the file will look as follows.
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!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">
            <link rel="stylesheet" type="text/css" href="css/affablebean.css">
            <title>The Affable Bean</title>
        </head>
        <body>
            <div id="main">
                <div id="header">
                    <div id="widgetBar">
    
                        <div class="headerWidget">
                            [ language toggle ]
                        </div>
    
                        <div class="headerWidget">
                            [ checkout button ]
                        </div>
    
                        <div class="headerWidget">
                            [ shopping cart widget ]
                        </div>
    
                    </div>
    
                    <a href="#">
                        <img src="#" id="logo" alt="Affable Bean logo">
                    </a>
    
                    <img src="#" id="logoText" alt="the affable bean">
                </div>
  5. Copy the footer code from any of the JSP pages and paste it into the footer.jspf file. The footer code should include the <div id="footer"> element, through to the closing <html> tag. After you paste code into footer.jspf, the file will look as follows.
                <div id="footer">
                    <hr>
                    <p id="footerText">[ footer text ]</p>
                </div>
            </div>
        </body>
    </html>
  6. Remove the header and footer code from all five JSP pages (index.jsp, category.jsp, cart.jsp, checkout.jsp, and confirmation.jsp).

Adding a Directive to the Deployment Descriptor

So far, you've placed views in their proper location and have factored out common header and footer code into the header.jspf and footer.jspf files. The application still needs to know which pages the header and footer files will be applied to. You could add <jsp:include> tags to each of the page views. Doing so however would just reintroduce the code repetition which we've just made efforts to eliminate. An alternative solution would be to create a web.xml deployment descriptor, and add a JSP Property Group directive to specify which page views the header and footer fragments should apply to.

  1. Press Ctrl-N (⌘-N on Mac) to open the New File wizard. Select the Web category, then under File Types, select Standard Deployment Descriptor (web.xml).
  2. Click Next. Note that the file is named web.xml, and that the wizard will place it in the project's WEB-INF directory upon completion.
  3. Click Finish. The web.xml file is created and added to the project. The IDE's graphical interface for the deployment descriptor opens in the editor.

    The interface is categorized by the areas that can be configured in a web application. These areas are displayed as tabs in the editor toolbar, and include topics such as Servlets, Filters, References, and Security. The XML tab displays the entire source code for the file. Any changes you make in the graphical interface will cause immediate updates to the deployment descriptor's source code, which you can verify by switching to the XML tab. This is demonstrated in the following steps.
  4. Click the Pages tab, then click the Add JSP Property Group button. The Add JSP Property Group dialog opens.
  5. Type in 'header and footer settings' for the Description field. Leave Display Name blank. Both the Display Name and Description fields are optional.
  6. For URL Patterns, specify the paths to the five views. Type in '/index.jsp' and '/WEB-INF/view/*'. Separate the two paths with a comma. (The '*' is a wildcard that represents all files within the given folder.)
    Add JSP Property Group dialog
  7. Click OK. An entry is added to the JSP Properties Groups category in the Pages tab.
  8. Switch back to the XML tab. Notice that the following code has been added to the deployment descriptor.
    <jsp-config>
        <jsp-property-group>
            <description>header and footer settings</description>
            <url-pattern>/index.jsp</url-pattern>
            <url-pattern>/WEB-INF/view/*</url-pattern>
        </jsp-property-group>
    </jsp-config>

    Note: You may need to add carriage returns to the code so that it displays on multiple lines. You can right-click in the editor and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac) to have the code properly indented.

  9. Switch to the Pages tab again, and in the Include Preludes and Include Codas fields, enter the paths to the header.jspf and footer.jspf files, respectively. You can click the Browse button and navigate to the files in the provided dialog.
    JSP Property Group shown under Pages tab of web.xml
  10. Switch back to the XML tab. Note that the following code has been added. (Changes in bold.)
    <jsp-config>
        <jsp-property-group>
            <description>header and footer settings</description>
            <url-pattern>/index.jsp</url-pattern>
            <url-pattern>/WEB-INF/view/*</url-pattern>
            <include-prelude>/WEB-INF/jspf/header.jspf</include-prelude>
            <include-coda>/WEB-INF/jspf/footer.jspf</include-coda>
        </jsp-property-group>
    </jsp-config>
    The above directive specifies that for all files found within the given url-patterns, the header.jspf file will be prepended, and the footer.jspf file appended.

    To view the definitions of the above tags, as well as all tags available to you in the web deployment descriptor, consult the Servlet Specification.

  11. Run the application again (press F6; fn-F6 on Mac). You've already removed the header and footer code from the index.jsp file, so you can determine whether it is automatically being added when the file is requested.

    You will see that the welcome page displays as it did previously, with header and footer content included.

Creating the Controller Servlet

The controller servlet handles incoming requests by initiating any actions needed to generate the model for the request, then forwarding the request to the appropriate view. For a visual representation, refer back to the MVC diagram for the AffableBean project.

The IDE provides a Servlet wizard that enables you to define the servlet component in a web application either by including the @WebServlet annotation in the generated class, or by adding the necessary directives to the deployment descriptor. In the following steps, you create the ControllerServlet and define it in the application context using the @WebServlet annotation.

  1. In the Projects window, right-click the AffableBean project node and choose New > Servlet.
  2. In the wizard, type ControllerServlet in the Class Name field.
  3. In the Package field, type controller. (The new package is automatically created when you complete the wizard.)
    Servlet wizard
  4. Click Next. Step 3 of the wizard lets you configure the servlet. Of primary importance are the URL patterns that you need to specify. The patterns identify the URLs that invoke the servlet. For example, if you enter '/category', you are directing the servlet to handle a request that appears as follows.
    http://localhost/AffableBean/category
    The URL patterns should correspond to the views and actions that a user can initiate. Looking at the welcome page mockup, a user should be able to select a category. We can therefore associate the /category URL with the action of clicking on a category image. Likewise, in the category page, users should be able to add an item to the shopping cart. We can therefore specify /addToCart.
  5. In the URL Pattern(s) field, type in '/category, /addToCart, /viewCart'. Patterns are separated by commas. You can add more patterns directly in the servlet class once it's created.
    Servlet wizard, Step 3: Configure Servlet Deployment
  6. Click Finish. The IDE generates the ControllerServlet and opens it in the editor. The servlet and URL patterns are included in the @WebServlet annotation that appears above the class signature.
    @WebServlet(name="ControllerServlet", urlPatterns={"/category", "/addToCart", "/viewCart"})
    public class ControllerServlet extends HttpServlet {
    In the previous step, if you had chosen the 'Add information to deployment descriptor (web.xml)' option in the wizard, the following markup would have been generated in the application's web.xml file instead.
    <servlet>
        <servlet-name>ControllerServlet</servlet-name>
        <servlet-class>controller.ControllerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/category</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/addToCart</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/viewCart</url-pattern>
    </servlet-mapping>
  7. Add other URL patterns directly to the @WebServlet annotation's urlPatterns element. The application requires more URL patterns for other actions and views. You can type in the following patterns:
    • /updateCart
    • /checkout
    • /purchase
    • /chooseLanguage
    Be sure to separate each pattern with a comma. You can also reformat the annotation as follows:
    @WebServlet(name="ControllerServlet",
                urlPatterns = {"/category",
                               "/addToCart",
                               "/viewCart",
                               "/updateCart",
                               "/checkout",
                               "/purchase",
                               "/chooseLanguage"})
  8. Finally, include the loadOnStartup element so that the servlet is instantiated and initialized when the application is deployed. A value of 0 or greater will cause this to happen (-1 is the default).
    @WebServlet(name="ControllerServlet",
                loadOnStartup = 1,
                urlPatterns = {"/category",
                               "/addToCart",
                               "/viewCart",
                               "/updateCart",
                               "/checkout",
                               "/purchase",
                               "/chooseLanguage"})

Implementing the Controller Servlet

As previously stated, the controller servlet handles incoming requests by initiating any actions needed to generate the model for the request, then forwarding the request to the appropriate view. For a visual representation, refer back to the MVC diagram for the AffableBean project.

Looking at the generated code for the new ControllerServlet, you can see that the IDE's servlet template employs a processRequest method which is called by both doGet and doPost methods. (You may need to expand the code fold by clicking the plus icon ( Code fold icon ) in the editor's left margin to view these methods.) Because this application differentiates between doGet and doPost, you'll add code directly to these methods and remove the processRequest method altogether.



Now that you've mapped URL patterns to the servlet using the @WebServlet annotation, set up the ControllerServlet to handle these patterns. Also, instantiate a RequestDispatcher to forward the requested pattern to the appropriate view.

  1. Replace the ControllerServlet class template code with the following code.
    public class ControllerServlet extends HttpServlet {
    
        /**
         * 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 {
    
            String userPath = request.getServletPath();
    
            // if category page is requested
            if (userPath.equals("/category")) {
                // TODO: Implement category request
    
            // if cart page is requested
            } else if (userPath.equals("/viewCart")) {
                // TODO: Implement cart page request
    
                userPath = "/cart";
    
            // if checkout page is requested
            } else if (userPath.equals("/checkout")) {
                // TODO: Implement checkout page request
    
            // if user switches language
            } else if (userPath.equals("/chooseLanguage")) {
                // TODO: Implement language request
    
            }
    
            // use RequestDispatcher to forward request internally
            String url = "/WEB-INF/view" + userPath + ".jsp";
    
            try {
                request.getRequestDispatcher(url).forward(request, response);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
        /**
         * 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 {
    
            String userPath = request.getServletPath();
    
            // if addToCart action is called
            if (userPath.equals("/addToCart")) {
                // TODO: Implement add product to cart action
    
            // if updateCart action is called
            } else if (userPath.equals("/updateCart")) {
                // TODO: Implement update cart action
    
            // if purchase action is called
            } else if (userPath.equals("/purchase")) {
                // TODO: Implement purchase action
    
                userPath = "/confirmation";
            }
    
            // use RequestDispatcher to forward request internally
            String url = "/WEB-INF/view" + userPath + ".jsp";
    
            try {
                request.getRequestDispatcher(url).forward(request, response);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
    }
    As you continue through the tutorial, you'll return to the ControllerServlet and implement each of the mapped URL patterns individually.
  2. Examine the code above. There are several points to note:
    • The servlet uses a userPath instance variable to get the requested URL pattern from the client:
      String userPath = request.getServletPath();
      userPath is used by both doGet and doPost methods.
    • URL patterns associated primarily with page requests are managed by the doGet method. For example, /category, /viewCart, and /checkout result in the display of the category, cart, and checkout pages.)
    • URL patterns associated with form submits and the transport of sensitive user data (e.g., /addToCart, /updateCart, and /purchase) are managed by the doPost method.
    • For both doGet and doPost methods, the path to the appropriate view is formed using a url string:
      String url = "/WEB-INF/view" + userPath + ".jsp";
    • The RequestDispatcher is obtained from the HttpServletRequest and applies the url to forward the request:
      request.getRequestDispatcher(url).forward(request, response);
    • TODO notes have been used to denote work that still needs to be done. For example:
      // if category page is requested
      if (userPath.equals("/category")) {
          // TODO: Implement category request
      Applying TODO notes in your code is a useful way to keep track of tasks that you need to complete. You can use the IDE's Tasks window (Ctrl-6; ⌘-6 on Mac) to view all TODO notes, as well as any syntax or compile errors contained in your project.
      Tasks window

      You can control the keywords that display in the Tasks window. Open the Options window (Tools > Options; NetBeans > Preferences on Mac), then choose Miscellaneous > Tasks.

  3. Run the project (press F6; fn-F6 on Mac) and test to see whether the ControllerServlet is forwarding requests to the appropriate views.
    • Type in http://localhost:8080/AffableBean/category in the browser's address bar. The application's category page displays.
    • Type in http://localhost:8080/AffableBean/viewCart in the browser's address bar. The application's cart page displays.
    • Type in http://localhost:8080/AffableBean/checkout in the browser's address bar. The application's checkout page displays.

    Note: Entering http://localhost:8080/AffableBean/purchase in the browser's address bar does not allow you to view the confirmation page. Naturally, this is because the /purchase URL pattern is handled by the servlet's doPost method, and requests sent from the browser's address bar are typically sent using the HTTP GET method.

At this stage, you've created JSP pages that contain placeholders for functional components. You've also set up the front-end structure of the application. JSP pages now reside within the WEB-INF folder, header and footer code has been factored out into separate files, your deployment descriptor is properly configured, and you've set up the ControllerServlet to handle incoming requests. In the next tutorial unit, you take measures to enable connectivity between the application and the database.

If you'd like to compare your work with the sample solution for this unit, you can download snapshot 2 of the AffableBean project.


See Also





The NetBeans E-commerce Tutorial - Connecting the Application to the Database

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

This tutorial unit focuses on communication between the database and the application. You begin by adding sample data to the database and explore some of the features provided by the IDE's SQL editor. You set up a data source and connection pool on the GlassFish server, and proceed by creating a JSP page that tests the data source by performing a simple query on the database.

This unit also addresses how the application retrieves and displays images necessary for web presentation, and how to set context parameters and retrieve their values from web pages. Once you are certain the data source is working correctly, you apply JSTL's core and sql tag libraries to retrieve and display category and product images for the index and category pages.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 2
website images n/a

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, perform the following three steps:
    1. Set up your MySQL database server. Follow the steps outlined in: Communicating with the Database Server.
    2. Create the affablebean schema on the database server.
      1. Click on affablebean_schema_creation.sql and copy (Ctrl-C; ⌘-C on Mac) the entire contents of the file.
      2. Open the IDE's SQL editor. In the Services window (Ctrl-5; ⌘-5 on Mac), right-click the affablebean database connection ( Database connection node ) node and choose Execute Command. The IDE's SQL editor opens.
      3. Paste (Ctrl-V; ⌘-V on Mac) the entire contents of the affablebean.sql file into the editor.
      4. Click the Run SQL ( Run SQL button ) button in the editor's toolbar. The script runs on your MySQL server. Tables are generated for the affablebean database.
    3. Open the project snapshot in the IDE. In the IDE, press Ctrl-Shift-O (⌘-Shift-O on Mac) and navigate to the location on your computer where you unzipped the downloaded file.

Adding Sample Data to the Database

Begin by adding sample data to the category and product tables. You can do this using the IDE's SQL editor, which allows you to interact directly with the database using native SQL. The IDE's SQL support also includes a GUI editor that enables you to add, remove, modify and delete table records.

category table

  1. In the Services window (Ctrl-5; ⌘-5 on Mac), right-click the category table ( database table node ) node and choose View Data. The SQL editor opens and displays with a GUI representation of the category table in the lower region. Note that the table is empty, as no data has yet been added.
    Empty category table displayed in SQL editor
    Also, note that the native SQL query used to generate the GUI representation is displayed in the upper region of the editor: 'select * from category'.
  2. Delete 'select * from category' and enter the following SQL statement:
    INSERT INTO `category` (`name`) VALUES ('dairy'),('meats'),('bakery'),('fruit & veg');
    This statement inserts four new records, each with a unique entry for the 'name' column. Because the id column was specified as AUTO_INCREMENT when you created the schema, you do not need to worry about supplying a value.
  3. Click the Run SQL ( Run SQL button ) button in the editor's toolbar. The SQL statement is executed.
  4. To confirm that the data has been added, run the 'select * from category' query again. To do so, you can use the SQL History window. Click the SQL History ( SQL History button ) button in the editor's toolbar and double-click the 'select * from category' entry. The SQL History window lists all SQL statements that you recently executed in the IDE.

Watch the screencast below to see how you can follow the above steps. When typing in the editor, be sure to take advantage of the IDE's code completion and suggestion facilities.




product table

  1. Right-click the product table ( database table node ) node and choose Execute Command. Choosing the Execute Command menu option in the Services window opens the SQL editor in the IDE.
  2. Copy and paste the following INSERT statements into the editor.
    --
    -- Sample data for table `product`
    --
    
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('milk', 1.70, 'semi skimmed (1L)', 1);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('cheese', 2.39, 'mild cheddar (330g)', 1);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('butter', 1.09, 'unsalted (250g)', 1);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('free range eggs', 1.76, 'medium-sized (6 eggs)', 1);
    
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('organic meat patties', 2.29, 'rolled in fresh herbs<br>2 patties (250g)', 2);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('parma ham', 3.49, 'matured, organic (70g)', 2);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('chicken leg', 2.59, 'free range (250g)', 2);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('sausages', 3.55, 'reduced fat, pork<br>3 sausages (350g)', 2);
    
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('sunflower seed loaf', 1.89, '600g', 3);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('sesame seed bagel', 1.19, '4 bagels', 3);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('pumpkin seed bun', 1.15, '4 buns', 3);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('chocolate cookies', 2.39, 'contain peanuts<br>(3 cookies)', 3);
    
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('corn on the cob', 1.59, '2 pieces', 4);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('red currants', 2.49, '150g', 4);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('broccoli', 1.29, '500g', 4);
    INSERT INTO `product` (`name`, price, description, category_id) VALUES ('seedless watermelon', 1.49, '250g', 4);
    
    Examine the above code and note the following points:
    • By examining the affablebean schema generation script, you'll note that the product table contains a non-nullable, automatically incremental primary key. Whenever you insert a new record into the table (and don't explicitly set the value of the primary key), the SQL engine sets it for you. Also, note that the product table's last_update column applies CURRENT_TIMESTAMP as its default value. The SQL engine will therefore provide the current date and time for this field when a record is created.

      Looking at this another way, if you were to create an INSERT statement that didn't indicate which columns would be affected by the insertion action, you would need to account for all columns. In this case, you could enter a NULL value to enable the SQL engine to automatically handle fields that have default values specified. For example, the following statement elicits the same result as the first line of the above code:
      INSERT INTO `product` VALUES (NULL, 'milk', 1.70, 'semi skimmed (1L)', NULL, 1);
      After running the statement, you'll see that the record contains an automatically incremented primary key, and the last_update column lists the current date and time.
    • The value for the final column, 'category_id', must correspond to a value contained in the category table's id column. Because you have already added four records to the category table, the product records you are inserting reference one of these four records. If you try to insert a product record that references a category_id that doesn't exist, a foreign key constraint fails.
  3. Click the Run SQL ( Run SQL button ) button in the editor's toolbar.

    Note: View the Output window (Ctrl-4; ⌘-4 on Mac) to see a log file containing results of the execution.

  4. Right-click the product table ( database table node ) node and choose View Data. You can see 16 new records listed in the table.
    16 new records displayed in SQL editor's 'product' table

Creating a Connection Pool and Data Source

From this point onward, you establish connectivity between the MySQL database and the affablebean application through the GlassFish server which it is deployed to. This communication is made possible with the Java Database Connectivity (JDBC) API. The JDBC API is an integration library contained in the JDK (refer back to the component diagram displayed in the tutorial Introduction). Although this tutorial does not work directly with JDBC programming, the application that we are building does utilize the JDBC API whenever communication is required between the SQL and Java languages. For example, you start by creating a connection pool on the GlassFish server. In order for the server to communicate directly with the the MySQL database, it requires the Connector/J JDBC driver which converts JDBC calls directly into a MySQL-specific protocol. Later in this tutorial unit, when you apply JSTL's <sql:query> tags to query the affablebean database, the tags are translated into JDBC Statements.

A connection pool contains a group of reusable connections for a particular database. Because creating each new physical connection is time-consuming, the server maintains a pool of available connections to increase performance. When an application requests a connection, it obtains one from the pool. When an application closes a connection, the connection is returned to the pool. Connection pools use a JDBC driver to create physical database connections.

A data source (a.k.a. a JDBC resource) provides applications with the means of connecting to a database. Applications get a database connection from a connection pool by looking up a data source using the Java Naming and Directory Interface (JNDI) and then requesting a connection. The connection pool associated with the data source provides the connection for the application.

In order to enable the application access to the affablebean database, you need to create a connection pool and a data source that uses the connection pool. Use the NetBeans GlassFish JDBC Resource wizard to accomplish this.

Note: You can also create connection pools and data sources directly on the GlassFish server using the GlassFish Administration Console. However, creating these resources in this manner requires that you manually enter database connection details (i.e., username, password and URL). The benefit of using the NetBeans wizard is that it extracts any connection details directly from an existing database connection, thus eliminating potential connectivity problems.

To access the console from the IDE, in the Services window right-click the Servers > GlassFish node and choose View Admin Console. The default username / password is: admin / adminadmin. If you'd like to set up the connection pool and data source using the GlassFish Administration console, follow steps 3-15 of the NetBeans E-commerce Tutorial Setup Instructions. The setup instructions are provided for later tutorial units.

  1. Click the New File ( New File button ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
  2. Select the GlassFish category, then select JDBC Resource and click Next.
  3. In Step 2 of the JDBC Resource wizard, select the Create New JDBC Connection Pool option. When you do so, three new steps are added to the wizard, enabling you to specify connection pool settings.
  4. Enter details to set up the data source:
    • JNDI Name: jdbc/affablebean
      By convention, the JNDI name for a JDBC resource begins with the 'jdbc/' string.
    • Object Type: user
    • Enabled: true
    JDBC Resource wizard - General Attributes
  5. Click Next. In Step 3, Additional Properties, you do not need to specify any additional configuration information for the data source.
  6. Click Next. In Step 4, Choose Database Connection, type in AffableBeanPool as the JDBC connection pool name. Also, ensure that the Extract from Existing Connection option is selected, and that the jdbc:mysql://localhost:3306/affablebean connection is listed.
  7. Click Next. In Step 5, Add Connection Pool Properties, specify the following details:
    • Datasource Classname: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    • Resource Type: javax.sql.ConnectionPoolDataSource
    • Description: (Optional) Connects to the affablebean database
    Also, note that the wizard extracts and displays properties from the existing connection.
    JDBC Resource wizard - Add Connection Pool
  8. Click Finish. The wizard generates a sun-resources.xml file for the project that contains all information required to set up the connection pool and data source on GlassFish. The sun-resources.xml file is a deployment descriptor specific to the GlassFish application server. When the project next gets deployed, the server will read in any configuration data contained in sun-resources.xml, and set up the connection pool and data source accordingly. Note that once the connection pool and data source exist on the server, your project no longer requires the sun-resources.xml file.
  9. In the Projects window (Ctrl-1; ⌘-1 on Mac), expand the Server Resources node and double-click the sun-resources.xml file to open it in the editor. Here you see the XML configuration required to set up the connection pool and data source. (Code below is formatted for readability.)
    <resources>
      <jdbc-resource enabled="true"
                     jndi-name="jdbc/affablebean"
                     object-type="user"
                     pool-name="AffableBeanPool">
      </jdbc-resource>
    
      <jdbc-connection-pool allow-non-component-callers="false"
                            associate-with-thread="false"
                            connection-creation-retry-attempts="0"
                            connection-creation-retry-interval-in-seconds="10"
                            connection-leak-reclaim="false"
                            connection-leak-timeout-in-seconds="0"
                            connection-validation-method="auto-commit"
                            datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                            fail-all-connections="false"
                            idle-timeout-in-seconds="300"
                            is-connection-validation-required="false"
                            is-isolation-level-guaranteed="true"
                            lazy-connection-association="false"
                            lazy-connection-enlistment="false"
                            match-connections="false"
                            max-connection-usage-count="0"
                            max-pool-size="32"
                            max-wait-time-in-millis="60000"
                            name="AffableBeanPool"
                            non-transactional-connections="false"
                            pool-resize-quantity="2"
                            res-type="javax.sql.ConnectionPoolDataSource"
                            statement-timeout-in-seconds="-1"
                            steady-pool-size="8"
                            validate-atmost-once-period-in-seconds="0"
                            wrap-jdbc-objects="false">
    
        <description>Connects to the affablebean database</description>
        <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
      </jdbc-connection-pool>
    </resources>
  10. In the Projects window (Ctrl-1; ⌘-1 on Mac), right-click the AffableBean project node and choose Deploy. The GlassFish server reads configuration data from the sun-resources.xml file and creates the AffableBeanPool connection pool, and jdbc/affablebean data source.
  11. In the Services window, expand the Servers > GlassFish > Resources > JDBC node. Here you can locate the jdbc/affablebean data source listed under JDBC Resources, and the AffableBeanPool connection pool listed under Connection Pools.
    Services window - GlassFish JDBC Resources

    Right-click data source and connection pool nodes to view and make changes to their properties. You can associate a data source with any connection pool registered on the server. You can edit property values for connection pools, and unregister both data sources and connection pools from the server.


Testing the Connection Pool and Data Source

Start by making sure the GlassFish server can successfully connect to the MySQL database. You can do this by pinging the AffableBeanPool connection pool in the GlassFish Administration Console.

Then proceed by adding a reference in your project to the data source you created on the server. To do so, you create a <resource-ref> entry in the application's web.xml deployment descriptor.

Finally, use the IDE's editor support for the JSTL sql tag library, and create a JSP page that queries the database and outputs data in a table on a web page.

Pinging the Connection Pool

  1. Ensure that the GlassFish server is already running. In the Services window (Ctrl-5; ⌘-5 on Mac), expand the Servers node. Note the small green arrow next to the GlassFish icon ( GlassFish server node in Services window ).

    (If the server is not running, right-click the server node and choose Start.)
  2. Right-click the server node and choose View Admin Console. The GlassFish Administration Console opens in a browser.
  3. Log into the administration console. The default username / password is: admin / adminadmin.
  4. In the console's tree on the left, expand the Resources > JDBC > Connection Pools nodes, then click AffableBeanPool. In the main window, the Edit Connection Pool interface displays for the selected connection pool.
  5. Click the Ping button. If the ping succeeds, the GlassFish server has a working connection to the affablebean database on the MySQL server.
    GlassFish Administration Console - Edit Connection Pool
    (If the ping fails, see suggestions in the Troubleshooting section below.)

Creating a Resource Reference to the Data Source

  1. In the Projects window, expand the Configuration Files folder and double-click web.xml. A graphical interface for the file displays in the IDE's main window.
  2. Click the References tab located along the top of the editor. Expand the Resource References heading, then click Add. The Add Resource Reference dialog opens.
  3. Enter the following details into the dialog:
    • Resource Name: jdbc/affablebean
    • Resource Type: javax.sql.ConnectionPoolDataSource
    • Authentication: Container
    • Sharing Scope: Shareable
    • Description: (Optional) Connects to database for AffableBean application
    Add Resource Reference dialog
  4. Click OK. The new resource is added under the Resource References heading.
    Resource reference to jdbc/affablebean data source listed in the deployment descriptor
    To verify that the resource is now added to the web.xml file, click the XML tab located along the top of the editor. Notice that the following <resource-ref> tags are now included:
    <resource-ref>
        <description>Connects to database for AffableBean application</description>
        <res-ref-name>jdbc/affablebean</res-ref-name>
        <res-type>javax.sql.ConnectionPoolDataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>

Querying the Database from a JSP Page

  1. Create a new JSP page to test the data source. Click the New File ( New File button ) button. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
  2. Select the Web category, then select the JSP file type and click Next.
  3. Enter 'testDataSource' as the file name. In the Folder field, type in 'test'.
    JSP wizard

    The project does not yet have a folder named 'test' within the Web Pages location (i.e., within the web folder). By entering 'test' into the Folder field, you have the IDE create the folder upon completing the wizard.

  4. Click finish. The IDE generates a new testDataSource.jsp file, and places it into the new test folder within the project.
  5. In the new testDataSource.jsp file, in the editor, place your cursor at the end of the line containing the <h1> tags (line 17). Press Return, then press Ctrl-Space to invoke code suggestions. Choose DB Report from the list of options.
    Code suggestions displayed in editor

    If line numbers do not display, right-click in the left margin of the editor and choose Show Line Numbers.

  6. In the Insert DB Report dialog, specify the data source and modify the SQL query to be executed:
    • Data Source: jdbc/affablebean
    • Query Statement: SELECT * FROM category, product WHERE category.id = product.category_id
    Insert DB Report dialog
  7. Click OK. The dialog adds the taglib directives for the JSTL core and sql libraries to the top of the file:
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    The dialog also generates template code to display the query results in an HTML table:
    <sql:query var="result" dataSource="jdbc/affablebean">
        SELECT * FROM category, product
        WHERE category.id = product.category_id
    </sql:query>
    
    <table border="1">
        <!-- column headers -->
        <tr>
            <c:forEach var="columnName" items="${result.columnNames}">
                <th><c:out value="${columnName}"/></th>
            </c:forEach>
        </tr>
        <!-- column data -->
        <c:forEach var="row" items="${result.rowsByIndex}">
            <tr>
                <c:forEach var="column" items="${row}">
                    <td><c:out value="${column}"/></td>
                </c:forEach>
            </tr>
        </c:forEach>
    </table>
  8. Before running the file in a browser, make sure you have enabled the JDBC driver deployment option in NetBeans' GlassFish support. Choose Tools > Servers to open the Servers window. In the left column, select the GlassFish server you are deploying to. In the main column, ensure that the 'Enable JDBC Driver Deployment' option is selected, then click Close.
    Servers window
    For Java applications that connect to a database, the server requires a JDBC driver to be able to create a communication bridge between the SQL and Java languages. In the case of MySQL, you use the Connector/J JDBC driver. Ordinarily you would need to manually place the driver JAR file into the server's lib directory. With the 'Enable JDBC Driver Deployment' option selected, the server performs a check to see whether a driver is needed, and if so, the IDE deploys the driver to the server.
  9. Right-click in the editor and choose Run File (Shift-F6; fn-Shift-F6 on Mac). The testDataSource.jsp file is compiled into a servlet, deployed to the server, then runs in a browser.
  10. Open the Output window (Ctrl-4; ⌘-4 on Mac) and click the 'AffableBean (run)' tab. The output indicates that the driver JAR file (mysql-connector-java-5.1.6-bin.jar) is deployed.
    Output window listing MySQL driver deployment
  11. Examine testDataSource.jsp in the browser. You see an HTML table listing data contained in the category and product tables.
    Browser display of testDataSource.jsp
    (If you receive a server error, see suggestions in the Troubleshooting section below.)

At this stage, we have set up a working data source and connection pool on the server, and demonstrated that the application can access data contained in the affablebean database.


Setting Context Parameters

This section demonstrates how to configure context parameters for the application, and how to access parameter values from JSP pages. The owner of an application may want to be able to change certain settings without the need to make intrusive changes to source code. Context parameters enable you application-wide access to parameter values, and provide a convenient way to change parameter values from a single location, should the need arise.

Setting up context parameters can be accomplished in two steps:

  1. Listing parameter names and values in the web deployment descriptor
  2. Calling the parameters in JSP pages using the initParam object

The JSP Expression Language (EL) defines implicit objects, which initParam is an example of. When working in JSP pages, you can utilize implicit objects using dot notation and placing expressions within EL delimiters (${...}). For example, if you have an initialization parameter named myParam, you can access it from a JSP page with the expression ${initParam.myParam}.

For more information on the JSP Expression Language and implicit objects, see the Java EE 5 Tutorial: JavaServer Pages Technology > Unified Expression Language.

By way of demonstration, you create context parameters for the image paths to category and product images used in the AffableBean project. Begin by adding the provided image resources to the project, then perform the two steps outlined above.

  1. Download the website sample images, and unzip the file to a location on your computer. The unzipped file is an img folder that contains all of the image resources required for the AffableBean application.
  2. Import the img folder into the AffableBean project. Copy (Ctrl-C; ⌘-C on Mac) the img folder, then in the IDE's Projects window, paste (Ctrl-V; ⌘-V on Mac) the folder into the project's Web Pages node.
    'img' folder displayed in Projects window
    The categories and products folders contain the images that will be displayed in the index and category pages, respectively.
  3. Open the project's web deployment descriptor. In the Projects window, expand the Configuration Files node and double-click web.xml.
  4. Click the General tab, then expand Context Parameters and click the Add button.
  5. In the Add Context Parameter dialog, enter the following details:
    • Parameter Name: productImagePath
    • Parameter Value: img/products/
    • Description: (Optional) The relative path to product images
    Add Context Parameter dialog
  6. Click OK.
  7. Click the Add button again and enter the following details:
    • Parameter Name: categoryImagePath
    • Parameter Value: img/categories/
    • Description: (Optional) The relative path to category images
  8. Click OK. The two context parameters are now listed:
    web.xml - context parameters
  9. Click the XML tab to view the XML content that has been added to the deployment descriptor. The following <context-param> entries have been added:
    <context-param>
        <description>The relative path to product images</description>
        <param-name>productImagePath</param-name>
        <param-value>img/products/</param-value>
    </context-param>
    <context-param>
        <description>The relative path to category images</description>
        <param-name>categoryImagePath</param-name>
        <param-value>img/categories/</param-value>
    </context-param>
  10. To test whether the values for the context parameters are accessible to web pages, open any of the project's web pages in the editor and enter EL expressions using the initParam implicit object. For example, open index.jsp and enter the following (New code in bold):
    <div id="indexLeftColumn">
        <div id="welcomeText">
            <p>[ welcome text ]</p>
    
            <!-- test to access context parameters -->
            categoryImagePath: ${initParam.categoryImagePath}
            productImagePath: ${initParam.productImagePath}
        </div>
    </div>
  11. Run the project. Click the Run Project ( Run Project button ) button. The project's index page opens in the browser, and you see the values for the categoryImagePath and productImagePath context parameters displayed in the page.
    Context parameter values displayed in browser

Working with JSTL

So far in this tutorial unit, you've established how to access data from the affablebean database, add image resources to the project, and have set up several context parameters. In this final section, you combine these achievements to plug the product and category images into the application. In order to do so effectively, you need to begin taking advantage of the JavaServer Pages Standard Tag Library (JSTL).

Note that you do not have to worry about adding the JSTL JAR file (jstl-impl.jar) to your project's classpath because it already exists. When you created the AffableBean project and selected GlassFish as your development server, the libraries contained in the server were automatically added to your project's classpath. You can verify this in the Projects window by expanding the AffableBean project's Libraries > GlassFish Server 3 node to view all of the libraries provided by the server.
GlassFish libraries listed in Projects window
The jstl-impl.jar file is GlassFish' implementation of JSTL, version 1.2.

You can also download the GlassFish JSTL JAR file separately from: http://jstl.dev.java.net/download.html

Before embarking upon an exercise involving JSTL, one implementation detail needs to first be clarified. Examine the files contained in the categories and products folders and note that the names of the provided image files match the names of the category and product entries found in the database. This enables us to leverage the database data to dynamically call image files within the page. So for example, if the web page needs to access the image for the broccoli product entry, you can make this happen using the following statement.

${initParam.productImagePath}broccoli.png

After implementing a JSTL forEach loop, you'll be able to replace the hard-coded name of the product with an EL expression that dynamically extracts the name of the product from the database, and inserts it into the page.

${initParam.productImagePath}${product.name}.png

Begin by integrating the category images into the index page, then work within the category page so that data pertaining to the selected category is dynamically handled.

index page

  1. In the Projects window, double-click the index.jsp node to open it in the editor. (If already opened, press Ctrl-Tab to select it in the editor.)
  2. At the top of the file, before the first <div> tag, place your cursor on a blank line, then type 'db' and press Ctrl-Space. In the code-completion pop-up window that displays, choose DB Query.
    DB completion items displayed in editor
  3. In the Insert DB Query dialog, enter the following details:
    • Variable Name: categories
    • Scope: page
    • Data Source: jdbc/affablebean
    • Query Statement: SELECT * FROM category
    Insert DB query dialog
  4. Click OK. The dialog generates an SQL query using JSTL <sql:query> tags. Also, note that the required reference to the sql taglib directive has been automatically inserted at the top of the page. (Changes displayed in bold.)
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    <%--
        Document   : index
        Created on : Sep 5, 2009, 4:32:42 PM
        Author     : nbuser
    --%>
    
    <sql:query var="categories" dataSource="jdbc/affablebean">
        SELECT * FROM category
    </sql:query>
    
                <div id="indexLeftColumn">
                    <div id="welcomeText">
                        <p>[ welcome text ]</p>
                        
    The SQL query creates a result set which is stored in the categories variable. You can then access the result set using EL syntax, e.g., ${categories} (demonstrated below).
  5. Place your cursor at the end of '<div id="indexRightColumn">' (line 22), hit return, type 'jstl' then press Ctrl-Space and choose JSTL For Each.
    JSTL completion items displayed in editor
  6. In the Insert JSTL For Each dialog, enter the following details:
    • Collection: ${categories.rows}
    • Current Item of the Iteration: category
    Insert JSTL For Each dialog
  7. Click OK. The dialog sets up syntax for a JSTL forEach loop using <c:forEach> tags. Also, note that the required reference to the core taglib directive has been automatically inserted at the top of the page. (Changes displayed in bold.)
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    
        ...
    
        <div id="indexRightColumn">
            <c:forEach var="category" items="categories.rows">
            </c:forEach>
            <div class="categoryBox">

    If you are wondering what 'rows' refers to in the generated code, recall that the categories variable represents a result set. More specifically, categories refers to an object that implements the javax.servlet.jsp.jstl.sql.Result interface. This object provides properties for accessing the rows, column names, and size of the query’s result set. When using dot notation as in the above example, 'categories.rows' is translated in Java to 'categories.getRows()'.

  8. Integrate the <c:forEach> tags into the page. You can nest the <div class="categoryBox"> tags within the forEach loop so that HTML markup is generated for each of the four categories. Use EL syntax to extract the category table's id and name column values for each of the four records. Make sure to delete the other <div class="categoryBox"> tags which exist outside the forEach loop. When you finish, the complete index.jsp file will look as follows. (<c:forEach> tags and contents are displayed in bold.)
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    <%--
        Document   : index
        Created on : Sep 5, 2009, 4:32:42 PM
        Author     : nbuser
    --%>
    
    <sql:query var="categories" dataSource="jdbc/affablebean">
        SELECT * FROM category
    </sql:query>
    
                <div id="indexLeftColumn">
                    <div id="welcomeText">
                        <p>[ welcome text ]</p>
    
                        <!-- test to access context parameters -->
                        categoryImagePath: ${initParam.categoryImagePath}
                        productImagePath: ${initParam.productImagePath}
                    </div>
                </div>
    
                <div id="indexRightColumn">
                    <c:forEach var="category" items="${categories.rows}">
                        <div class="categoryBox">
                            <a href="category?${category.id}">
    
                                <span class="categoryLabelText">${category.name}</span>
    
                                <img src="${initParam.categoryImagePath}${category.name}.jpg"
                                     alt="${category.name}">
                            </a>
                        </div>
                    </c:forEach>
                </div>
  9. Click the Run Project ( Run Project button ) button. The project's index page opens in the browser, and you see the names and images of the four categories.
    Category images displayed in index page in browser
  10. Click any of the four images in the browser. The category page displays.
    Category page in browser
    To understand how linking takes place between the index and category pages, reexamine the HTML anchor tags within the forEach loop:
    <a href="category?${category.id}">
    When a user clicks the image link in the browser, a request for 'category' is sent to the application's context root on the server. In your development environment, the URL is:
    http://localhost:8080/AffableBean/category
    which can be explained as follows:
    • http://localhost:8080: The default location of the GlassFish server on your computer
    • /AffableBean: The context root of your deployed application
    • /category: The path to the request
    Recall that in Preparing the Page Views and Controller Servlet, you mapped a request for '/category' to the ControllerServlet. Currently, the ControllerServlet internally forwards the request to /WEB-INF/view/category.jsp, which is why the category page displays upon clicking an image link.

    You can verify the application's context root by expanding the Configuration Files node in the Projects window, and opening the sun-web.xml file. The sun-web.xml file is a deployment descriptor specific to GlassFish.


    Also, note that a question mark (?) and category ID are appended to the requested URL.
    <a href="category?${category.id}">
    This forms the query string. As is demonstrated in the next section, you can apply (pageContext.request.queryString} to extract the value of the query string from the request. You can then use the category ID from the query string to determine which category details need to be included in the response.

category page

Three aspects of the category page need to be handled dynamically. The left column must indicate which category is selected, the table heading must display the name of the selected category, and the table must list product details pertaining to the selected category. In order to implement these aspects using JSTL, you can follow a simple, 2-step pattern:

  1. Retrieve data from the database using the JSTL sql tag library.
  2. Display the data using the JSTL core library and EL syntax.

Tackle each of the three tasks individually.

Display selected category in left column

  1. In the Projects window, double-click the category.jsp node to open it in the editor. (If already opened, press Ctrl-Tab to select it in the editor.)
  2. Add the following SQL query to the top of the file.
    <sql:query var="categories" dataSource="jdbc/affablebean">
        SELECT * FROM category
    </sql:query>
    Either use the Insert DB Query dialog as described above, or use the editor's code suggestion and completion facilities by pressing Ctrl-Space while typing.
  3. Between the <div id="categoryLeftColumn"> tags, replace the existing static placeholder content with the following <c:forEach> loop.
    <div id="categoryLeftColumn">
    
        <c:forEach var="category" items="${categories.rows}">
    
            <c:choose>
                <c:when test="${category.id == pageContext.request.queryString}">
                    <div class="categoryButton" id="selectedCategory">
                        <span class="categoryText">
                            ${category.name}
                        </span>
                    </div>
                </c:when>
                <c:otherwise>
                    <a href="category?${category.id}" class="categoryButton">
                        <div class="categoryText">
                            ${category.name}
                        </div>
                    </a>
                </c:otherwise>
            </c:choose>
    
        </c:forEach>
    
    </div>
    In the above snippet, you access the request's query string using 'pageContext.request.queryString'. pageContext is another implicit object defined by the JSP Expression Language. The EL expression uses the PageContext to access the current request (an HttpServletRequest object). From HttpServletRequest, the getQueryString() method is called to obtain the value of the request's query string.
  4. Make sure to add the JSTL core and sql taglib directives to the top of the page. (This is done automatically when using the editor's code suggestion and completion facilities.)
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
  5. Run the project. In the browser, navigate to the category page and click the category buttons in the left column. Each time you click, the page refreshes highlighting the selected category.
    Category page with bakery category selected
    Also, note that the ID of the selected category is displayed in the page's URL. (In the above image, the bakery category is selected, and '3' is appended to the URL in the browser's navigation toolbar.)

    Your servlet container (i.e., GlassFish) converts JSP pages into servlets before running them as part of a project. You can view the generated servlet for a JSP page by right-clicking the page node in the Projects window and choosing View Servlet. Of course, you first need to run the project so that the servlet is generated. Taking the index.jsp file as an example, when you choose View Servlet, the IDE displays a read-only copy of the generated servlet, index_jsp.java, in the editor. The servlet exists on the server at: <gf-install-dir>/glassfish/domains/domain1/generated/jsp/AffableBean/org/apache/jsp/index_jsp.java.


Display title heading above product table

  1. Add the following SQL query to the top of the file, underneath the query you just implemented. (New query is shown in bold.)
    <sql:query var="categories" dataSource="jdbc/affablebean">
        SELECT * FROM category
    </sql:query>
    
    <sql:query var="selectedCategory" dataSource="jdbc/affablebean">
        SELECT name FROM category WHERE id = ?
        <sql:param value="${pageContext.request.queryString}"/>
    </sql:query>
  2. Use JSP EL syntax to extract the category name from the query and display it in the page. Make the following change to the <p id="categoryTitle"> element. (Displayed in bold.)
    <p id="categoryTitle">${selectedCategory.rows[0].name}</p>
    Since the result from the selectedCategory query contains only one item (i.e., user can select only one category), you can retrieve the first row of the result set using 'selectedCategory.rows[0]'. If a user selects the 'meats' category for example, the returned expression would be '{name=meats}'. You could then access the category name with '${selectedCategory.rows[0].name}'.
  3. Save (Ctrl-S; ⌘-S on Mac) changes made to the file.
  4. Return to the browser and refresh the category page. The name of the selected category now displays above the product table.
    Category page with bakery title displayed over product table

    Note: As demonstrated in this and the previous step, you do not need to explicitly recompile, deploy, and run the project with each change to your code base. The IDE provides a Deploy on on Save feature, which is enabled for Java web projects by default. To verify that the feature is activated, right-click your project node in the Projects window and choose Properties. In the Project Properties window, click the Run category and examine the 'Deploy on Save' option.

Display product details within the table

  1. Add the following SQL query to the top of the file, underneath the previous queries you implemented. (New query is shown in bold.)
    <sql:query var="categories" dataSource="jdbc/affablebean">
        SELECT * FROM category
    </sql:query>
    
    <sql:query var="selectedCategory" dataSource="jdbc/affablebean">
        SELECT name FROM category WHERE id = ?
        <sql:param value="${pageContext.request.queryString}"/>
    </sql:query>
    
    <sql:query var="categoryProducts" dataSource="jdbc/affablebean">
        SELECT * FROM product WHERE category_id = ?
        <sql:param value="${pageContext.request.queryString}"/>
    </sql:query>
  2. Between the <table id="productTable"> tags, replace the existing static table row placeholders (<tr> tags) with the following <c:forEach> loop. (Changes are displayed in bold.)
    <table id="productTable">
    
        <c:forEach var="product" items="${categoryProducts.rows}" varStatus="iter">
    
            <tr class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}">
                <td>
                    <img src="${initParam.productImagePath}${product.name}.png"
                        alt="${product.name}">
                </td>
                <td>
                    ${product.name}
                    <br>
                    <span class="smallText">${product.description}</span>
                </td>
                <td>
                    &euro; ${product.price} / unit
                </td>
                <td>
                    <form action="addToCart" method="post">
                        <input type="hidden"
                               name="productId"
                               value="${product.id}">
                        <input type="submit"
                               value="add to cart">
                    </form>
                </td>
            </tr>
    
        </c:forEach>
    
    </table>
    Note that in the above snippet an EL expression is used to determine the background color for table rows:
    class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}"
    The API documentation for the <c:forEach> tag indicates that the varStatus attribute represents an object that implements the LoopTagStatus interface. Therefore, iter.index retrieves the index of the current round of the iteration. Continuing with the expression, (iter.index % 2) == 0) evaluates the remainder when iter.index is divided by 2, and returns a boolean value based on the outcome. Finally, an EL conditional operator (? :) is used to set the returned value to 'lightBlue' if true, 'white' otherwise.

    For a description of JSP Expression Language operators, see the Java EE 5 Tutorial: JavaServer Pages Technology > Unified Expression Language > Operators.

  3. Save (Ctrl-S; ⌘-S on Mac) changes made to the file.
  4. Return to the browser and refresh the category page. Product details now display within the table for the selected category.
    Category page displaying products for selected category

You have now completed this tutorial unit. In it, you explored how to connect your application to the database by setting up a connection pool and data source on the server, then referenced the data source from the application. You also created several context parameters, and learned how to access them from JSP pages. Finally, you implemented JSTL tags into the application's web pages in order to dynamically retrieve and display database data.

You can download and examine snapshot 3 if you'd like to compare your work with the solution project. The solution project contains enhancements to the HTML markup and stylesheet in order to properly display all provided images. It also provides welcome page text, and a basic implementation for the page footer.


Troubleshooting

If you are having problems, see the troubleshooting tips below. If you continue to have difficulty, or would like to provide constructive feedback, use the Send us Your Feedback link.

  • You receive the following exception:
    org.apache.jasper.JasperException: PWC6188: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
    This is a known issue for NetBeans IDE 6.9. Try to deploy the project, then access the file by typing its URL in the browser. For example, if you are trying to view testDataSource.jsp in a browser, enter 'http://localhost:8080/AffableBean/test/testDataSource.jsp' in the browser's URL field directly. Otherwise, add the IDE's JSTL 1.1 library to the project. In the Projects window, right-click the Libraries node and choose Add Library. Select JSTL 1.1. For more information, see: http://forums.netbeans.org/topic28571.html.
  • You receive the following exception:
    javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
    This can occur when the MySQL driver has not been added to the domain lib folder. (Note that after adding, it is necessary to restart the server if it is already running.)
  • You receive the following exception:
    javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver found for jdbc/affablebean"
    This can occur when the jdbc/affablebean resource reference hasn't been added to the web.xml deployment descriptor.
  • You receive the following exception:
    javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Access denied for user 'root'@'localhost' (using password: YES)"
    This can occur when you are using an incorrect username/password combination. Make sure the username and password you use to connect to the MySQL server are correctly set for your connection pool in the sun-resources.xml file. Also, check that the username and password are correctly set for the connection pool in the GlassFish Administration Console.

See Also





The NetBeans E-commerce Tutorial - Adding Entity Classes and Session Beans

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

This tutorial unit introduces the Enterprise JavaBeans (EJB) and Java Persistence (JPA) technologies. In it, you use two of the IDE's wizards that are essential to Java EE development. These are:

  • Entity Classes from Database wizard: Creates a Java Persistence API entity class for each selected database table, complete with named query annotations, fields representing columns, and relationships representing foreign keys.
  • Session Beans for Entity Classes wizard: Creates an EJB session facade for each entity class with basic access methods.

These two wizards provide an efficient way for you to quickly set up the model for your application. If you reexamine the MVC diagram for the application you are building, you can see where EJB session beans and JPA entity classes fit into its structure.

MVC diagram of the AffableBean application

In this unit, the entity classes you create form a Java-based representation of the affablebean database. While each entity class represents a database table, instances of entity classes correspond to records that can be saved (i.e., persisted) to the database. The business logic of the application is encapsulated by session beans, which can either be used as facade classes that enable CRUD (Create-Read-Update-Delete) access to entities (as demonstrated here), or they can contain code that implements actions specific to your application. (An example of this is provided in Unit 9: Integrating Transactional Business Logic).

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 3

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.
  • Snapshot 4 of the AffableBean project is available for download and corresponds to state the project after completing this unit using NetBeans IDE 6.9.

What are EJB and JPA Technologies?

Up until now, the project that you've been developing in this tutorial could be run in a web server with a servlet container, such as Apache Tomcat. After all, you've so far only made use of JSTL and servlet technologies, and are connecting to the database directly using JDBC. In fact, you could theoretically continue to develop the application using just these technologies, while manually coding for all aspects of your application, including thread-safety, transactions, and security. However, using Enterprise beans with JPA entity classes allows you focus on the business logic of your application while relying on solutions that have already been tried and tested. The following sections introduce the two technologies and define their role in EE development.

Enterprise JavaBeans

The official EJB product page describes EnterPrise JavaBeans technology as a "server-side component architecture" that "enables rapid and simplified development of distributed, transactional, secure and portable applications." You can apply EJBs (i.e., Enterprise beans) to your projects, and the services provided by the technology remain transparent to you as a developer, thus eliminating the tedious and often error-prone task of adding a lot of boiler plate code which would otherwise be required. If you are new to EE development, you may question the need for EJBs in your Java web application. The book EJB 3 In Action, by Debu Panda, Reza Rahman and Derek Lane, paraphrases the role of EJB technology nicely:

Although many people think EJBs are overkill for developing relatively simple web applications of moderate size, nothing could be further from the truth. When you build a house, you don't build everything from scratch. Instead, you buy materials or even the services of a contractor as you need it. It isn't too practical to build an enterprise application from scratch either. Most server-side applications have a lot in common, including churning business logic, managing application state, storing and retrieving information from a relational database, managing transactions, implementing security, performing asynchronous processing, integrating systems, and so on.

As a framework, the EJB container provides these kinds of common functionality as out-of-the-box services so that your EJB components can use them in your applications without reinventing the wheel. For instance, let's say that when you build a credit card module in your web application, you write a lot of complex and error-prone code to manage transactions and security access control. You could have avoided that by using the declarative transaction and security services provided by the EJB container. These services as well as many others are available to EJB components when they are deployed in an EJB container. This means writing high-quality, feature-rich applications much faster than you might think.
[1]

You can think of EJB both as components, or Java classes that are incorporated in your project, as well as a framework that provides numerous enterprise-related services. Some of the services that we take advantage of in this tutorial are described in EJB 3 In Action as follows:

  • Pooling: For each EJB component, the EJB platform creates a pool of component instances that are shared by clients. At any point in time, each pooled instance is only allowed to be used by a single client. As soon as an instance is finished servicing a client, it is returned to the pool for reuse instead of being frivolously discarded for the garbage collector to reclaim.
  • Thread Safety: EJB makes all components thread-safe and highly performant in ways athat are completely invisible. This means that you can write your server components as if you were developing a single-threaded desktop application. It doesn't matter how complex the component itself is; EJB will make sure it is thread-safe.
  • Transactions: EJB supports declarative transaction management that helps you add transactional behavior to components using simple configuration instead of code. In effect, you can designate any component method to be transactional. If the method completes normally, EJB commits the transaction and makes the data changes made by the method permanent. Otherwise the transaction is rolled back. Container-managed EJB transactions are demonstrated in Unit 9, Integrating Transactional Business Logic.
  • Security: EJB supports integration with the Java Authentication and Authorization Service (JAAS) API, so it is easy to completely externalize security and secure an application using simple configuration instead of cluttering up your application with security code.[2] In Unit 11, Securing the Application, a demonstration of EJB's @RolesAllowed annotation is provided.

Java Persistence

In the context of Java Enterprise, persistence refers to the act of automatically storing data contained in Java objects into a relational database. The Java Persistence API (JPA) is an object-relational mapping (ORM) technology that enables applications to manage data between Java objects and a relational database in a way that is transparent to the developer. This means that you can apply JPA to your projects by creating and configuring a set of Java classes (entities) that mirror your data model. Your application can then access these entities as though it were directly accessing the database.

There are various benefits to using JPA in your projects:

  • JPA has its own rich, SQL-like query language for static and dynamic queries. Using the Java Persistence Query Language (JPQL), your applications remain portable across different database vendors.
  • You can avoid the task of writing low-level, verbose and error-prone JDBC/SQL code.
  • JPA transparently provides services for data caching and performance optimization.

What are Session Beans?

Enterprise session beans are invoked by a client in order to perform a specific business operation. The name session implies that a bean instance is available for the duration of a "unit of work". The EJB 3.1 specification describes a typical session object as having the following characteristics:

  • Executes on behalf of a single client
  • Can be transaction-aware
  • Updates shared data in an underlying database
  • Does not represent directly shared data in the database, although it may access and update such data
  • Is relatively short-lived
  • Is removed when the EJB container crashes. The client has to re-establish a new session object to continue computation.

EJB provides three types of session beans: stateful, stateless, and singleton. The following descriptions are adapted from the Java EE 6 Tutorial.

  • Stateful: The state of the bean is maintained across multiple method calls. The "state" refers to the values of its instance variables. Because the client interacts with the bean, this state is often called the conversational state.
  • Stateless: Stateless beans are used for operations that can occur in a single method call. When the method finishes processing, the client-specific state of the bean is not retained. A stateless session bean therefore does not maintain a conversational state with the client.
  • Singleton: A singleton session bean is instantiated once per application, and exists for the lifecycle of the application. Singleton session beans are designed for circumstances where a single enterprise bean instance is shared across and concurrently accessed by clients.

For more information on EJB session beans, see the Java EE 6 Tutorial: What is a Session Bean?.

For purposes of developing the e-commerce application in this tutorial, we will only be working with stateless session beans.


About Specifications and Implementations

EJB and JPA technologies are defined by the following specifications:

These specifications define the technologies. To apply a technology to your project however, you must use an implementation of the specification. When a specification becomes finalized, it includes a reference implementation, which is a free implementation of the technology. If you find this concept confusing, consider the following analogy: A musical composition (i.e., the notes on a page) defines a piece of music. When a musician learns the composition and records her performance, she provides an interpretation of the piece. In this manner the musical composition is likened to the technical specification, and the musician's recording corresponds to the specification's implementation.

See What is the Java Community Process? for an explanation of Java technical specifications, and how they are formally standardized.

If you examine the download pages for the final releases of the EJB and JPA specifications, you'll find links to the following reference implementations:

Implementations of the JPA specification are dubbed persistence providers, and the persistence provider which has been chosen as the reference implementation for the JPA 2.0 specification is EclipseLink.

If you examine the link for the EJB reference implementation, you'll come to a page that lists not only the implementation for EJB, but for all reference implementations provided by Project GlassFish. The reason for this is that Project GlassFish forms the reference implementation of the Java EE 6 platform specification (JSR 316). The GlassFish v3 application server (or the Open Source Edition), which you are using to build the e-commerce project in this tutorial, contains the reference implementations of all technologies developed under Project GlassFish. As such, it is referred to as a Java EE 6 container.

A Java EE container contains three essential components: a web (i.e., servlet) container, an EJB container, and a persistence provider. The deployment scenario for the e-commerce application is displayed in the diagram below. Entity classes that you create in this unit are managed by the persistence provider. The session beans that you create in this unit are managed by the EJB container. Views are rendered in JSP pages, which are managed by the web container.

GlassFish v3 Java EE container

Adding Entity Classes

Begin by using the IDE's Entity Classes from Database wizard to generate entity classes based on the affablebean schema. The wizard relies on the underlying persistence provider to accomplish this task.

  1. Open the project snapshot in the IDE. In the IDE, press Ctrl-Shift-O (�-Shift-O on Mac) and navigate to the location on your computer where you unzipped the downloaded file.
  2. Press Ctrl-N (⌘-N on Mac) to open the File wizard.
  3. Select the Persistence category, then select Entity Classes from Database. Click Next.
  4. In Step 2: Database Tables, choose jdbc/affablebean from the Data Source drop-down list. The drop-down list is populated by data sources registered with the application server.

    When you choose the jdbc/affablebean data source, the IDE scans the database and lists the database tables in the Available Tables pane.
    Entity Classes from Database wizard
  5. Click the Add All button, then click Next.
  6. Step 3 of the Entity Classes from Database wizard differs slightly between NetBeans IDE 6.8 and 6.9. Depending on the version IDE you are using, perform the following steps.

    NetBeans IDE 6.8

    Entity Classes from Database wizard, Step 3: Entity Classes
    1. Type in entity in the Package field. The wizard will create a new package for the entity classes upon completing.
    2. Click the Create Persistence Unit button. The Create Persistence Unit dialog opens.
      Create Persistence Unit dialog
      A persistence unit refers to a collection of entity classes that exist in an application. The above dialog generates a persistence.xml file, which is used by your persistence provider to specify configuration settings for the persistence unit. Note that 'EclipseLink (JPA 2.0)' is the default selection for the server associated with the project. Leave 'Table Generation Strategy' set to 'None'. This prevents the persistence provider from affecting your database. (For example, if you want the persistence provider to delete then recreate the database based on the existing entity classes, you could set the strategy to 'Drop and Create'. This action would then be taken each time the project is deployed.)
    3. Click Create.
    4. Back in Step 3: Entity Classes, note that the class names for the entities are based on database tables. For example, the CustomerOrder entity is mapped to the customer_order database table. Also note that the 'Generate Named Query Annotations for Persistent Fields' option is selected by default. We will be using various named queries later in the tutorial.
    5. Continue to step 7 below.

    NetBeans IDE 6.9

    Entity Classes from Database wizard, Step 3: Entity Classes
    1. Type in entity in the Package field. The wizard will create a new package for the entity classes upon completing.
    2. Note the following:
      • The class names for the entities are based on database tables. For example, the CustomerOrder entity will be mapped to the customer_order database table.
      • The 'Generate Named Query Annotations for Persistent Fields' option is selected by default. We will be using various named queries later in the tutorial.
      • The 'Create Persistence Unit' option is selected by default. A persistence unit is a collection of entity classes that exist in an application. The persistence unit is defined by a persistence.xml configuration file, which is read by your persistence provider. Enabling this option therefore means that the wizard will also generate a persistence.xml file and populate it with default settings.
  7. Click Finish. The JPA entity classes are generated, based on the affablebean database tables. You can examine the entity classes in the Projects window by expanding the newly created entity package. Also, note that the new persistence unit exists under the Configuration Files node.
    Projects window - entity classes displayed in project

    Note that the wizard generated an additional entity class, OrderedProductPK. Recall that the data model's ordered_product table uses a composite primary key that comprises the primary keys of both the customer_order and product tables. (See Designing the Data Model - Creating Many-To-Many Relationships.) Because of this, the persistence provider creates a separate entity class for the composite key, and embeds it into the OrderedProduct entity. You can open OrderedProduct in the editor to inspect it. JPA uses the @EmbeddedId annotation to signify that the embeddable class is a composite primary key.
    public class OrderedProduct implements Serializable {
        private static final long serialVersionUID = 1L;
        @EmbeddedId
        protected OrderedProductPK orderedProductPK;

    Press Ctrl-Space on the @EmbeddedId annotation to invoke the API documentation.

    API documentation invoked on @EmbeddedId
  8. Open the persistence unit (persistence.xml) in the editor. The IDE provides a Design view for persistence units, in addition to the XML view. The Design view provides a convenient way to make configuration changes to the persistence provider's management of the project.
    Design view of AffableBeanPU persistence unit
  9. Click the XML tab at the top of the AffableBeanPU persistence unit to open the XML view. Add the following property to the file.
    <persistence-unit name="AffableBeanPU" transaction-type="JTA">
      <jta-data-source>jdbc/affablebean</jta-data-source>
      <properties>
        <property name="eclipselink.logging.level" value="FINEST"/>
      </properties>
    </persistence-unit>
    You set the logging level property to FINEST so that you can view all possible output produced by the persistence provider when the application runs. This enables you to see the SQL that the persistence provider is using on the database, and can facilitate in any required debugging.

    See the official EclipseLink documentation for an explanation of logging and a list of all logging values: How To Configure Logging


Adding Session Beans

In this section, we use the IDE's Session Beans for Entity Classes wizard to generate an EJB session facade for each of the entity classes that you just created. Each session bean will contain basic access methods for its respective entity class.

A session facade is a design pattern advertised in the Enterprise BluePrints program. As stated in the Core J2EE Pattern Catalog, it attempts to resolve common problems that arise in a multi-tiered application environment, such as:

  • Tight coupling, which leads to direct dependence between clients and business objects
  • Too many method invocations between client and server, leading to network performance problems
  • Lack of a uniform client access strategy, exposing business objects to misuse

A session facade abstracts the underlying business object interactions and provides a service layer that exposes only the required functionality. Thus, it hides from the client's view the complex interactions between the participants. Thus, the session bean (representing the session facade) manages the relationships between business objects. The session bean also manages the life cycle of these participants by creating, locating, modifying, and deleting them as required by the workflow.

  1. Press Ctrl-N (⌘-N on Mac) to open the File wizard.
  2. Select the Persistence category, then select Session Beans for Entity Classes.
    File wizard: Persistence category, Session Beans for Entity Classes file type
  3. Click Next.
  4. In Step 2: Entity Classes, note that all entity classes contained in your project are listed on the left, under Available Entity Classes. Click Add All. All entity classes are moved to the right, under Selected Entity Classes.
  5. Click Next.
  6. In Step 3: Generated Session Beans, type in session into the Package field.
    Session Beans for Entity Classes wizard - Step 3: Generated Session Beans

    Note: You can use the wizard to generate local and remote interfaces for the session beans. While there is benefit to programming session beans to interfaces (For example, hiding business object interactions behind an interface enables you to further decouple the client from your business logic. This also means that you can code multiple implementations of the interface for your application, should the need arise.), this lies outside the scope of the tutorial. Note that EJB versions prior to 3.1 require that you implement an interface for each session bean.

  7. Click Finish. The IDE generates session beans for each of the entity classes contained in your project. In the Projects window, expand the new session package to examine the session beans.

    NetBeans 6.8 NetBeans 6.9
    Projects window - session beans displayed in project Projects window - session beans displayed in project

    Note: As shown above, NetBeans IDE 6.9 provides slight improvements in the way the Session Beans for Entity Classes wizard generates facade classes. Namely, boiler-plate code that is common to all classes is factored out into an abstract class named AbstractFacade. If you are working in version 6.9, open any of the facade classes that have been generated (aside from AbstractFacade). You'll see that the class extends AbstractFacade.

  8. Open a session facade in the editor, for example, ProductFacade. All of the generated session facades instantiate an EntityManager using the @PersistenceContext annotation.
    @PersistenceContext(unitName = "AffableBeanPU")
    private EntityManager em;
    The @PersistenceContext annotation is used to inject a container-managed EntityManager into the class. In other words, we rely on GlassFish' EJB container to open and close EntityManagers as and when needed. The unitName element specifies the AffableBeanPU persistence unit, which has been defined in the application's persistence.xml file.

    The EntityManager is an integral component of the Java Persistence API, and is responsible for performing persistence actions on the database. The book EJB 3 In Action describes the EntityManager as follows:
    The JPA EntityManager interface manages entities in terms of actually providing persistence services. While entities tell a JPA provider how they map to the database, they do not persist themselves. The EntityManager interface reads the ORM metadata for an entity and performs persistence operations.

Your application now contains a persistence model of the affablebean database in the form of JPA entity classes. It also contains a session facade consisting of Enterprise beans that can be used to access the entity classes. The next section demonstrates how you can access the database using the session beans and entity classes.


Accessing Data with EJBs

In the previous tutorial unit, you learned how to access the database from the application by configuring a data source on GlassFish, adding a resource reference to the application's deployment descriptor, and using JSTL <sql> tags in the application's JSP pages. This is a valuable technique, as it allows you to quickly set up prototypes that include data from the database. However, this is not a realistic scenario for medium to large-sized applications, or applications managed by a team of developers, as it would prove difficult to maintain or scale. Furthermore, if you are developing the application into multiple tiers or are adhering to the MVC pattern, you would not want to keep data-access code in your front-end. Using Enterprise beans with a persistence model enables you better conform to the MVC pattern by effectively decoupling the presentation and model components.

The following instructions demonstrate how to begin using the session and entity beans in the AffableBean project. You are going to remove the JSTL data access logic that you previously set up for the index and category pages. In its place, you'll utilize the data access methods provided by the session beans, and store the data in scoped variables so that it can be retrieved from front-end page views. We'll tackle the index page first, then move on to the more complicated category page.

index page

The index page requires data for the four product categories. In our current setup, the JSTL <sql> tags query the database for category details each time the index page is requested. Since this information is rarely modified, it makes more sense from a performance standpoint to perform the query only once after the application has been deployed, and store the data in an application-scoped attribute. We can accomplish this by adding this code to the ControllerServlet's init method.

  1. In the Projects window, double-click the Source Packages > controller > ControllerServlet node to open it in the editor.
  2. Declare an instance of CategoryFacade, and apply the @EJB annotation to the instance.
    public class ControllerServlet extends HttpServlet {
    
        @EJB
        private CategoryFacade categoryFacade;
    
        ...
    }
    The @EJB annotation instructs the EJB container to instantiate the categoryFacade variable with the EJB named CategoryFacade.
  3. Use the IDE's hints to add import statements for:
    • javax.ejb.EJB
    • session.CategoryFacade

    Pressing Ctrl-Shift-I (⌘-Shift-I on Mac) automatically adds required imports to your class.

  4. Add the following init method to the class. The web container initializes the servlet by calling its init method. This occurs only once, after the servlet is loaded and before it begins servicing requests.
    public class ControllerServlet extends HttpServlet {
    
        @EJB
        private CategoryFacade categoryFacade;
    
        public void init() throws ServletException {
    
            // store category list in servlet context
            getServletContext().setAttribute("categories", categoryFacade.findAll());
        }
    
        ...
    }
    Here, you apply the facade class' findAll method to query the database for all records of Category. You then set the resulting List of Category objects as an attribute that can be referenced by the "categories" string. Placing the reference in the ServletContext means that the reference exists in a scope that is application-wide.

    To quickly determine the method signature of the findAll method, hover your mouse over the method while holding down the Ctrl key (⌘ on Mac). (The image below displays the popup that appears using NetBeans IDE 6.8.)

    Editor displaying method signature in a pop-up
    Clicking the hyperlink enables you to navigate directly to the method.
  5. Use the IDE's hint to add the @Overrides annotation. The init method is defined by HttpServlet's superclass, GenericServlet.
    Hint displayed in editor
    Adding the annotation is not required, however it does provide several advantages:
    • It enables you to use compiler checking to ensure that you are actually overriding a method that you assume you are overriding.
    • It improves readability, as it becomes clear when methods in your source code are being overridden.

    For more information on annotations, see the Java Tutorials: Annotations.

  6. Now that you have set up an application-scoped attribute that contains a list of categories, modify the index page to access the newly created attribute.

    Double-click the Web Pages > index.jsp node in the Projects window to open the file in the editor.
  7. Comment out (or delete) the <sql:query> statement that is listed at the top of the file. To comment out code in the editor, highlight the code, then press Ctrl-/ (⌘-/ on Mac).
    Commented-out snippet displayed in editor
  8. Modify the opening <c:forEach> tag so that its items attribute references the new application-scoped categories attribute.
    <c:forEach var="category" items="${categories}">
  9. Open the project's web deployment descriptor. Press Alt-Shift-O (Ctrl-Shift-O on Mac) and in the Go to File dialog, type 'web', then click OK.
    Go to File dialog
  10. Comment out (or delete) the <resource-ref> entry. The entry was required for the <sql> tags in order to identify the data source registered on the server. We are now relying on JPA to access the database, and the jdbc/affablebean data source has already been specified in the persistence unit. (Refer to the Design view of the project's persistence unit above.)

    Highlight the entire <resource-ref> entry, then press Ctrl-/ (⌘-/ on Mac).
    <!-- <resource-ref>
             <description>Connects to database for AffableBean application</description>
             <res-ref-name>jdbc/affablebean</res-ref-name>
             <res-type>javax.sql.ConnectionPoolDataSource</res-type>
             <res-auth>Container</res-auth>
             <res-sharing-scope>Shareable</res-sharing-scope>
         </resource-ref> -->
  11. Run the project. Click the Run Project ( Run Project button ) button. The project's index page opens in the browser, and you see that all four category names and images display.
    Index page displaying category details

category page

The category page requires three pieces of data in order to render properly:

  1. category data: for left column category buttons
  2. selected category: the selected category is highlighted in the left column, and the name of the selected category displays above the product table
  3. product data for selected category: for products displayed in the product table

Let's approach each of the three pieces of data individually.

category data

To account for category data, we can reuse the application-scoped categories attribute that we created for the index page.

  1. Open category.jsp in the editor, and comment out (Ctrl-/; ⌘-/ on Mac) the JSTL <sql> statements that are listed at the top of the file.
    <sql> statements commented out in editor
  2. Modify the opening <c:forEach> tag so that its items attribute references the application-scoped categories attribute. (This is identical to what you did above for index.jsp.)
    <c:forEach var="category" items="${categories}">
  3. Run the project to examine the current state of the category page. Click the Run Project ( Run Project button ) button. When the project's index page opens in the browser, click any of the four categories. The category buttons in the left column display and function as expected.
    Category page displaying category buttons in left column

selected category

To retrieve the selected category, we can use the categoryFacade that we already created to find the Category whose ID matches the request query string.

  1. Open the ControllerServlet in the editor. (If already opened, press Ctrl-Tab and choose from the pop-up list.)
  2. Start implementing functionality to acquire the selected category. Locate the TODO: Implement category request comment, delete it and add the following code (in bold).
    // if category page is requested
    if (userPath.equals("/category")) {
    
        // get categoryId from request
        String categoryId = request.getQueryString();
    
        if (categoryId != null) {
    
        }
    
    // if cart page is requested
    } else if (userPath.equals("/viewCart")) {
    You retrieve the requested category ID by calling getQueryString() on the request.

    Note: The logic to determine the selected category within the left column category buttons is already implemented in category.jsp using an EL expression, which is comparable to calling getQueryString() in the servlet. The EL expression is: pageContext.request.queryString.

  3. Add the following line of code within the if statement.
    // get categoryId from request
    String categoryId = request.getQueryString();
    
    if (categoryId != null) {
    
        // get selected category
        selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
    }
    You use the CategoryFacade's find method to retrieve the Category object based on the requested category ID. Note that you must cast categoryId to a Short, as this is the type used for the id field in the Category entity class.
  4. Click the badge ( Hint badge ) in the left margin to use the editor's hint to declare selectedCategory as a local variable within the doGet method.
    Editor hints
    Because selectedCategory is of type Category, which hasn't yet been imported into the class, the IDE automatically adds an import statement for entity.Category to the top of the file.
  5. Add the following line to place the retrieved Category object in the request scope.
    // get categoryId from request
    String categoryId = request.getQueryString();
    
    if (categoryId != null) {
    
        // get selected category
        selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
    
        // place selected category in request scope
        request.setAttribute("selectedCategory", selectedCategory);
    }
  6. In the editor, switch to category.jsp. (Press Ctrl-Tab and choose from the pop-up list.)
  7. Locate <p id="categoryTitle"> and make the following change.
    <p id="categoryTitle">
        <span style="background-color: #f5eabe; padding: 7px;">${selectedCategory.name}</span>
    </p>
    You are now using the selectedCategory attribute, which you just placed in the request scope from the ControllerServlet. Using '.name' within the EL expression calls the getName method on the given Category object.
  8. Switch back to the browser and refresh the category page. The name of the selected category now displays in the page.
    Category page displaying name of selected category

product data for selected category

In order to retrieve all products for a selected category, we'll make use of the Category entity's getProductCollection() method. Start by calling this method on selectedCategory to get a collection of all Products associated with the selectedCategory. Then store the collection of products as an attribute in the request scope, and finally reference the scoped attribute from the category.jsp page view.

  1. In the ControllerServlet, add the following statement to the code that manages the category request.
    // if category page is requested
    if (userPath.equals("/category")) {
    
        // get categoryId from request
        String categoryId = request.getQueryString();
    
        if (categoryId != null) {
    
            // get selected category
            selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
    
            // place selected category in request scope
            request.setAttribute("selectedCategory", selectedCategory);
    
            // get all products for selected category
            categoryProducts = selectedCategory.getProductCollection();
        }
    Calling getProductCollection() here enables us to get a collection of all Products associated with the selectedCategory.
  2. Use the editor's hint to define categoryProducts as a local variable for the doGet method.
    Editor hints
  3. Place the collection of Products in the request scope so that it can be retrieved from the application's front-end.
    // if category page is requested
    if (userPath.equals("/category")) {
    
        // get categoryId from request
        String categoryId = request.getQueryString();
    
        if (categoryId != null) {
    
            // get selected category
            selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
    
            // place selected category in request scope
            request.setAttribute("selectedCategory", selectedCategory);
    
            // get all products for selected category
            categoryProducts = selectedCategory.getProductCollection();
    
            // place category products in request scope
            request.setAttribute("categoryProducts", categoryProducts);
        }
  4. Open the category.jsp file in the editor and make the following change to the product table.
    <table id="productTable">
    
        <c:forEach var="product" items="${categoryProducts}" varStatus="iter">
    The <c:forEach> tag now references the categoryProducts collection. The c:forEach loop will now iterate over each Product object contained in the collection, and extract data accordingly.
  5. Press F6 (fn-F6 on Mac) to run the project. Navigate to the category page in the browser and note that all products now display for each category.
    Category page displaying products in table

This tutorial unit provided a brief introduction to JPA and EJB technologies. It also described the role of Java specifications, and how their reference implementations are used by the GlassFish application server. It then demonstrated how to create a set of JPA entity classes that provide a Java implementation of the project database. Then, following the session facade pattern, it showed how to create a set of EJB session beans that exist on top of the entity classes and enable convenient access to them. Finally, you modified the AffableBean project to utilize the new session beans and entities for database access required in the index and category pages.

You can download snapshot 4 of the AffableBean project, which corresponds to state the project after completing this unit using NetBeans IDE 6.9.

In the next unit you explore session management, and how to enable the application to remember a user's actions as he or she clicks through the site. This is key to implementing a shopping cart mechanism in an e-commerce application.



See Also

NetBeans Resources

EJB Resources

JPA Resources

GlassFish Resources

Technical Articles

Books


References

  1. ^ Adapted from EJB 3 In Action Chapter 1, section 1.1.2: EJB as a framework.
  2. ^ There are many other services provided by EJB. For a more comprehensive list, see EJB 3 In Action, Chapter 1, section 1.3.3: Gaining functionality with EJB services.




The NetBeans E-commerce Tutorial - Managing Sessions

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

Every e-commerce application that offers some form of shopping cart functionality needs to be able to remember user-specific data as users click through the website. Unfortunately for you the developer, the HTTP protocol, over which communication on the Internet takes place, is a stateless protocol. Each request received by your server is an independent piece of information that has no relation to previously received requests. Therefore, if a customer clicks a button to add an item to his or her shopping cart, your application must take measures to ensure not only that the state of the user's cart is updated, but that the action doesn't affect the cart of another user who happens to be browsing the site at the same time.

In order to properly handle the above-described scenario, you need to implement functionality so that a session can be created and maintained for the duration of a user's visit to the site. Servlet technology, which is the foundation of all Java-based web applications, provides for this with its HttpSession interface. You also need to define several classes, namely ShoppingCart and ShoppingCartItem, that allow the application to temporarily store user data while the session is being maintained.

This tutorial unit takes a different approach from others in the NetBeans E-commerce Tutorial. Instead of having you create project files and providing steps with code snippets for you to copy and paste into your own project, you open the completed project snapshot for this unit, and examine the code using the IDE's debugger and other tools. In the process, you'll learn how to apply an HttpSession object to your code so that each visit to the website results in a dedicated session. You also learn about scoped variables, and their usage in both Java classes and JSP pages. This unit also discusses HttpSession's default mechanism for maintaining sessions (i.e., cookies) and shows what steps need to be taken in the event that cookies are deactivated in a user's browser. Finally, session time-outs are covered, and the unit demonstrates how to handle them by creating a simple filter that intercepts requests to check whether a session exists.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 5

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

Handling Session Data

Applications can manage user sessions with the HttpSession object. You can bind user-specific data to the HttpSession object, then access this data at a later stage. Both bind and access actions can be done from Java classes, as well as from session-scoped variables in EL expressions.

Working with an HttpSession Object

The AffableBean application uses the HttpSession object to identify users over multiple requests. An HttpSession object is obtained using getSession() on a given request:

HttpSession session = request.getSession();

If a session object doesn't yet exist for the request, the method creates and returns a new session object.

You can use the session object as a vehicle for passing data between requests. You use the setAttribute method to bind objects to the session. Likewise, you use getAttribute to retrieve objects from the session. In the AffableBean application for example, the user's shopping cart is created and bound to the user session in the following manner:

ShoppingCart cart = new ShoppingCart();
session.setAttribute("cart", cart);

In order to retrieve the cart from the session, the getAttribute method is applied:

cart = (ShoppingCart) session.getAttribute("cart");

In JSP pages, you can access objects bound to the session using EL expressions. Continuing with the above example, if a ShoppingCart object named 'cart' is bound to the session, you can access the object using the following EL expression:

${cart}

Accessing the ShoppingCart object on its own is of little value however. What you really want is a way to access values stored in the object. If you explore the new ShoppingCart class in the project snapshot, you'll note that it contains the following properties:

  • double total
  • int numberOfItems
  • List<String, ShoppingCartItem> items

Provided that properties have matching getter methods, you can access values for singular properties using simple dot notation in an EL expression. If you examine the cart.jsp page, you'll see that this is exactly how the value for numberOfItems is accessed:

<p>Your shopping cart contains ${cart.numberOfItems} items.</p>

In order to extract data from properties that contain multiple values, such as the above items list, the cart.jsp page uses a <c:forEach> loop:

<c:forEach var="cartItem" items="${cart.items}" varStatus="iter">

  <c:set var="product" value="${cartItem.product}"/>

    <tr class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}">
        <td>
            <img src="${initParam.productImagePath}${product.name}.png"
                 alt="${product.name}">
        </td>

        <td>${product.name}</td>

        <td>
            &euro; ${cartItem.total}
            <br>
            <span class="smallText">( &euro; ${product.price} / unit )</span>
        </td>
        ...
    </tr>

</c:forEach>

ShoppingCartItem's product property identifies the product type for a cart item. The above loop takes advantage of this by first setting a product variable to the expression ${cartItem.product}. It then uses the variable to obtain information about that product (e.g., name, price).

Working with Scoped Variables in Web Applications

When working with JSP/Servlet technology, there are four scope objects available to you within the realm of the application. JSP technology implements implicit objects that allows you to access classes defined by the Servlet API.

Scope Definition Servlet Class JSP Implicit Object
Application Global memory for a web application javax.servlet.ServletContext applicationScope
Session Data specific to a user session javax.servlet.http.HttpSession sessionScope
Request Data specific to an individual server request javax.servlet.HttpServletRequest requestScope
Page Data that is only valid in the context of a single page (JSPs only) [n/a] pageScope

If you open your project's category.jsp file in the editor, you'll see that EL expressions include various scoped variables, including ${categories}, ${selectedCategory} and ${categoryProducts}. The ${categories} variable is application-scoped, which is set in the ControllerServlet's init method:

// store category list in servlet context
getServletContext().setAttribute("categories", categoryFacade.findAll());

The other two, ${selectedCategory} and ${categoryProducts}, are placed in the application's session scope from the ControllerServlet. For example:

// place selected category in session scope
session.setAttribute("selectedCategory", selectedCategory);

Note: If you are continuing from the previous tutorial units, you'll likely note that ${selectedCategory} and ${categoryProducts} were originally placed in the request scope. In previous units this was fine, but consider now what happens if a user clicks the 'add to cart' button in a category page. The server responds to an addToCart request by returning the currently viewed category page. It therefore needs to know the selectedCategory and the categoryProducts pertaining to the selected category. Rather than establishing this information for each request, you place it in the session scope from a category request so that it is maintained across multiple requests, and can be accessed when you need it. Also, examine the functionality provided by the cart page. (A functional description is provided below.) The 'continue shopping' button returns the user to the previously viewed category. Again, the selectedCategory and the categoryProducts variables are required.

When referencing scoped variables in an EL expression, you do not need to specify the variable's scope (provided that you do not have two variables of the same name in different scopes). The JSP engine checks all four scopes and returns the first variable match it finds. In category.jsp for example, the expression:

${categoryProducts}

is shorthand for:

${sessionScope.categoryProducts}
For more information, see the following resources:

Examining Session Data with the Java Debugger

Begin exploring how the application behaves during runtime. Use the IDE's debugger to step through code and examine how the HttpSession is created, and how other objects can be placed in the session scope to be retrieved at a later point.

  1. Open the project snapshot for this tutorial unit in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project. If you are proceeding from the previous tutorial unit, note that this project snapshot includes a new cart package, containing ShoppingCart and ShoppingCartItem classes. Also, the following files have been modified:
    • WEB-INF/web.xml
    • css/affablebean.css
    • WEB-INF/jspf/header.jspf
    • WEB-INF/jspf/footer.jspf
    • WEB-INF/view/cart.jsp
    • WEB-INF/view/category.jsp
    • WEB-INF/view/checkout.jsp
    • controller/ControllerServlet
  2. Run the project ( Run Project button ) to ensure that it is properly configured with your database and application server.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

  3. Test the application's functionality in your browser. If you are continuing directly from the previous tutorial unit, you'll note the following enhancements.

    category page

    • Clicking 'add to cart' for the first time enables the shopping cart and 'proceed to checkout' widgets to display in the header.
    • Clicking 'add to cart' results in an update to the number of cart items in the header's shopping cart widget.
    • Clicking 'view cart' results in the cart page displaying.
    • Clicking 'proceed to checkout' results in the checkout page displaying.
    Browser image of category page

    cart page

    • Clicking 'clear cart' results in shopping cart being emptied of items.
    • Clicking 'continue shopping' results in a return to the previously viewed category.
    • Clicking 'proceed to checkout' results in the checkout page displaying.
    • Entering a number (1 - 99) in an item's quantity field then clicking 'update' results in a recalculation of the total price for the item, and of the subtotal.
    • Entering zero in an item's quantity field then clicking 'update' results in the item being removed from the displayed table.
    Browser image of cart page

    checkout page

    • Clicking 'view cart' results in the cart page displaying.
    • Clicking 'submit purchase' results in the confirmation page displaying (without user-specific data).
    Browser image of checkout page
  4. Use the Go to File dialog to open the ControllerServlet in the editor. Press Alt-Shift-O (Ctrl-Shift-O on Mac), then type 'Controller' in the dialog and click OK.
    Go to File dialog
  5. Set a breakpoint in the doPost method on the line that creates an HttpSession object (line 150). To set a breakpoint, click in the left margin of the editor.
    Breakpoint set in editor

    To toggle line numbers for the editor, right-click in the left margin and choose Show Line Numbers.

  6. Run the debugger. Click the Debug Project ( Debug Project button ) button in the IDE's main toolbar. The GlassFish server starts (or restarts, if it is already running) and opens a socket on its debug port number. The application welcome page opens in your browser.

    You can view and modify the debug port number from the Servers window (Tools > Servers). Select the Java tab for the server you are using. Specify the port number in the 'Address to use' field under Debug Settings.

  7. When the application's welcome page displays in the browser, click any category image to navigate to the category page. Recall that clicking the 'add to cart' button sends an addToCart request to the server:
    <form action="addToCart" method="post">
    As you may recall from Preparing the Page Views and Controller Servlet, the ControllerServlet's doPost method handles requests for the /addToCart URL pattern. You can therefore expect that when a user clicks an 'add to cart' button, the doPost method is called.
  8. Click 'add to cart' for any product in the category page. Switch back to the IDE and note that the debugger suspends on the breakpoint.
    Debugger suspended on breakpoint in editor
  9. Place your cursor on the call to getSession() and press Ctrl-Space to invoke the Javadoc documentation.
    Javadoc documentation displayed in editor
    According to the documentation, getSession() returns the HttpSession currently associated with the request, and if no session exists, the method creates a new session object.

  10. Hover your mouse over the session variable. Note that the debugger suspends on the line it is about to execute. The value returned by getSession() has not yet been saved into the session variable, and you see a popup stating that "session is not a known variable in the current context."
    Debugger popup displayed in editor
  11. Click the Step Over ( Step Over button ) button in the debugger toolbar located above the editor. The line is executed, and the debugger steps to the next line in the file.
  12. Hover your mouse over the session variable again. Now you see the value currently set to the session variable.
    Debugger popup displayed in editor

    In NetBeans 6.9, you can click the grey pointer ( Step Over button ) in the popup to expand a list of variable values contained in the highlighted element.

  13. Click the Step Over ( Step Over button ) button (F8; fn-F8 on Mac) to arrive at the if statement (line 154). Because you just clicked the 'add to cart' button in the browser, you know that the expression userPath.equals("/addToCart") should evaluate to true.
  14. Highlight the userPath.equals("/addToCart") expression (by control-clicking with your mouse). This time you see a popup indicating the value of the expression you highlighted.
    Evaluated expression displayed in popup
  15. Press F8 (fn-F8 on Mac) to step to the next line (line 158). The application has been designed so that the ShoppingCart object for the user session is only created when the user adds an item to the cart for the first time. Since this is the first time the addToCart request has been received in this debug session, you can expect the cart object to equal null.
    Evaluated expression displayed in popup
  16. Press F8 (fn-F8 on Mac) to step to the next line (line 160). Then, on line 160, where the ShoppingCart object is created, click the Step Into ( Step Into button ) button. The debugger steps into the method being called. In this case, you are taken directly to the ShoppingCart's constructor.
    Evaluated expression displayed in popup
  17. Press Ctrl-Tab to switch back to the ControllerServlet. Note that the IDE provides a Call Stack ( Call Stack badge ) badge on line 160, indicating that the debugger is currently suspended somewhere on a method higher up in the call stack.

    Press Alt-Shift-3 (Ctrl-Shift-3 on Mac) to open the IDE's Call Stack window.

  18. Press F8 (fn-F8 on Mac) to continue stepping through code. When the debugger completes the ShoppingCart constructor, you are taken back to the ControllerServlet.

    Line 161 of the ControllerServlet binds the newly-created cart object to the session.
    session.setAttribute("cart", cart);
    To witness this, open the debugger's Variables window. Choose Window > Debugging > Variables, or press Alt-Shift-1 (Ctrl-Shift-1 on Mac).
    Variables window
    If you expand the session > session > attributes node, you are able to view the objects that are bound to the session. In the above image, there are two items currently bound to the session (highlighted). These are selectedCategory and categoryProducts, instantiated in the ControllerServlet at lines 83 and 89, respectively. Both of these items were bound earlier, when you clicked a category image, and the ControllerServlet processed the category page request.
  19. Press F8 (fn-F8 on Mac) to execute line 161. The cart object is bound to the session, and the Variables window updates to reflect changes. In the Variables window, note that the session now contains three attributes, the third being the newly initialized ShoppingCart object (highlighted below).
    Variables window

    So far, we have not "proven" that the session, as listed in the Variables window, represents an HttpSession. As previously mentioned, HttpSession is actually an interface, so when we talk about an HttpSession object, or session object, we are in fact referring to any object that implements the HttpSession interface. In the Variables window, if you hover your cursor over 'session', a popup displays indicating that the variable represents an HttpSession object. The StandardSessionFacade type, as displayed, is the internal class that GlassFish uses to implement the HttpSession interface. If you are familiar with Tomcat and are puzzled by the 'org.apache.catalina' paths that appear in the Value column, this is because the GlassFish web/servlet container is in fact a derivative of the Apache Tomcat container.

    A new ShoppingCart is added to the session, and the request continues to be processed. In order to complete implementation of the 'add to cart' functionality, the following actions are taken:
    • the ID of the selected product is retrieved from the request (line 165)
    • a Product object is created using the ID (line 169)
    • a new ShoppingCartItem is created using the product (line 170)
    • the ShoppingCartItem is added to ShoppingCart's items list (line 170)
  20. Press F8 (fn-F8 on Mac) to continue stepping through code while being mindful of the above-listed four actions. Pause when the debugger suspends on line 170.
  21. Create a watch on the session. This will allow you to view values contained in the session when you step into the addItem method in the next step. Right-click the session in the Variables window and choose Create Fixed Watch.
    Right-click menu displayed in Variables window

    Alternatively, you can place your cursor on the session variable in the editor, then right-click and choose New Watch. The New Watch dialog enables you to specify variables or expressions to watch continuously when debugging an application. (In the case of expressions, highlight the expression first, then right-click and choose New Watch.)
    New Watch dialog

    A new watch is created on the session variable and all variables it contains. The watch is visible from the Watches window (Window > Debugging > Watches) or, if you toggle the Watches ( Watches button ) button in the left margin of the Variables window, it displays in the top row of the Variables window.

    The debugger enables you to keep an eye on variables as it steps through code. This can be helpful, for example if you'd like to follow changes to specific variable values (and don't want to need to sift through the full list presented in the Variables window with each step), or if you temporarily step into a class that doesn't contain the variables you are interested in.
  22. Click the Step Into ( Step Into button ) button to step into ShoppingCart's addItem method.
  23. Step through the addItem method until you reach line 53. As the Javadoc states, addItem "adds a ShoppingCartItem to the ShoppingCart's items list. If item of the specified product already exists in shopping cart list, the quantity of that item is incremented."
  24. Examine the session variable which you created a watch on (step 21 above). The items.add(scItem) statement in line 51 added the new ShoppingCartItem to the items list in the ShoppingCart. This is evident by drilling into the third attribute (i.e., the cart variable) contained in the session.
    Variables window
    At this stage, you can see how an HttpSession is created for the request, how a ShoppingCart object is created and attached to the session, and how a ShoppingCartItem is created based on the user's product choice, then added to the ShoppingCart's list of items. The only remaining action is to forward the request to the category.jsp view.
  25. Open the header JSP fragment (header.jspf) in the editor and place a breakpoint on line 86. This line contains the EL statement within the shopping cart widget that displays the number of cart items.
    Breakpoint set in JSP page
  26. Click the Continue ( Continue button ) button in the debugger toolbar. The debugger continues until execution completes, or until it reaches another breakpoint. In this case, the debugger suspends on line 86 in the header JSP fragment.

    Note: In order to suspend the debugger in a JSP page, you need to set a breakpoint. For example, when the ControllerServlet forwards the request to the appropriate view, the debugger will not automatically suspend within the JSP page.

  27. Open the Variables window (Alt-Shift-1; Ctrl-Shift-1 on Mac) if it is not already open. Unlike with Java classes, the debugger does not provide tooltips when you hover your mouse over variables or expressions in a JSP page. However, the Variables window does enable you to determine variable values as you step through code. So, where can you find the value for ${cart.numberOfItems}?
  28. In the Variables window, expand the Implicit Objects > pageContext > session > session > attributes node. This provides access to the session object, just as you saw earlier when working in the ControllerServlet. In fact, you may note that the session which you created a watch on in step 21 above points to the very same object. Here you can verify that the value of ${cart.numberOfItems} equals '1'.
    Variables window

    Maximize the Variables window, or any window in the IDE, by right-clicking the window header, then choosing Maximize Window (Shift-Esc).

    The debugger gives you access to the pageContext implicit object. pageContext represents the context of the JSP page, and offers direct access to various objects including the HttpServletRequest, HttpSession, and ServletContext objects. For more information, see the Java EE 5 Tutorial: Implicit Objects.
  29. Click the Finish Session ( Finish Session button ) button. The runtime finishes executing, and the debug session terminates. The browser displays a fully-rendered category page, and you can see that the shopping cart widget in the page header contains one item.

Hopefully you now feel comfortable using the IDE's debugger not only to examine your project when it behaves unexpectedly, but also as a tool to become more familiar with code. Other useful buttons in the debugger toolbar include:

  • ( Step Out button ) Step Out: Steps you out of the current method call. Executes and removes the topmost method call in your call stack.
  • ( Run to Cursor button ) Run to Cursor: Executes up to the line on which your cursor is placed.
  • ( Apply Code Changes button ) Apply Code Changes: After editing a file, you can press this button so that the file is recompiled and changes are taken into account in the debug session.
  • ( Step Over Expression button ) Step Over Expression: Enables you to view the input parameters and resulting output values of each method call within an expression. You can inspect the output values for the previous method and the input parameters for the next method in the Local Variables window. When there are no further method calls, Step Over Expression behaves like the Step Over ( Step Over button ) command.

Examining Session Tracking Options

There are three conventional ways of tracking sessions between client and server. By far the most common is with cookies. URL rewriting can be applied in the event that cookies are not supported or disabled. Hidden form fields can also be used as a means of "maintaining state" over multiple requests, but these are limited to usage within forms.

The AffableBean project includes an example of the hidden field method in both the category and cart pages. The 'add to cart' and 'update' buttons that display for product items contain a hidden field which relays the product ID to the server when the button is clicked. If you open the cart.jsp page in the editor, you'll see that the <form> tags contain a hidden field.

<form action="updateCart" method="post">
    <input type="hidden"
           name="productId"
           value="${product.id}">
    ...
</form>

In this manner, the product ID is sent as a request parameter which the server uses to identify the item within the user's cart whose quantity needs to be modified.

The Servlet API provides a high-level mechanism for managing sessions. Essentially, it creates and passes a cookie between the client and server with each request-response cycle. If the client browser doesn't accept cookies, the servlet engine automatically reverts to URL rewriting. The following two exercises demonstrate this functionality.

Examining Client-Server Communication with the HTTP Monitor

By default, the servlet engine uses cookies to maintain and identify sessions between requests. A random, alphanumeric number is generated for each session object, which serves as a unique identifier. This identifier is passed as a 'JSESSIONID' cookie to the client. When the client makes a request, the servlet engine reads the value of the JSESSIONID cookie to determine the session which the request belongs to.

To demonstrate this, we'll use the debugger in tandem with the IDE's HTTP Monitor.

  1. Begin by activating the HTTP Monitor for the server you are using. Choose Tools > Servers. In the left column of the Servers window, select the server you are using (GlassFish). Then, in the main column, select the Enable HTTP Monitor option.
    Servers window
  2. If your server is already running, you need to restart it. However, since we plan to use the debugger, and running the debugger restarts the server to communicate on a different port, just click the Debug Project ( Debug Project button ) button in the IDE's main toolbar. The server restarts, a debug session begins and the application's welcome page opens in your browser. The HTTP Monitor displays in the bottom region of the IDE.
    HTTP Monitor
  3. Click the AffableBean record in the left column (as shown in the above image). When you select records in the left column, the right (i.e., main) column refreshes to display corresponding data. In the above image, the Request tab displays the requested URI (/AffableBean/), the HTTP method (GET), and points out that there was no query string sent with the request.
  4. Select the Session tab. Note that there is a statement, "The session was created as a result of this request." This is due to the fact that the server has sent a Set-Cookie header for the JSESSIONID cookie in its response. Also note that the new session ID is listed under 'Session properties'. As will later be shown, the session ID is the value of the JSESSIONID cookie.
    HTTP Monitor - Session tab
    You may wonder how a session object was created from a request for the site welcome page. After all, the ControllerServlet does not handle the initial request for /AffableBean/, and nowhere does this request encounter getSession(). Or does it? Recall that JSP pages are compiled into servlets upon deployment. Once you've deployed your project to the server, you can actually use the IDE to view the JSP's compiled servlet on your server.
  5. In the Projects window, right-click the index.jsp file and choose View Servlet. An index_jsp.java file opens in the editor. This is the servlet that was automatically compiled from the index.jsp page.
  6. Perform a search in the file for getSession. Press Ctrl-F (⌘-F on Mac), type 'getSession' in the search bar, then press Enter.

    Ctrl-F (⌘-F on Mac) is a keyboard shortcut for Edit > Find.

    Editor displaying getSession method
    The getSession method is in fact called. The reason this occurs is because JSP pages include the pageContext.session implicit object by default. If you wanted to deactivate this behavior, you could add the following directive to the top of a JSP file:
    <%@page session="false" %>
    and the getSession method in the compiled servlet would be removed.

    To find out the location of the compiled servlet on your server, you can hover your mouse over the servlet's name tab above the editor. A popup displays the path to the file on your computer.

  7. In the browser, select a category then add an item to your cart. Switch back to the IDE. Note that the debugger suspends on the breakpoint in the ControllerServlet you set earlier (line 150). All breakpoints are remembered between sessions. To remove the breakpoint, you could click the breakpoint ( Breakpoint badge ) badge in the editor's left margin. However, since there are multiple breakpoints already set in the project, open the debugger's Breakpoints window (Window > Debugging > Breakpoints).
    Breakpoints window
    From the Breakpoints window, you can view and call actions on all breakpoints set in projects opened in the IDE.
  8. Right-click the breakpoint set in header.jspf and choose Delete. Then right-click the breakpoint set in the ControllerServlet and choose Disable. (You'll re-enable it later in this exercise.)
  9. Click the Continue ( Continue button ) button. The request finishes executing, and the category page displays in the browser with one item added to the cart.
  10. In the HTTP Monitor, search for the addToCart request in the left column, then select it to display details in the main column.

    Click the Ascending Sort ( Ascending Sort button ) button so that the most recent records are listed at the top.


    Under the Request tab, note the requested URI (/AffableBean/addToCart), the HTTP method (POST), and the request parameters (productId and submit).
    HTTP Monitor - Request tab
  11. Select the Cookies tab. Here you see that a cookie named JSESSIONID exists, and was sent from the client to the server. Note that the value for the cookie is the same as the Session ID displayed under the Session tab.
    HTTP Monitor - Cookies tab
    Likewise, if you click the Header tab, you see the cookie listed, since 'Cookie' is a request header that was sent by the client.
    HTTP Monitor - Cookies tab

    See Wikipedia's List of HTTP headers for more information on request and response headers.

  12. Select the Session tab. There is a statement which indicates, "The session existed before this request." Also note that the cart attribute is listed under 'Session attributes after the request'. This makes sense, since we know that the cart object is bound to the session when the addToCart request is processed for the first time.
    HTTP Monitor - Session tab

    In the next few steps, locate the session ID and JSESSIONID cookie in the Variables window.
  13. Re-enable the breakpoint you set earlier in the ControllerServlet. Press Alt-Shift-5 (Ctrl-Shift-5 on Mac) to open the Breakpoints window, then click in the checkbox next to the breakpoint entry to re-enable it.
  14. In the browser, click the 'add to cart' button for one of the listed products.
  15. Switch to the IDE and note that the debugger is suspended on the breakpoint set in the ControllerServlet. Click the Step Over ( Step Over button ) button so that the session variable is assigned to the session object.
  16. Open the Variables window (Alt-Shift-1; Ctrl-Shift-1 on Mac) and expand session > session. You'll find the session ID listed as the value for the id variable.
  17. To locate the JSESSIONID cookie, recall that you can normally access cookies from a servlet by calling the getCookies method on the HttpServletRequest. Therefore, drill into the request object: request > Inherited > request > request > Inherited > cookies. Here you see the cookies ArrayList. If you expand the list, you'll find the JSESSIONID cookie, the value of which is the session ID.
  18. Click the Finish Session ( Finish Session button ) button to terminate the debug session.

Maintaining Sessions with URL Rewriting

As mentioned, the servlet engine detects whether cookies are supported for the client browser, and if not, it switches to URL rewriting as a means of maintaining sessions. This all happens transparently for the client. For you, the developer, the process isn't entirely transparent.

You need to ensure that the application is capable of rewriting URLs whenever cookies are disabled. You do this by calling the response’s encodeURL method on all URLs returned by servlets in your application. Doing so enables the session ID to be appended to the URL in the event that the use of cookies is not an option; otherwise, it returns the URL unchanged.

For example, the browser sends a request for AffableBean's third category (bakery): category?3. The server responds with session ID included in the URL:

/AffableBean/category;jsessionid=364b636d75d90a6e4d0085119990?3

As stated above, all URLs returned by your application's servlets must be encoded. Keep in mind that JSP pages are compiled into servlets. How can you encode URLs in JSP pages? JSTL's <c:url> tag serves this purpose. The following exercise demonstrates the problem and illustrates a solution.

  1. Temporarily disable cookies in your browser. If you are using Firefox, you can choose Tools > Options (Firefox > Preferences on Mac). In the window that displays, select the Privacy tab, then under History, select 'Use custom settings for history' in the provided drop-down. Deselect the 'Accept cookies from sites' option.
    Firefox Preferences window
  2. Run the AffableBean project. When the welcome page displays, click into a category, then try adding an item to your cart. You'll see that the application's functionality is severely compromised in its present state.
    Broken categories page
    As before, the server generates a session and binds objects to it. This is how the category page is able to display the selected category and products. However, the server has failed in its attempt to set a JSESSIONID cookie. Therefore, when the client makes a second request (when user clicks 'add to cart'), the server has no way of identifying the session which the request belongs to. It therefore cannot locate any of the attributes previously set in the session, such as selectedCategory and categoryProducts. This why the rendered response lacks the information specified by these attributes.
  3. Open the project's category.jsp page in the editor. Locate the line that implements the 'add to cart' button (line 58). The <form> element's action attribute determines the request sent to the server.
    <form action="addToCart" method="post">
  4. Modify the request so that it is passed through the <c:url> tag.
    <form action="<c:url value='addToCart'/>" method="post">
  5. Press Ctrl-S (⌘-S on Mac) to save changes to the file. Recall that the IDE provides the Deploy on Save feature, which is enabled by default. This means that any saved changes are automatically deployed to your server.
  6. In the browser, select a different category so that the application renders the newly modified category page.
  7. Examine the source code for the page. In Firefox, you can press Ctrl-U (⌘-U on Mac). The 'add to cart' button for each product displays with the session ID appended to the URL.
    <form action="addToCart;jsessionid=4188657e21d72f364e0782136dde" method="post">
  8. Click the 'add to cart' button for any item. You see that the server is now able to determine the session which the request belongs to, and renders the response appropriately.
  9. Before proceeding, make sure to re-enable cookies for your browser.

Again, every link that a user is able to click on within the application, whose response requires some form of session-related data, needs to be properly encoded. Sometimes implementation is not as straight-forward as the example shown above. For example, the 'clear cart' widget used in cart.jsp currently sets a clear parameter to true when the link is clicked.

<%-- clear cart widget --%>
<c:if test="${!empty cart && cart.numberOfItems != 0}">
    <a href="viewCart?clear=true" class="bubble hMargin">clear cart</a>
</c:if>

The <c:url> tag can be applied to the URL in the following manner:

<%-- clear cart widget --%>
<c:if test="${!empty cart && cart.numberOfItems != 0}">

    <c:url var="url" value="viewCart">
        <c:param name="clear" value="true"/>
    </c:url>

    <a href="${url}" class="bubble hMargin">clear cart</a>
</c:if>

The clear=true parameter is set by adding a <c:param tag between the <c:url> tags. A variable named 'url' is set using <c:url>'s var attribute, and var is then accessed in the HTML anchor tag using the ${url} expression.

You can download and examine snapshot 6 to see how all links in the project have been encoded.

URL rewriting should only be used in the event that cookies are not an available tracking method. URL rewriting is generally considered a suboptimal solution because it exposes the session ID in logs, bookmarks, referer headers, and cached HTML, in addition to the browser's address bar. It also requires more server-side resources, as the server needs to perform additional steps for each incoming request in order to extract the session ID from the URL and pair it with an existing session.


Handling Session Time-Outs

Setting Session Time Intervals

You should consider the maximum time interval which your server maintains sessions for. If your website receives heavy traffic, a large number of sessions could expend your server's memory capacity. You might therefore shorten the interval in hopes of removing unused sessions. On the other hand, you certainly wouldn't want to cut sessions too short, as this could become a usability issue that might have a negative impact on the business behind the website. Taking the AffableBean application as an example, a user proceeds to checkout after filling her shopping cart with items. She then realizes she needs to enter her credit card details and goes off to find her purse. After returning to her computer with credit card in hand, she fills in the checkout form and clicks submit. During this time however, her session has expired on the server. The user sees that her shopping cart is empty and is redirected to the homepage. Will she really take the time to step through the process again?

The following steps demonstrate how to set the session time-out interval in the AffableBean project to 10 minutes. Of course, the actual duration ultimately depends on your server resources, the business objectives of the application, and the popularity of your website.

  1. Open the application's deployment descriptor in the editor. Press Alt-Shift-O (Ctrl-Shift-O on Mac) to use the IDE's Go to File dialog. Type in 'web', then click OK.
    Go to File dialog
    The editor displays the web.xml file in the XML view. The template that NetBeans provides for the web.xml file includes a default setting for 30 minutes.
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
  2. Click the General tab, and type in '10' in the Session Timeout field.
    General tab of web.xml file
  3. Save the file (Ctrl-S; ⌘-S on Mac).

    If you switch back to the XML view, you'll see that the <session-timeout> element has been updated.
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>

Note: Alternatively, you could remove the <session-timeout> element altogether, and edit the session-properties element in the GlassFish-specific deployment descriptor (sun-web.xml). This would set the global time-out for all applications in the server's web module. See the Oracle GlassFish Server 3.0.1 Application Development Guide: Creating and Managing Sessions for more details.

Programmatically Handling Session Time-Outs

If your application relies on sessions, you need to take measures to ensure that it can gracefully handle situations in which a request is received for a session that has timed out or cannot be identified. You can accomplish this in the AffableBean application by creating a simple filter that intercepts requests heading to the ControllerServlet. The filter checks if a session exists, and if not, it forwards the request to the site's welcome page.

  1. Start by examining the problem that arises when a session times out midway through a user's visit to the site. Temporarily reset the session time-out interval to one minute. Open the web deployment descriptor (web.xml) and enter '1' between the <session-timeout> tags.
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>
  2. Run the AffableBean project. In the browser, click into a category page, add several items to your cart, then click 'view cart'.
    Cart page displaying items in shopping cart
  3. Wait at least one full minute.
  4. Update the quantity for one of the items displayed in the cart page. (Any number between 1 and 99 is acceptable.) Click 'update'. The server returns an HTTP Status 500 message.
    GlassFish error report displayed in browser
  5. Examine the GlassFish server log in the IDE. Open the Output window (Ctrl-4; ⌘-4 on Mac) and select the GlassFish Server tab. Scroll to the bottom of the log to examine the error's stack trace.
    GlassFish error report displayed in browser
    The server log indicates that a NullPointerException occurred at line 184 in the ControllerServlet. The Output window forms a link to the line where the exception occurred.
  6. Click the link. You navigate directly to line 184 in the ControllerServlet. Hovering your mouse over the error badge in the editor's left margin provides a tooltip describing the exception.
    Error badge and tooltip displayed in editor
    Because the session had already expired before the request was received, the servlet engine was unable to associate the request with its corresponding session. It was therefore unable to locate the cart object (line 151). The exception finally occurred in line 184 when the engine attempted to call a method on a variable equating to null.

    Now that we've identified the problem, let's fix it by implementing a filter.
  7. Click the New File ( New File button ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
  8. Select the Web category, then select Filter and click Next.
  9. Name the filter SessionTimeoutFilter. Type filter into the Packages field so that the filter class is placed in a new package when created.
  10. Click Next. Accept default settings and click Finish. A template for the SessionTimeoutFilter is generated and opens in the editor.

    Note: Currently, in NetBeans 6.9, it isn't possible to use the wizard to set a mapping to a servlet that isn't registered in the web deployment descriptor. (ControllerServlet was registered using the @WebServlet annotation.) We'll therefore modify the generated code in the next step.

  11. Modify the @WebFilter annotation signature so that it appears as follows.
    @WebFilter(servletNames = {"Controller"})
    public class SessionTimeoutFilter implements Filter {
    This sets the filter to intercept any requests that are handled by the ControllerServlet. (Alternatively, you could have kept the urlPatterns attribute, and listed all patterns that the ControllerServlet handles.)

    Note that 'Controller' is the name of the ControllerServlet, as specified in the servlet's @WebServlet annotation signature. Also note that you've removed the filterName attribute, since the name of the filter class is used by default.

    The IDE's filter template provides a lot of interesting code which is worth inspecting in its own right. However, most of it is not needed for our purposes here. Any filter class must implement the Filter interface, which defines three methods:
    • init: performs any actions after the filter is initialized but before it is put into service
    • destroy: removes the filter from service. This method can also be used to perform any cleanup operations.
    • doFilter: used to perform operations for each request the filter intercepts

    Use the Javadoc Index Search to pull up documentation on the Filter interface. Press Shift-F1 (fn-Shift-F1 on Mac), then type 'Filter' into the search field and hit Enter. Select the 'Interface in javax.servlet' entry. The Javadoc documentation displays in the lower pane of the index search tool.

  12. Replace the body of the SessionTimeoutFilter with the following contents.
    @WebFilter(servletNames = {"Controller"})
    public class SessionTimeoutFilter implements Filter {
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            HttpServletRequest req = (HttpServletRequest) request;
    
            HttpSession session = req.getSession(false);
    
            // if session doesn't exist, forward user to welcome page
            if (session == null) {
                try {
                    req.getRequestDispatcher("/index.jsp").forward(request, response);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return;
            }
    
            chain.doFilter(request, response);
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {}
    
        public void destroy() {}
    
    }
  13. Press Ctrl-Shift-I (⌘-Shift-I on Mac) to fix import statements. (Imports need to be added for HttpServletRequest and HttpSession.) Also, use the editor hints to add the @Override annotation to the init, destroy, and doFilter methods.

    In the coming steps, you run the debugger on the project and step through the doFilter method to see how it determines whether the request is bound to an existing session.
  14. Open the Breakpoints window (Alt-Shift-5; Ctrl-Shift-5 on Mac) and ensure that you do not have any existing breakpoints set. To delete a breakpoint, right-click the breakpoint and choose Delete. (If you completed the above exercise, Examining Client-Server Communication with the HTTP Monitor, you may have an outstanding breakpoint set in the ControllerServlet.)
  15. Run the debugger. Click the Debug Project ( Debug Project button ) button in the IDE's main toolbar.
  16. When the welcome page displays in the browser, select a category, then add several items to your shopping cart.
  17. Set a breakpoint on the line in SessionTimeoutFilter's doFilter method that tries to access the session (line 32).
    Breakpoint set in editor
  18. In the browser, click the 'view cart' button. Switch to the IDE and note that the debugger has suspended on the breakpoint.

    Recall that getSession() creates a new session object if the current one doesn't exist. Here, we use getSession(false), which refrains from creating a new object if none is found. In other words, the method returns null if the session doesn't exist.
  19. Click the Step Over ( Step Over button ) button, then hover your mouse over the session variable. Provided that a minute hasn't passed since the previous request was sent, you'll see that the variable has been assigned to a StandardSessionFacade. This represents the session object for the request.
    Popup displaying 'session' variable assigned to a session object
  20. Continue stepping through the method until the request is processed. Since session doesn't equal null, you skip the if statement and chain.doFilter then forwards the request to the ControllerServlet (line 44).
  21. In the browser, make sure a full minute has passed, then update a quantity for one of the product items in your cart. This is the same procedure we went through earlier in the exercise when the status 500 message was returned. Now that the filter intercepts requests heading to the ControllerServlet, let's see what happens when a session time-out occurs.
  22. After clicking 'update', switch to the IDE and note that the debugger is again suspended on the breakpoint set in the filter.
  23. Highlight the req.getSession(false) expression, then hover your mouse over it. Here you see the expression equates to null, as the session has already expired.
    Popup displaying 'session' variable equates to 'null'
  24. Continue stepping through the code. Now that the session variable equals null, the if statement on line 35 is processed, and the request is forwarded to /index.jsp. When the debugger finishes executing, you'll see that the browser displays the site's welcome page.
  25. Click the Finish Session ( Finish Session button ) button to terminate the debug session.
  26. Open the project's web.xml file and change the session time-out interval back to 10 minutes.
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
  27. Save (Ctrl-S; ⌘-S on Mac) the file.

Snapshot 6 provides you with the completed project version for this tutorial unit. One final topic concerning session management should be mentioned. You can explicitly terminate a session by calling the invalidate method on the session object. If the session is no longer needed, it should be removed in order to conserve the memory available to your server. After you complete the next unit, Integrating Transactional Business Logic, you will see how the ControllerServlet, upon successfully processing a customer order, destroys the user's cart object and terminates the session using the invalidate method.

// if order processed successfully send user to confirmation page
if (orderId != 0) {

    // dissociate shopping cart from session
    cart = null;

    // end session
    session.invalidate();

    ...
}

This is demonstrated in project snapshot 8 (and later snapshots).


See Also





The NetBeans E-commerce Tutorial - Integrating Transactional Business Logic

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

The purpose of this tutorial unit is to demonstrate how you can use the object-relational mapping (ORM) capabilities provided by EJB and JPA technologies to gather data from a web request and write to a back-end database. Of particular interest is EJB's support for container-managed transactions (refer to the GlassFish v3 Java EE Container diagram). By applying several non-intrusive annotations, you can transform your EJB class into a transaction manager, thereby ensuring the integrity of the data contained in the database. In other words, the transaction manager handles multiple write actions to the database as a single unit of work. It ensures that the work-unit is performed either in its entirety or, if failure occurs at some point during the process, any changes made are rolled back to the database's pre-transaction state.

Within the context of the AffableBean application, this tutorial unit focuses on processing a customer order when data from the checkout form is received. You create an OrderManager EJB to process the checkout form data along with the session cart object. The OrderManager performs a transaction that involves multiple write actions to the affablebean database. If any of the actions fails, the transaction is rolled back.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 7

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

Overview of the Transaction

In order to process the data from the checkout form as well as the items contained in the customer's shopping cart, you create an OrderManager EJB. The OrderManager uses the provided data and performs the following write actions to the database:

  • A new Customer record is added.
  • A new CustomerOrder record is added.
  • New OrderedProduct records are added, according to the items contained in the ShoppingCart.

We'll implement this by creating a placeOrder method which performs the three write actions by sequentially calling private helper methods, addCustomer, addOrder, and addOrderedItems. We'll also implement the three helper methods in the class. To leverage EJB's container-managed transaction service, we only require two annotations. These are:

Diagram of transaction implemented in AffableBean

Because we are implementing the transaction within a larger context, we'll approach this exercise by dividing it into several easily-digestible tasks.


Examining the Project Snapshot

Begin by examining the project snapshot associated with this tutorial unit.

  1. Open the project snapshot for this tutorial unit in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project. If you are proceeding from the previous tutorial unit, note that this project snapshot is identical to the state of the project after completing the previous unit, but with the following exceptions:
    • The confirmation.jsp page is fully implemented.
    • The affablebean.css stylesheet includes rules specific to the confirmation.jsp page implementation.
  2. Run the project ( Run Project button ) to ensure that it is properly configured with your database and application server.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

  3. Test the application's functionality in your browser. In particular, step through the entire business process flow. When you click the submit an order from the checkout page, the confirmation page currently displays as follows:
    Confirmation page displayed in browser
    No data related to the order is displayed on the confirmation page. In fact, in its current state the application doesn't do anything with the data from the checkout form. By the end of this tutorial unit, the application will gather customer data and use it to process an order. In its final state, the application will display a summary of the processed order on the confirmation page, remove the user's ShoppingCart and terminate the user session. (Snapshot 8 completes the request-response cycle when a checkout form is submitted.)

Creating the OrderManager EJB

  1. Click the New File ( New File button ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.) In the New File wizard, select the Java EE category, then select Session Bean.
  2. Click Next. Name the EJB 'OrderManager', place the EJB in the session package, and accept other default settings. (Create a stateless session bean, and do not have the wizard generate an interface for the bean.)
    Session Bean wizard
  3. Click Finish. The new OrderManager class is generated and opens in the editor.

Handling Request Parameters

  1. Open the project's ControllerServlet. (Either select it from the Projects window, or press Alt-Shift-O (Ctrl-Shift-O on Mac) and use the Go to File dialog.)
  2. Locate the area in the doPost method where the /purchase request will be implemented (line 190).

    Press Ctrl-G to use the Go To Line dialog.

    Go to Line dialog
  3. Implement code that extracts the parameters from a submitted checkout form. Locate the TODO: Implement purchase action comment, delete it, and add the following:
    // if purchase action is called
    } else if (userPath.equals("/purchase")) {
    
        if (cart != null) {
    
            // extract user data from request
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String cityRegion = request.getParameter("cityRegion");
            String ccNumber = request.getParameter("creditcard");
        }
    
        userPath = "/confirmation";
    }

Implementing placeOrder and Helper Methods

  1. In the ControllerServlet, add a reference to the OrderManager EJB. Scroll to the top of the class and add a reference beneath the session facade EJBs that are already listed.
    public class ControllerServlet extends HttpServlet {
    
        private String userPath;
        private String surcharge;
        private ShoppingCart cart;
    
        @EJB
        private CategoryFacade categoryFacade;
        @EJB
        private ProductFacade productFacade;
        @EJB
        private OrderManager orderManager;
  2. Press Ctrl-Shift-I (�:-Shift-I on Mac) to allow the editor to add an import statement for session.OrderManager.
  3. Use the extracted parameters, as well as the session cart object, as arguments for the OrderManager.placeOrder method. Add the following code:
    // if purchase action is called
    } else if (userPath.equals("/purchase")) {
    
        if (cart != null) {
    
            // extract user data from request
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String cityRegion = request.getParameter("cityRegion");
            String ccNumber = request.getParameter("creditcard");
    
            int orderId = orderManager.placeOrder(name, email, phone, address, cityRegion, ccNumber, cart);
        }
    
        userPath = "/confirmation";
    }
    Note that we haven't created the placeOrder method yet. This is why the editor flags an error. You can use the tip that displays in the left margin, which allows you to generate the method signature in the appropriate class.
    Tip displayed in editor
  4. Click the tip. The IDE generates the placeOrder method in the OrderManager class.
    @Stateless
    public class OrderManager {
    
        public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        ...
    }
    The import statement for cart.ShoppingCart is also automatically inserted at the top of the file.
  5. In the new placeOrder method, use the method arguments to make calls to the (yet nonexistent) helper methods. Enter the following:
    public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
        Customer customer = addCustomer(name, email, phone, address, cityRegion, ccNumber);
        CustomerOrder order = addOrder(customer, cart);
        addOrderedItems(order, cart);
    }
    Note that we need to follow a particular order due to database constraints. For example, a Customer record needs to be created before the CustomerOrder record, since the CustomerOrder requires a reference to a Customer. Likewise, the OrderedItem records require a reference to an existing CustomerOrder.
  6. Press Ctrl-Shift-I (⌘:-Shift-I on Mac) to fix imports. Import statements for entity.Customer and entity.CustomerOrder are automatically added to the top of the file.
  7. Use the editor hints to have the IDE generate method signatures for addCustomer, addOrder, and addOrderedItems. After utilizing the three hints, the OrderManager class looks as follows.
    @Stateless
    public class OrderManager {
    
        public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
            Customer customer = addCustomer(name, email, phone, address, cityRegion, ccNumber);
            CustomerOrder order = addOrder(customer, cart);
            addOrderedItems(order, cart);
        }
    
        private Customer addCustomer(String name, String email, String phone, String address, String cityRegion, String ccNumber) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        private CustomerOrder addOrder(Customer customer, ShoppingCart cart) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        private void addOrderedItems(CustomerOrder order, ShoppingCart cart) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
    }
    Note that an error is still flagged in the editor, due to the fact that the method is currently lacking a return statement. The placeOrder signature indicates that the method returns an int. As will later be demonstrated, the method returns the order ID if it has been successfully processed, otherwise 0 is returned.
  8. Enter the following return statement.
    public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
        Customer customer = addCustomer(name, email, phone, address, cityRegion, ccNumber);
        CustomerOrder order = addOrder(customer, cart);
        addOrderedItems(order, cart);
        return order.getId();
    }
    At this stage, all errors in the OrderManager class are resolved.
  9. Begin implementing the three helper methods. For now, simply add code that applies each method's input parameters to create new entity objects.

    addCustomer

    Create a new Customer object and return the object.

    private Customer addCustomer(String name, String email, String phone, String address, String cityRegion, String ccNumber) {
    
        Customer customer = new Customer();
        customer.setName(name);
        customer.setEmail(email);
        customer.setPhone(phone);
        customer.setAddress(address);
        customer.setCityRegion(cityRegion);
        customer.setCcNumber(ccNumber);
    
        return customer;
    }

    addOrder

    Create a new CustomerOrder object and return the object. Use the java.util.Random class to generate a random confirmation number.

    private CustomerOrder addOrder(Customer customer, ShoppingCart cart) {
    
        // set up customer order
        CustomerOrder order = new CustomerOrder();
        order.setCustomer(customer);
        order.setAmount(BigDecimal.valueOf(cart.getTotal()));
    
        // create confirmation number
        Random random = new Random();
        int i = random.nextInt(999999999);
        order.setConfirmationNumber(i);
    
        return order;
    }

    addOrderedItems

    Iterate through the ShoppingCart and create OrderedProducts. In order to create an OrderedProduct, you can use the OrderedProductPK entity class. The instantiated OrderedProductPK can be passed to the OrderedProduct constructor, as demonstrated below.

    private void addOrderedItems(CustomerOrder order, ShoppingCart cart) {
    
        List<ShoppingCartItem> items = cart.getItems();
    
        // iterate through shopping cart and create OrderedProducts
        for (ShoppingCartItem scItem : items) {
    
            int productId = scItem.getProduct().getId();
    
            // set up primary key object
            OrderedProductPK orderedProductPK = new OrderedProductPK();
            orderedProductPK.setCustomerOrderId(order.getId());
            orderedProductPK.setProductId(productId);
    
            // create ordered item using PK object
            OrderedProduct orderedItem = new OrderedProduct(orderedProductPK);
    
            // set quantity
            orderedItem.setQuantity(scItem.getQuantity());
        }
    }
  10. Press Ctrl-Shift-I (⌘-Shift-I on Mac) to fix imports. A dialog opens to display all classes that will be imported. Note that the dialog correctly guesses for java.util.List.
    Fix All Imports dialog
  11. Click OK. All necessary import statements are added, and the class becomes free of any compiler errors.

Utilizing JPA's EntityManager

As was mentioned in Adding Entity Classes and Session Beans, the EntityManager API is included in JPA, and is responsible for performing persistence operations on the database. In the AffableBean project, all of the EJBs employ the EntityManager. To demonstrate, open any of the session facade beans in the editor and note that the class uses the @PersistenceContext annotation to express a dependency on a container-managed EntityManager and its associated persistence context (AffableBeanPU, as specified in the persistence.xml file). For example, the ProductFacade bean looks as follows:

@Stateless
public class ProductFacade extends AbstractFacade<Product> {
    @PersistenceContext(unitName = "AffableBeanPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    ...

    // manually created
    public List<Product> findForCategory(Category category) {
        return em.createQuery("SELECT p FROM Product p WHERE p.category = :category").
               setParameter("category", category).getResultList();
    }

}

To be able to write to the database, the OrderManager EJB must take similar measures. With an EntityManager instance, we can then modify the helper methods (addCustomer, addOrder, addOrderedItems) so that the entity objects they create are written to the database.

  1. In OrderManager, apply the @PersistenceContext annotation to express a dependency on a container-managed EntityManager and the AffableBeanPU persistence context. Also declare an EntityManager instance.
    @Stateless
    public class OrderManager {
    
        @PersistenceContext(unitName = "AffableBeanPU")
        private EntityManager em;
    
        ...
    }
  2. Press Ctrl-Shift-I (⌘:-Shift-I on Mac) to fix imports. Import statements for javax.persistence.EntityManager and javax.persistence.PersistenceContext are added to the top of the class.
  3. Use the EntityManager to mark entity objects to be written to the database. This is accomplished using the persist method in the EntityManager API. Make the following modifications to the helper methods.

    addCustomer

    private Customer addCustomer(String name, String email, String phone, String address, String cityRegion, String ccNumber) {
    
        Customer customer = new Customer();
        customer.setName(name);
        customer.setEmail(email);
        customer.setPhone(phone);
        customer.setAddress(address);
        customer.setCityRegion(cityRegion);
        customer.setCcNumber(ccNumber);
    
        em.persist(customer);
        return customer;
    }

    addOrder

    private CustomerOrder addOrder(Customer customer, ShoppingCart cart) {
    
        // set up customer order
        CustomerOrder order = new CustomerOrder();
        order.setCustomer(customer);
        order.setAmount(BigDecimal.valueOf(cart.getTotal()));
    
        // create confirmation number
        Random random = new Random();
        int i = random.nextInt(999999999);
        order.setConfirmationNumber(i);
    
        em.persist(order);
        return order;
    }

    addOrderedItems

    private void addOrderedItems(CustomerOrder order, ShoppingCart cart) {
    
        List<ShoppingCartItem> items = cart.getItems();
    
        // iterate through shopping cart and create OrderedProducts
        for (ShoppingCartItem scItem : items) {
    
            int productId = scItem.getProduct().getId();
    
            // set up primary key object
            OrderedProductPK orderedProductPK = new OrderedProductPK();
            orderedProductPK.setCustomerOrderId(order.getId());
            orderedProductPK.setProductId(productId);
    
            // create ordered item using PK object
            OrderedProduct orderedItem = new OrderedProduct(orderedProductPK);
    
            // set quantity
            orderedItem.setQuantity(String.valueOf(scItem.getQuantity()));
    
            em.persist(orderedItem);
        }
    }
    The EntityManager's persist method does not immediately write the targeted object to the database. To describe this more accurately, the persist method places the object in the persistence context. This means that the EntityManager takes on the responsibility of ensuring that the entity object is synchronized with the database. Think of the persistence context as an intermediate state used by the EntityManager to pass entities between the object realm and the relational realm (hence the term 'object-relational mapping').

    What is the scope of the persistence context? If you open the IDE's Javadoc Index Search (Shift-F1; Shift-fn-F1 on Mac) and examine the Javadoc documentation for the @PersistenceContext annotation, you'll note that the type element is used to "specif[y] whether a transaction-scoped persistence context or an extended persistence context is to be used." A transaction-scoped persistence context is created at the start of a transaction, and terminated when the transaction ends. An extended persistence context applies to stateful session beans only, and spans multiple transactions. The Javadoc documentation also informs us that javax.persistence.PersistenceContextType.TRANSACTION is the default value for the type element. Therefore, although we didn't specify that the EntityManager place objects in a transaction-scoped persistence context, this is in fact how a container-managed EntityManager behaves by default.

Synchronizing the Persistence Context with the Database

At this stage you might assume that, transaction or no transaction, the OrderManager is now able to successfully write entity objects to the database. Run the project and see how customer orders are currently being processed.

  1. Press F6 (fn-F6 on Mac) to run the project.
  2. Step through the business process flow. When you arrive at the checkout page, be sure to enter data that you know will not cause SQL errors to occur when the write actions are performed. (Validation is discussed in a later tutorial unit.) For example, enter the following into the checkout form:
    • name: Hugo Reyes
    • email:
    • phone: 606252924
    • address: Karlova 33
    • prague: 1
    • credit card number: 1111222233334444

    In the coming steps, you are going to examine the server log in the IDE's Output window. Before submitting the checkout form, open the Output window and clear the server log. You can accomplish this by right-clicking in the server log and choosing Clear (Ctrl-L; ⌘-L on Mac).

  3. Click the 'submit purchase' button. The server responds with an HTTP status 500 message.
    Browser window displaying HTTP status 500 message
  4. Switch to the IDE and examine the server log. The server log is located in the Output window (Ctrl-4; ⌘-4 on Mac) under the GlassFish server tab. You come across the following text.
    WARNING: A system exception occurred during an invocation on EJB OrderManager method
    public int session.OrderManager.placeOrder(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,cart.ShoppingCart)
    javax.ejb.EJBException
    ...
    Caused by: java.lang.NullPointerException
            at session.OrderManager.addOrderedItems(OrderManager.java:75)
            at session.OrderManager.placeOrder(OrderManager.java:33)

    Maximize the Output window by pressing Shift-Esc.

    The underlines displayed in the server log form links allowing you to navigate directly to the lines in your source files where errors are occurring.
  5. Click the link to session.OrderManager.addOrderedItems. The editor displays the line that is causing the exception.
    Editor displaying NullPointerException error
    To understand why order.getId method returns null, consider what the code is actually trying to accomplish. The getId method attempts to get the ID of an order which is currently in the process of being created. Since the ID is an auto-incrementing primary key, the database automatically generates the value only when the record is added. One way to overcome this is to manually synchronize the persistence context with the database. This can be accomplished using the EntityManager's flush method.
  6. In the addOrderedItems method, add a call to flush the persistence context to the database.
    private void addOrderedItems(CustomerOrder order, ShoppingCart cart) {
    
        em.flush();
    
        List<ShoppingCartItem> items = cart.getItems();
    
        // iterate through shopping cart and create OrderedProducts
        for (ShoppingCartItem scItem : items) {
    
            int productId = scItem.getProduct().getId();
    
            // set up primary key object
            OrderedProductPK orderedProductPK = new OrderedProductPK();
            orderedProductPK.setCustomerOrderId(order.getId());
            orderedProductPK.setProductId(productId);
    
            // create ordered item using PK object
            OrderedProduct orderedItem = new OrderedProduct(orderedProductPK);
    
            // set quantity
            orderedItem.setQuantity(String.valueOf(scItem.getQuantity()));
    
            em.persist(orderedItem);
        }
    }
  7. Rerun the project and step through the business process flow. This time, when you submit the checkout form the confirmation page displays.
  8. To confirm that the details have been recorded in the database, open the IDE's Services window (Ctrl-5; ⌘-5 on Mac). Locate the affablebean connection node. If the node appears broken ( Broken connection node ), right-click the node and choose Connect.
  9. Drill into the connection and locate the affablebean database's customer table. Right-click the table and choose View Data. A graphical display of the customer table appears in the editor. The customer details that you added in the checkout form display as a record in the table.
    Graphical display of affablebean customer table
    In this manner, you can also examine the customer_order and ordered_product tables to determine whether data has been recorded.

Setting up the Transaction Programmatically

A transaction's primary function is to ensure that all operations are performed successfully, and if not, then none of the individual operations are performed.[1] The following steps demonstrate how to ensure that the write operations performed in the placeOrder method are treated as a single transaction.

  1. Refer to the transaction diagram above. Add the two transaction-related annotations to the OrderManager EJB.
    @Stateless
    @TransactionManagement(TransactionManagementType.CONTAINER)
    public class OrderManager {
    
        @PersistenceContext(unitName = "AffableBeanPU")
        private EntityManager em;
    
        @TransactionAttribute(TransactionAttributeType.REQUIRED)
        public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
            try {
                ...
    The @TransactionManagement annotation is used to specify that any transactions occurring in the OrderManager EJB are container-managed. The @TransactionAttribute annotation placed on the placeOrder method specifies that any operations occurring in the method must be treated as part of a transaction.

    According to the EJB Specification, container-managed transactions are enabled by default for session beans. Furthermore, if you examine the Javadoc for both of the above annotations, you will rightly point out that CONTAINER is the default TransactionManagementType, and REQUIRED is the default TransactionAttributeType. In other words, neither of the two annotations is required for your code to run properly. However, it is often helpful to explicitly include default settings in your sources to improve readability.

  2. Currently, the placeOrder method returns the ID of the processed order. In the event that the transaction fails and the order isn't processed, have the method return '0'. Use a try-catch expression.
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
        try {
            Customer customer = addCustomer(name, email, phone, address, cityRegion, ccNumber);
            CustomerOrder order = addOrder(customer, cart);
            addOrderedItems(order, cart);
            return order.getId();
        } catch (Exception e) {
            return 0;
        }

  3. Add the following code. Explanation follows.
    @PersistenceContext(unitName = "AffableBeanPU")
    private EntityManager em;
    @Resource
    private SessionContext context;
    
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public int placeOrder(String name, String email, String phone, String address, String cityRegion, String ccNumber, ShoppingCart cart) {
    
        try {
            Customer customer = addCustomer(name, email, phone, address, cityRegion, ccNumber);
            CustomerOrder order = addOrder(customer, cart);
            addOrderedItems(order, cart);
            return order.getId();
        } catch (Exception e) {
            context.setRollbackOnly();
            return 0;
        }
    }
    Unfortunately, placing the three methods in the try clause means that if one of them fails during runtime, the engine immediately jumps to the catch clause, thus skipping any rollback operations that would normally follow.

    You can test this by commenting out the em.flush() line you previously added. This way, you know that the first two methods (addCustomer and addOrder) process successfully, but the third method (addOrderedItems) fails. Run the project and submit the checkout form in the browser. Since the transaction doesn't roll back, the customer and order records are written to the database, but any ordered items are not. This leads to a situation where the database is corrupt.

    To overcome this, you explicitly set the transaction for rollback in the catch clause. The above @Resource annotation is applied to grab an instance of the EJB's current SessionContext. The transaction is marked for rollback using the setRollbackOnly method.
  4. Run the project and step through the business process flow. When you submit an order, return to the IDE and examine the server log. You'll see output similar to the following:
    Output window - server output

    Press Shift-Esc on the Output window to maximize it.

    As shown in the above image, the green text indicates output from EclipseLink. Recall how in Adding Entity Classes and Session Beans you set EclipseLink's logging level to FINEST in the persistence unit. Being able to examine this output is key to understanding how the persistence provider interacts with the database and is a great help when you need to debug your project.

You've now successfully integrated the transaction into the AffableBean project. You can download snapshot 8 to examine code that completes the request-response cycle when a checkout form is submitted. The snapshot implements a getOrderDetails method in the OrderManager, which gathers all details pertaining to the placed order. If the transaction succeeds, the ControllerServlet places order details in the request scope, destroys the user's cart object, terminates the session, and forwards the request to the confirmation view. If the transaction fails, the ControllerServlet flags an error and forwards the response to the checkout view, enabling the user to attempt a resubmit.

Checkout page displayed with process failure message

Validating and Converting User Input

Also included in snapshot 8 are implementations for client and server-side validation for the checkout form. Form validation is the process of checking that a form has been filled in correctly before it is processed. This not only aids users by providing meaningful feedback for fields with invalid entries, but it also serves to thwart any malicious attempts to submit content that could adversely affect processing or storage.

There are two primary methods for validating forms: server-side (in our case, using Java), and client-side (using JavaScript). Both methods are usually essential for providing a pleasant user experience, as well as robust security for your application. Client-side validation is useful for offering immediate feedback to the user without the need to initiate a round-trip between the browser and server. As such, it can stem network traffic and decrease the server load. Modern forms of client-side validation are often implemented to provide immediate, "as-you-type", field-specific feedback to the user. Client-side JavaScript is run on the browser, and browsers generally allow JavaScript to be disabled. For this reason alone, your application cannot rely on client-side validation as the sole means of guarding against malformed or nefarious input. Server-side validation checks should therefore be performed when form data reaches the server. Data is extracted from the request and checked prior to being processed and/or stored. If a validation error is detected, the server responds by returning the form to the user with an appropriate message. If all data passes validation, data is converted to a different format if required.

Client-Side Validation

For the AffableBean application, client-side validation is provided by a popular jQuery plugin. jQuery is a cross-browser JavaScript library designed to simplify client-side scripting of HTML.

jQuery field validation displayed on checkout form

Snapshot 8 includes a js folder that contains the jQuery core library (jquery-1.4.2.js) as well as the script for the validation plugin (jquery.validate.js). The core library is referenced in the application header.jspf file, while the validation plugin script is referenced directly in checkout.jsp since it is only required by that file. Within checkout.jsp, the plugin is customized to suit the checkout form based on available documentation.

<script type="text/javascript">

    $(document).ready(function(){
        $("#checkoutForm").validate({
            rules: {
                name: "required",
                email: {
                    required: true,
                    email: true
                },
                phone: {
                    required: true,
                    number: true,
                    minlength: 9
                },
                address: {
                    required: true
                },
                creditcard: {
                    required: true,
                    creditcard: true
                }
            }
        });
    });
</script>

The IDE provides support for jQuery by enabling you to invoke code completion and documentation in the editor when pressing Ctrl-Space.

jQuery documentation popup window in editor

When you code in JavaScript, the IDE lets you specify which browsers your application is targeting. Open the Options window (Choose Tools > Options; NetBeans > Preferences on Mac), select Miscellaneous, then select the JavaScript tab.

Options window - JavaScript pane

If the function you are calling documentation on does not support all of your targeted browsers, the documentation popup flags a warning. For example in the image below, Internet Explorer version 5.5 has been included in the application's targeted browsers.

JavaScript documentation popup

Server-Side Validation

The purpose of server-side validation is to ensure that each piece of data is in a format that is ready for further processing or is acceptable for storage. By "format", we mean both the data type as well as the size of the piece of data. The generated JPA entity classes are guaranteed to map their properties to the appropriate data types of the corresponding database table columns. When relying on these entity classes, we need to not only make sure that user data can be applied to create (or update) entity classes, but that the size of the data is appropriate for the data types of the database columns.

To illustrate an example, consider the checkout form's credit card number field. Client-side validation checks that the entered data does not include letters.[2] Because the maxlength attribute in the HTML markup is set to 19, users cannot enter more than 19 characters into this field. Server-side validation also places a limit at 19 characters. Keep in mind that the data type of the cc_number column in the database's customer table is: VARCHAR(19) (Refer to step 3 of Designing the Data Model: Adding Entity Properties.) Now, consider what would happen if the data type of the cc_number column is set to VARCHAR(16), and a user enters a number that is 19 characters long. When the checkout form is submitted, the creditcard parameter is extracted from the request and converted into a String so that it becomes the ccNumber property in a newly created Customer object. Because 16 is the maximum number of characters the database column will hold, the database server will either truncate the number to 16 characters or produce a MysqlDataTruncation error, depending on the SQL mode set for the server. (For more information on the VARCHAR data type, see 10.4.1. The CHAR and VARCHAR Types.) In this manner, by not having client and server-side validation properly handle the size (i.e., length) of the data received for a credit card number, we risk a failed attempt at placing an order, or perhaps even worse, a truncated credit card number, which obviously won't allow payment.

Server-side validation in the AffableBean project is implemented by means of a Validator class. The ControllerServlet creates a Validator object and calls its validateForm method on the user data:

// validate user data
boolean validationErrorFlag = false;
validationErrorFlag = validator.validateForm(name, email, phone, address, cityRegion, ccNumber, request);

// if validation error found, return user to checkout
if (validationErrorFlag == true) {
    request.setAttribute("validationErrorFlag", validationErrorFlag);
    userPath = "/checkout";

    // otherwise, save order to database
} else {

    ...
}

If a validation error is found (i.e., if validateForm returns true), a flag is raised in the form of a request-scoped attribute, and the server sends the checkout page back to the client. When the flag is detected in checkout.jsp, a new table row is created to display error messages at the top of the table.

<form id="checkoutForm" action="<c:url value='purchase'/>" method="post">
    <table id="checkoutTable">
      <c:if test="${!empty validationErrorFlag}">
        <tr>
            <td colspan="2" style="text-align:left">
                <span class="error smallText">Please provide valid entries for the following field(s):

                  <c:if test="${!empty nameError}">
                    <br><span class="indent"><strong>name</strong> (e.g., Bilbo Baggins)</span>
                  </c:if>
                  <c:if test="${!empty emailError}">
                    <br><span class="indent"><strong>email</strong> (e.g., )</span>
                  </c:if>
                  <c:if test="${!empty phoneError}">
                    <br><span class="indent"><strong>phone</strong> (e.g., 222333444)</span>
                  </c:if>
                  <c:if test="${!empty addressError}">
                    <br><span class="indent"><strong>address</strong> (e.g., KorunnĂ­ 56)</span>
                  </c:if>
                  <c:if test="${!empty cityRegionError}">
                    <br><span class="indent"><strong>city region</strong> (e.g., 2)</span>
                  </c:if>
                  <c:if test="${!empty ccNumberError}">
                    <br><span class="indent"><strong>credit card</strong> (e.g., 1111222233334444)</span>
                  </c:if>

                </span>
            </td>
        </tr>
      </c:if>

      ...
    </table>
</form>

You can test server-side validation by temporarily disabling JavaScript in your browser.

Server-side validation displayed on checkout form

The provided implementation of server-side validation here serves merely to demonstrate how server-side validation can be set up in your project. The actual validation logic contained in the Validator class does not perform anything beyond the most basic of checks and should certainly not be used in a production environment!

Data Conversion

Sometimes, after data has passed validation, you may need to convert it into a different format. For example, this might apply to dates when users are allowed to enter them manually, or numbers that have been received as String objects but require calculation. This important step is referred to as server-side data conversion.

Although not implemented in the AffableBean application, consider again the checkout form's credit card number field. Both client and server-side validation allows for both formats of the following number:

1111222233334444
and:
1111-2222-3333-4444

Because of the ambiguous nature in which this piece of user data is acquired, it might be necessary to remove any hyphens ('-') or other non-numeric characters prior to processing payment. This step would likely occur before the data is placed in storage.


See Also


References

  1. ^ This all or nothing concept can be further extrapolated into the four defining characteristics of transactions: atomicity, consistency, isolation, and durability (ACID). For more information, see: ACID [Wikipedia].
  2. ^ Actually, for credit card number entries, validation typically ensures that the entered string conforms to the Luhn algorithm, which is a simple method of differentiating between valid numbers and a collection of random digits. This applies to the jQuery validation plugin as well. For more information, see Luhn algorithm [Wikipedia].




The NetBeans E-commerce Tutorial - Adding Language Support

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

The goal of this tutorial unit is to demonstrate how to enable language support for a web application. "Language support" here refers to the ability to display page views according to the customer-specified languages. Within the context of the AffableBean application, we have agreed to provide support for both English and Czech, as per the previously outlined customer requirements.

In order to accomplish this, you rely on Java's support for internationalization. You create a resource bundle for each language and let the Java runtime environment determine the appropriate language for incoming client requests. You also implement a 'language toggle' to enable users to switch the languages manually.

The NetBeans IDE provides special support for localizing application content. This includes a Customizer dialog that enables you to add new locales to an existing resource bundle base name, as well as a special Properties editor that lets you view and edit key-value pairs for all locales in a table layout. These are both utilized in this tutorial.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 8
AffableBean project snapshot 9

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

Understanding Resource Bundles

In Java, a resource bundle is a representation of the java.util.ResourceBundle class. As stated in the Javadoc,

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows you to write programs that can:
  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locales

From the Javadoc, you can also note that the ResourceBundle is parent to both ListResourceBundle and PropertyResourceBundle. In this tutorial we utilize the PropertyResourceBundle, which manages resources as text files that use the .properties extension and contain locale-specific information in the form of key-value pairs. With new each translation, a new version of the resource bundle is created by appending the locale identifier to the base name using an underscore ('_'). For example, snippets from two of the resource bundles you create in this tutorial look as follows:

messages_en.properties

meats=meats
bakery=bakery

messages_cs.properties

meats=maso
bakery=peÄŤivo

In the above example, 'messages' represents the base name, and the locale identifier is the two-letter code which is appended using an underscore. (i.e., 'en' for English, 'cs' for Czech). The two-letter codes are derived from the international ISO 639 standard, which lists codes that represent the names of languages. The ISO 639 standard is adopted by the W3C Internationalization Activity and is used by all major browsers (these are the codes understood in the Accept-Language HTTP header). It is also internalized in the java.util.Locale class.


Making Pages Multilingual

Returning to the AffableBean application, after continued discussions with the customer you've agreed on the following implementation details:

  • The website initially displays based on the preferred language of the user's browser.
  • If the browser's preferred language is neither English nor Czech, the site displays text in English.
  • The user has the option of changing the language by means of a 'language toggle' in the page header.
  • When using the language toggle to change the language, the user remains in the same page view.
  • The language toggle should not appear for the confirmation page, as a user will already have selected his or her language prior to checkout.

In order to implement the above points, divide the task into two parts. Start by creating basic bilingual support for page views. Once bilingual support is in place, implement the language toggle that enables users to manually switch languages.

There are three basic steps that you need to follow to incorporate multilingual support into your web pages.

  1. Create a resource bundle for each language you plan to support.
  2. Register the resource bundle with the application by setting a context parameter in the web.xml deployment descriptor.
  3. In page views, replace 'hard-coded' text with <fmt:message> tags that reference keys in the resource bundles.

The following exercise demonstrates how to integrate English and Czech language support into the AffableBean welcome page by applying the above three steps, and finishes by showing how to test for browser language support using Firefox.

  1. Create Resource Bundles
  2. Register the Resource Bundle with the Application
  3. Replace 'Hard-Coded' Text with <fmt:message> Tags
  4. Test Supported Languages

Create Resource Bundles

  1. Open the AffableBean project snapshot 8 in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project.
  2. Click the Run Project ( Run Project button ) button to run the project and ensure that it is properly configured with your database and application server.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

  3. Begin by creating a default resource bundle to contain text used in page views. Click the New File ( New File button ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
  4. Under Categories select Other, then under File Types select Properties File.
    New File wizard
    Note that the wizard provides a description for the selected file type:
    Creates a resource bundle (.properties) file suitable for internationalizing applications by separating out all human-visible text strings from your code. Resource bundle files can also be used to collect other types of strings, such as properties for Ant scripts. The created resource bundle contains only one locale, but you can add additional locales from the created file's contextual menu. The bundle can be edited in a text file (property-file format) for a specific locale or in a table that displays information for all locales.
  5. Click Next. In the Name and Location step, name the file messages and type in src/java/resources in the Folder field. This will instruct the wizard to place the resource bundle in a new package named resources.
    New Properties File wizard
  6. Click Finish. The messages.properties resource bundle is generated and opens in the editor.

    Note that the new messages.properties file name does not have a language code appended to it, as was previously described. This is because this file will be used as the default resource bundle. The default resource bundle is applied when the Java runtime environment does not find a direct match for the requested locale.
  7. Open the project's index.jsp file in the editor and note that the following text is currently used:
    • Greeting: Welcome to the online home of the Affable Bean Green Grocer.
    • Introductory Message: Enjoy browsing and learning more about our unique home delivery service bringing you fresh organic produce, dairy, meats, breads and other delicious and healthy items to your doorstep.
    Also, note that we'll need language-specific names for the four categories that display when index.jsp renders in the browser. Since these names are currently taken from the database, we can use them as keys in the resource bundle.

    Recall that one of the implementation details outlined above states that "if the browser's preferred language is neither English nor Czech, the site displays text in English." Therefore, the values that we apply to the messages.properties file will be in English.
  8. In the messages.properties file, begin adding key-value pairs for the text used in the welcome page. Add the following content.
    # welcome page
    greeting=Welcome to the online home of the Affable Bean Green Grocer.
    introText=Our unique home delivery service brings you fresh organic produce, dairy, meats, breads and other delicious and healthy items direct to your doorstep.
    
    # categories
    dairy=dairy
    meats=meats
    bakery=bakery
    fruit\ &\ veg=fruit & veg
    Comments are added using a number sign ('#'). Also, because the fruit & veg category name contains spaces, it is necessary to escape the space characters using a backslash ('\') in order to apply the name as a resource bundle key.

    We are now finished with the default resource bundle for the application's welcome page. Let's continue by creating resource bundles for the customer-specified languages.
  9. In the Projects window, expand the Source Packages node, then right-click the resources > messages.properties file node and choose Customize. The Customizer dialog opens.
  10. In the Customizer dialog, click the Add Locale button. In the New Locale dialog that displays, enter 'en' in the Language Code combo box, then click OK.
    New Locale dialog

    A locale can be defined by both a language and a geographic region. The optional country code which can be used to specify the region can be applied to define formatting for dates, time, numbers, and currency. For more information, see the technical article, Understanding Locale in the Java Platform.

  11. Click the Add Locale button again, then enter 'cs' in the Language Code combo box and click OK. The Customizer dialog displays as follows.
    New Locale dialog
  12. Click Close. In the Projects window, note that your resource bundles look as follows. You can expand a resource bundle to view the keys it contains.
    Resource bundles displayed in Projects window
  13. Right-click any of the three resource bundles and choose Open. The Properties editor opens, enabling you to view and edit key-value pairs for all locales in a table layout.

    Press Shift-Esc to maximize the window in the IDE.

    Note that when you add a new locale using the Customizer dialog, as you did for English and Czech in the previous steps, the keys and values of the default resource bundle are copied to the new locale.
  14. Modify the values for the Czech resource bundle. You can do this by either clicking into the table cells for each row and typing your entries directly or selecting the cell you want to edit and typing into the Value field located at the bottom of the Properties editor.
    • greeting: VĂ­tejte v našem domácĂ­m on-line obchodÄ› Affable Bean Green Grocer.
    • introText: Naše jedineÄŤná dodávková sluĹľba Vám zajistĂ­ dopravu ÄŤerstvÄ‚Ëťch organickÄ‚Ëťch produktĹŻ, mlĂ©ÄŤnÄ‚Ëťch vÄ‚ËťrobkĹŻ, uzenin, peÄŤiva a dalších delikates a zdravÄ‚Ëťch vÄ‚ËťrokĹŻ aĹľ ke dveřím.
    • dairy: mlĂ©ÄŤnĂ© vÄ‚Ëťrobky
    • meats: maso
    • bakery: peÄŤivo
    • fruit & veg: ovoce a zeleniny

    You can also add a comment to each key-value pair. Any text you enter into the Comment field in the Properties editor is added to the resource bundle text file above the key-value pair as a comment (i.e., following a '#' sign).

  15. Double-click the messages_cs.properties file node in the Projects window. Note that the text file has been updated according to your changes in the Properties editor.
    # welcome page
    greeting=Vítejte v našem domácím on-line obchodě Affable Bean Green Grocer.
    introText=Naše jedinečná dodávková služba Vám zajistí dopravu čerstvých organických produktů, mléčných výrobků, uzenin, pečiva a dalších delikates a zdravých výroků až ke dveřím.
    
    # categories
    dairy=mléčné výrobky
    meats=maso
    bakery=peÄŤivo
    fruit\ &\ veg=ovoce a zeleniny

We now have the following resource bundles defined:

  • default (English)
  • Czech
  • English

You might assume that if the default bundle is in English, then there is no need to create a resource bundle explicitly for English. However, consider the following scenario: a client browser's list of preferred languages includes both Czech and English, with English taking precedence over Czech. If the application doesn't provide a resource bundle for English but does for Czech, pages sent to that browser will be in Czech (since a Czech bundle was defined). This is clearly not the desired behavior for that browser.

Register the Resource Bundle with the Application

The purpose of this step is to inform JSTL's format (i.e., fmt) tag library where it can locate any resource bundles existing in the application. You accomplish this by instructing the application to create a LocalizationContext using the existing resource bundles. This can be done by setting a context parameter in the application's web.xml deployment descriptor.

The topic of setting context parameters is also covered in Connecting the Application to the Database.

  1. In the Projects window, expand the Configuration Files node, then double-click web.xml to open it in the editor.
  2. Under the deployment descriptor's General tab, expand the Context Parameters category.
  3. Click the Add button, then in the Add Context Parameter dialog enter the following values.
    • Parameter Name: javax.servlet.jsp.jstl.fmt.localizationContext
    • Parameter Value: resources.messages
    Add Context Parameter dialog

    The LocalizationContext class belongs to the javax.servlet.jsp.jstl.fmt package. You can verify this by viewing the JSTL 1.1 API Reference online.

  4. Click OK. The new context parameter is added to the table of existing context parameters under the General tab.
  5. Click the deployment descriptor's XML tab. Note that the following entry has been added to the file:
    <context-param>
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
        <param-value>resources.messages</param-value>
    </context-param>

Replace Hard-Coded Text with <fmt:message> Tags

In order to apply the localized text of resource bundles to your web pages, you reference the keys from the key-value pairs you created. You can reference the keys using JSTL's <fmt:message> tags.

  1. Open the project's index.jsp page in the editor. (If already opened, press Ctrl-Tab to switch to the file.)
  2. Delete instances of hard-coded text that display in the page's left column, and in their place enter <fmt:message> tags using the key attribute to specify the resource bundle key. The page's left column will look as follows.
    <div id="indexLeftColumn">
        <div id="welcomeText">
            <p style="font-size: larger"><fmt:message key='greeting'/></p>
    
            <p><fmt:message key='introText'/></p>
        </div>
    </div>
  3. Add <fmt:message> tags for the four category names, but use the ${category.name} expression as the value for the key attribute. Since the category name is also used as the value for the <img> tag's alt attribute, follow the same procedure. The page's right column will look as follows.
    <div id="indexRightColumn">
        <c:forEach var="category" items="${categories}">
            <div class="categoryBox">
                <a href="<c:url value='category?${category.id}'/>">
                    <span class="categoryLabel"></span>
                    <span class="categoryLabelText"><fmt:message key='${category.name}'/></span>
    
                    <img src="${initParam.categoryImagePath}${category.name}.jpg"
                         alt="<fmt:message key='${category.name}'/>" class="categoryImage">
                </a>
            </div>
        </c:forEach>
    </div>
  4. Finally, ensure that you have the fmt tag library declared in the web page. Enter the following at the top of the file:
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

    Note: Here you add the tag library declaration to the top of the index.jsp file. However, when you begin using <fmt> tags elsewhere in the project, it may make more sense to remove the tag library declaration from individual page views, and add it to the header (header.jspf) file. This practice is adopted in snapshot 9 (and later snapshots).

You've now completed the tasks necessary for providing bilingual support for the application's welcome page. The following step demonstrates how to test the language support in your browser.

Test Supported Languages

You could theoretically test for the following scenarios involving the application's supported languages, as well as an unsupported language (e.g., Korean):

Use-case Outcome
 1. Browser has no preferred language English displays
 2. Browser prefers only English English displays
 3. Browser prefers only Czech Czech displays
 4. Browser prefers only Korean English displays
 5. Browser prefers Korean and English; Korean takes precedence English displays
 6. Browser prefers Korean and English; English takes precedence English displays
 7. Browser prefers Korean and Czech; Korean takes precedence Czech displays
 8. Browser prefers Korean and Czech; Czech takes precedence Czech displays
 9. Browser prefers English and Czech; English takes precedence English displays
10. Browser prefers English and Czech; Czech takes precedence Czech displays
11. Browser prefers, in the following order, English, Czech, Korean English displays
12. Browser prefers, in the following order, English, Korean, Czech English displays
13. Browser prefers, in the following order, Czech, English, Korean Czech displays
14. Browser prefers, in the following order, Czech, Korean, English Czech displays
15. Browser prefers, in the following order, Korean, English, Czech English displays
16. Browser prefers, in the following order, Korean, Czech, English Czech displays

Rather than stepping through all 16 scenarios, we'll demonstrate how to examine scenario 3 above, in which the browser's preferred language is Czech, using the Firefox browser.

  1. In Firefox, choose Tools > Options (Firefox > Preferences on Mac). In the window that displays, click the Content tab.
    Firefox options - Content tab
  2. Under the Languages heading, click Choose.
  3. Select any language that is currently listed in the provided text area, then click Remove. (You should remember your language list and reinstate languages after completing this tutorial.)
  4. Click the 'Select Language to Add' drop-down and select Czech [cs]. Then click the Add button. The Czech language is added to the text area.
    Firefox options - General tab
  5. Click OK, then press Esc to close Firefox' Options window.
  6. Run the project ( Run Project button ). When the welcome page opens in your browser, note that text is displayed in Czech.
    Czech text displayed in welcome page

Implementing a Language Toggle

Now that basic Czech-English language support is in place, continue by implementing the language toggle in the application's page views. We can divide this task into three parts:

Create Toggle Display and Synchronize with the Browser's Preferred Language

  1. Use the Go to File dialog to open the header JSP fragment in the editor. Press Alt-Shift-O (Ctrl-Shift-O on Mac), then type 'h' in the dialog and click OK.
    Go to File dialog
  2. In the header.jspf file, locate the first <div class="headerWidget"> tag (line 56), and replace the [ language toggle ] placeholder text with the following HTML markup.
    <div class="headerWidget">
    
        <%-- language selection widget --%>
        english | <div class="bubble"><a href="chooseLanguage?language=cs">česky</a></div>
    </div>
    This markup implements the language toggle's appearance when English is the displayed language. In other words, the toggle provides a link allowing the user to select the Czech (i.e., 'ÄŤesky') option. The link is used to send a request for chooseLanguage, and creates a query string (?language=cs) that specifies the requested language code.

    Note: Recall that in Unit 5, Preparing the Page Views and Controller Servlet, you set the ControllerServlet to handle the /chooseLanguage URL pattern.

    Snapshot 8 includes the jQuery JavaScript library and takes advantage of various UI effects to enhance the appearance and behavior of the website. Aside from a jQuery plugin for client-side validation (discussed in the previous tutorial unit), the snapshot implements an easing effect for category headings in the welcome page, as well as for category buttons in the category page. Configuration is included in header.jspf of the project snapshot. Rounded corners are implemented using CSS3's border-radius property (applied in affablebean.css).

  3. Run the project ( Run Project button ) to see what the toggle looks like in the browser.
    Language toggle in browser
    Currently, the language toggle appears as in the above image regardless of what language the page displays in. In the next step, you integrate JSTL logic into the toggle so that it renders according to the language displayed on the page.
  4. Modify the toggle implementation as follows.
    <div class="headerWidget">
    
        <%-- language selection widget --%>
        <c:choose>
          <c:when test="${pageContext.request.locale.language ne 'cs'}">
            english
          </c:when>
          <c:otherwise>
            <c:url var="url" value="chooseLanguage">
              <c:param name="language" value="en"/>
            </c:url>
            <div class="bubble"><a href="${url}">english</a></div>
          </c:otherwise>
        </c:choose> |
    
        <c:choose>
          <c:when test="${pageContext.request.locale.language eq 'cs'}">
            ÄŤesky
          </c:when>
          <c:otherwise>
            <c:url var="url" value="chooseLanguage">
              <c:param name="language" value="cs"/>
            </c:url>
            <div class="bubble"><a href="${url}">česky</a></div>
          </c:otherwise>
        </c:choose>
    </div>
    In the above implementation, you rely on conditional tags from JSTL's core tag library to display the left and right portions of the toggle according to the language used by the request locale. What is the "language used by the request locale"? When a request is made, the browser passes a list of preferred locales in the Accept-Language HTTP header. The Java runtime environment on the server reads the list and determines the best match based on the locales defined by the application's resource bundles. This match is then recorded in the ServletRequest object, and can be accessed using the getLocale method. For example, you could access the preferred locale from a servlet with the following statement.
    request.getLocale();

    You can use the IDE's HTTP Monitor (Window > Debugging > HTTP Server Monitor) to examine HTTP headers for client requests. In order to use the HTTP Monitor, you need to first activate it for the server you are using. Unit 8, Managing Sessions provides a demonstration under the sub-section, Examining Client-Server Communication with the HTTP Monitor.

    To determine the language of the preferred locale, you use the Locale class' getLanguage method. Again, from a servlet you could access the language of the client request's preferred locale with the following.

    request.getLocale().getLanguage();

    Returning to the code you just added to the header.jspf fragment, you utilize the pageContext.request implicit object to access the ServletRequest for the given client request. Using dot notation, you then proceed to call the same methods as you would from a servlet. In the above example, accessing the "language used by the request locale" is as simple as:

    ${pageContext.request.locale.language}

    Note: The above implementation uses <c:url> tags to set up the toggle link. This is done in order to properly encode the request URL in the event that URL rewriting is used as a means for session tracking. Unit 8, Managing Sessions provides a brief explanation of how the <c:url> tags can be used.

  5. Add a basic language test to the header.jspf file. This will enable us to check whether the toggle is properly rendering according to the client request's preferred language. Enter the following after the page's <body> tag.
    <body>
    
        <%-- Language test --%>
        <p style="text-align: left;"><strong>tests:</strong>
            <br>
            <code>\${pageContext.request.locale.language}</code>: ${pageContext.request.locale.language}
        </p>
    
        <div id="main">
  6. Ensure that you have set Czech as your browser's preferred language. (If you are following this tutorial unit sequentially, you've already done this. If not, refer to the steps outlined above in Test Supported Languages.)
  7. Run the project ( Run Project button ) and examine the application welcome page in the browser.
    Language test and welcome page displayed in browser
    If your browser's preferred language is set to Czech, you can note the following:
    • The test that we introduced in the previous step indicates that 'cs' is the preferred language.
    • Czech text is displayed in the page.
    • The language toggle provides a link enabling the user to select English.

Implement Functionality to Handle a Request from the Language Toggle

Now that the toggle is in place and it appears according to the language displayed in the page, let's continue by adding code to the ControllerServlet that handles the request sent when a user clicks the link in the language toggle.

As indicated in the current language toggle implementation from step 4 above, the requested URL with query string looks as follows:

  • English: chooseLanguage?language=en
  • Czech: chooseLanguage?language=cs

Our goal is to register the language choice, and then display both the page view and language toggle based on the chosen language. We can accomplish this by extracting the language parameter from the query string and creating a session-scoped language attribute that remembers the language selected by the user. Then we'll return to the header.jspf fragment and apply the <fmt:setLocale> tag to set the page language based on the user's choice. With the <fmt:setLocale> tag we can manually switch the language used in the page display. We'll also modify the language toggle so that if the language attribute has been set, the toggle's appearance is determined according to the language attribute's value.

  1. Open the ControllerServlet in the editor. Use the Go To File dialog - press Alt-Shift-O (Ctrl-Shift-O on Mac), then type 'controller' and click OK. In the opened file, locate the portion of the doGet method that handles the chooseLanguage request (line 126).
  2. Delete the // TODO: Implement language request comment and enter code to extract the language parameter from the request query string.
    // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
    
        // get language choice
        String language = request.getParameter("language");
    }
  3. Place the language parameter in the request scope. Add the following.
    // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
    
        // get language choice
        String language = request.getParameter("language");
    
        // place in request scope
        request.setAttribute("language", language);
    }
  4. As a temporary measure, have the application forward the response to the index.jsp welcome page when the language toggle link is clicked. Add the following code.
    // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
    
        // get language choice
        String language = request.getParameter("language");
    
        // place in request scope
        request.setAttribute("language", language);
    
        // forward request to welcome page
        try {
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return;
    }
    Naturally, forwarding the user to the welcome page regardless of what page he or she is on is not an ideal way to handle the language toggle's behavior. We'll return to this matter in the next sub-section, Enable the Application to Keep Track of the Originating Page View. For the meantime however, this will allow us to examine the results of the current language toggle implementation when running the project.
  5. Switch to the header.jspf fragment (If the file is already opened in the editor, press Ctrl-Tab and choose the file.) and apply the <fmt:setLocale> tag to set the page language based on the new language variable. Add the following.
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    
    <%-- Set language based on user's choice --%>
    <c:if test="${!empty language}">
        <fmt:setLocale value="${language}" scope="session" />
    </c:if>
    
    
    <%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
    Since the language variable is only created when the user clicks the link in the language toggle, you perform a test using <c:if> tags to determine whether the variable exists before attempting to set the language. When applying the <fmt:setLocale> tag, you set its scope to session as you want the user-selected language to take precedence for the remainder of his or her session on the website. Also, since this is the first time the fmt library is used in the header, you declare the tag library.

    You can read the EL expression ${!empty language} as, "False if the language variable is null or an empty string." See the Java EE 5 Tutorial: Examples of EL Expressions for other available examples.

  6. Modify the language toggle implementation so that if a value has been set by the <fmt:setLocale> tag, the toggle displays according to the language specified by that value. (You can determine this value using the ${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']} expression.)

    Enclose the current implementation within <c:choose> tags, and create logic similar to the current implementation in the event that the locale has been manually set. (Changes are displayed in bold.)
    <div class="headerWidget">
    
      <%-- language selection widget --%>
      <c:choose>
        <%-- When user hasn't explicitly set language,
             render toggle according to browser's preferred locale --%>
        <c:when test="${empty sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}">
          <c:choose>
            <c:when test="${pageContext.request.locale.language ne 'cs'}">
              english
            </c:when>
            <c:otherwise>
              <c:url var="url" value="chooseLanguage">
                <c:param name="language" value="en"/>
              </c:url>
              <div class="bubble"><a href="${url}">english</a></div>
            </c:otherwise>
          </c:choose> |
    
          <c:choose>
            <c:when test="${pageContext.request.locale.language eq 'cs'}">
              ÄŤesky
            </c:when>
            <c:otherwise>
              <c:url var="url" value="chooseLanguage">
                <c:param name="language" value="cs"/>
              </c:url>
              <div class="bubble"><a href="${url}">česky</a></div>
            </c:otherwise>
          </c:choose>
        </c:when>
    
        <%-- Otherwise, render widget according to the set locale --%>
        <c:otherwise>
          <c:choose>
            <c:when test="${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session'] ne 'cs'}">
              english
            </c:when>
            <c:otherwise>
              <c:url var="url" value="chooseLanguage">
                <c:param name="language" value="en"/>
              </c:url>
              <div class="bubble"><a href="${url}">english</a></div>
            </c:otherwise>
          </c:choose> |
    
          <c:choose>
            <c:when test="${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session'] eq 'cs'}">
              ÄŤesky
            </c:when>
            <c:otherwise>
              <c:url var="url" value="chooseLanguage">
                <c:param name="language" value="cs"/>
              </c:url>
              <div class="bubble"><a href="${url}">česky</a></div>
            </c:otherwise>
          </c:choose>
        </c:otherwise>
      </c:choose>
    
    </div>
  7. Before examining the project in a browser, add another test that displays the value set by the <fmt:setLocale> tag. Add the following code beneath the test you created earlier.
    <p style="text-align: left;"><strong>tests:</strong>
        <br>
        <code>\${pageContext.request.locale.language}</code>: ${pageContext.request.locale.language}
        <br>
        <code>\${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}</code>: ${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}
    </p>

    javax.servlet.jsp.jstl.fmt.locale.session is the string literal key for the Locale set by the <fmt:setLocale> tag. You can verify this by clicking in the editor's left margin to set a breakpoint ( Breakpoint badge ) on the new test, then running the debugger ( Debug Project button ) on the project. When you click the toggle link to change languages in the browser, examine the Variables window (Alt-Shift-1; Ctrl-Shift-1 on Mac) when the debugger suspends on the breakpoint.

    EL expressions presented in this tutorial primarily use dot (.) notation. The format depicted in the expression above is known as bracket ([]) notation whereby you enter the string literal key within quotes in order to extract the object's value:

    ${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}

    Numerous EL resolver classes exist for the purpose of resolving expressions. For example, when the above expression is encountered at runtime, the ImplicitObjectResolver first returns a Map that maps session-scoped attribute names to their values. (In the above image of the Variables window, you can verify that session attributes are maintained in a ConcurrentHashMap.) In order to resolve the remainder of the expression, the MapELResolver is used to get the value of the key named 'javax.servlet.jsp.jstl.fmt.locale.session'.

    For more information, refer to the Java EE 5 Tutorial: Unified Expression Language: Resolving Expressions.

  8. Run the project ( Run Project button ) and examine the application welcome page in the browser.
    Welcome page displayed in browser
    In the above image, the server identifies Czech (cs) as the browser's preferred language from the Accept-Language HTTP header. This is indicated from the first test. The page displays in Czech, and the language toggle enables the user to choose English. The second test remains blank as the <fmt:setLocale> tag has not yet been called.
  9. Click the toggle link for English.
    Welcome page displayed in browser
    When clicking the toggle link, the default Czech language is overridden by means of the <fmt:setLocale> tag implemented in the header.jspf file. Although the browser's preferred language remains Czech, you see that the page now displays according to the new language made available by the language toggle.
  10. Click the toggle link for Czech.
    Welcome page displayed in browser
    Changing the language back to the browser's preferred language works as expected, however note that the deciding factor is no longer the language detected from the Accept-Language HTTP header, but is the language specified from the <fmt:setLocale> tag.
  11. Before continuing, remove the tests you added to the header.jspf file. (Deleted code in strike-through text.)
    <body>
    
        <%-- Language tests --%>
        <p style="text-align: left;"><strong>tests:</strong>
            <br>
            <code>\${pageContext.request.locale.language}</code>: ${pageContext.request.locale.language}
            <br>
            <code>\${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}</code>: ${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session']}
        </p>
    
        <div id="main">

Enable the Application to Keep Track of the Originating Page View

One of the implementation details which you have agreed on with the Affable Bean staff is that when the language toggle is used to change the language, the user remains in the same page view. In our current implementation, the welcome page is returned whenever the language toggle is clicked. A more user-friendly approach would be to provide the application with a means of tracking the request page view, and forwarding the request to that page view when the language toggle link is clicked.

We can accomplish this by setting a session-scoped view attribute within each of the page views, then referencing this attribute in the ControllerServlet in order to determine where to forward the request. There are however several caveats to consider when dealing with the language toggle in the confirmation page. These are discussed and dealt with in steps 7-11 below.

Begin this exercise with snapshot 9 of the AffableBean project. This snapshot includes completed English and Czech resource bundles for all page views, all page views have been modified to use text from the resource bundles, and the language toggle is presented in a state corresponding to this point in the tutorial.

  1. Open snapshot 9 in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project.
  2. Click the Run Project ( Run Project button ) button to run the project. When navigating through the site, note that when you click the language toggle from any of the page views, you are returned to the application's welcome page.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

  3. Use <c:set> tags to set a session-scoped view attribute for each of the page views. Open each of the page views in the editor and add the following code to the top of each file.

    index.jsp

    <%-- Set session-scoped variable to track the view user is coming from.
         This is used by the language mechanism in the Controller so that
         users view the same page when switching between English and Czech. --%>
    <c:set var='view' value='/index' scope='session' />

    category.jsp

    <%-- Set session-scoped variable to track the view user is coming from.
         This is used by the language mechanism in the Controller so that
         users view the same page when switching between English and Czech. --%>
    <c:set var='view' value='/category' scope='session' />

    cart.jsp

    <%-- Set session-scoped variable to track the view user is coming from.
         This is used by the language mechanism in the Controller so that
         users view the same page when switching between English and Czech. --%>
    <c:set var='view' value='/cart' scope='session' />

    checkout.jsp

    <%-- Set session-scoped variable to track the view user is coming from.
         This is used by the language mechanism in the Controller so that
         users view the same page when switching between English and Czech. --%>
    <c:set var='view' value='/checkout' scope='session' />
    Based on customer-agreed implementation details, we do not need to provide a means of switching languages on the confirmation page view. From a usability perspective, a user will have already selected his or her preferred language prior to checkout. From an implementation perspective, recall that we destroy the user session upon a successfully completed order. (Refer back to the final paragraph in Managing Sessions, which describes how to apply the invalidate method to explicitly terminate a user session.) If the Affable Bean staff were to insist on allowing customers to view their orders bilingually, you would need to consider the following scenarios, dependent on whether you destroy the user session upon displaying the confirmation page:
    1. Session destroyed: Would be necessary to take extra measures to ensure that a chooseLanguage request from the confirmation page refers to the appropriate order, and can display customer-sensitive details in a secure fashion.
    2. Session maintained: Would risk enabling users to mistakenly place double orders on their shopping cart. Also, by not terminating user sessions when they are no longer needed, an unnecessary load may be placed on the server.
  4. Open the ControllerServlet in the editor. (If already opened, press Ctrl-Tab and choose the file.) In the opened file, locate the portion of the doGet method that handles the chooseLanguage request (line 126).

    Note that currently chooseLanguage requests are forwarded to the index.jsp welcome page.
    // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
    
        // get language choice
        String language = request.getParameter("language");
    
        // place in session scope
        session.setAttribute("language", language);
    
        // forward request to welcome page
        try {
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return;
    }
  5. Use the view session attribute to forward the request back to the originating page view. Make the following changes (in bold).
    // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
    
        // get language choice
        String language = request.getParameter("language");
    
        // place in request scope
        request.setAttribute("language", language);
    
        String userView = (String) session.getAttribute("view");
    
        if ((userView != null) &&
            (!userView.equals("/index"))) {     // index.jsp exists outside 'view' folder
                                                // so must be forwarded separately
            userPath = userView;
        } else {
    
            // if previous view is index or cannot be determined, send user to welcome page
            try {
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return;
        }
    }
    In the above implementation, you extract the value of the view attribute and, provided that the view:
    • can be identified (i.e., the value is not null),
    • does not originate from the welcome page (index.jsp does not reside in the same location as other page views, and therefore cannot be resolved using the doGet method's way of forwarding requests)
    ...you set it to the doGet method's userPath variable, and forward the request using the method's existing RequestDispatcher:
    // use RequestDispatcher to forward request internally
    String url = "/WEB-INF/view" + userPath + ".jsp";
    
    try {
        request.getRequestDispatcher(url).forward(request, response);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
  6. Run the project ( Run Project button ) to test it in the browser. When you navigate to the category, cart or checkout pages, switch languages using the language toggle. When you do so, you now remain within the same page view.
  7. In the browser, complete an order so that the application forwards you to the confirmation page. When you click the language toggle from the confirmation page, note that you are sent back to the website's welcome page.

    Implementation-wise, you may consider this to be sufficient. However, the Affable Bean staff have explicitly asked you to remove the language toggle from this page view. One way to accomplish this is to perform a test to determine whether the request servlet path contains '/confirmation'.

    Switch to the header.jspf file in the editor and surround the language toggle with the following test. You can use JSTL's functions (i.e., fn) library to perform string operations.
    <div class="headerWidget">
    
      <%-- If servlet path contains '/confirmation', do not display language toggle --%>
      <c:if test="${!fn:contains(pageContext.request.servletPath,'/confirmation')}">
    
        <%-- language selection widget --%>
        <c:choose>
    
            ...
        </c:choose>
    
      </c:if>
    </div>
    Examine the above code snippet and note the following points:
    • The servlet path can be accessed from the HttpServletRequest using the getServletPath method. Because we use a RequestDispatcher to forward the request to the confirmation page (ControllerServlet, line 158), the servlet path becomes:
      /WEB-INF/view/confirmation.jsp
    • Using the pageContext.request.servletPath EL expression is comparable to calling request.getServletPath() from a servlet.
    • The fn:contains() function allows you to test if an input string contains the specified substring.
    • The fn tag library has already been declared for you at the top of in the header.jspf file in snapshot 9:
      <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
  8. Run the project again and step through to the confirmation page. Note that the page no longer displays the language toggle.
    Confirmation page displayed in browser
  9. In the browser, step through to the confirmation page but switch languages once along the way using the language toggle. Note that when you complete an order, the confirmation page inadvertently switches back to the originally displayed language. You may rightly identify the cause: upon a successfully completed order, the ControllerServlet destroys the user session and consequently the session-scoped locale that was set using the <fmt:setLocale> tag is also lost.

    To remedy this, open the ControllerServlet and locate the invalidate() method which is used to destroy user sessions (approximately line 259).

    Use the editor's quick search facility: press Ctrl-F (⌘-F on Mac) and type in 'invalidate'.

  10. Add code that extracts the session-scoped locale value prior to destroying the user session and resets the request-scoped language attribute to the locale value after the session has been destroyed. (Changes in bold.)
    // if order processed successfully send user to confirmation page
    if (orderId != 0) {
    
        // in case language was set using toggle, get language choice before destroying session
        Locale locale = (Locale) session.getAttribute("javax.servlet.jsp.jstl.fmt.locale.session");
        String language = "";
    
        if (locale != null) {
    
            language = (String) locale.getLanguage();
        }
    
        // dissociate shopping cart from session
        cart = null;
    
        // end session
        session.invalidate();
    
        if (!language.isEmpty()) {                       // if user changed language using the toggle,
                                                         // reset the language attribute - otherwise
            request.setAttribute("language", language);  // language will be switched on confirmation page!
        }
    
        // get order details
        Map orderMap = orderManager.getOrderDetails(orderId);
    
        ...
        userPath = "/confirmation";
    }
  11. Run the project and again, step through to the confirmation page but switch languages once along the way using the language toggle. Note that when you complete an order, the confirmation page now displays in the language you selected.

You have now successfully integrated language support into the AffableBean application according to customer specification. You've factored out all text from page views, placed it into resource bundles, and have applied JSTL's fmt tag library to use resource bundle content based on the user's preferred language. You also implemented a language toggle that enables users to switch between English and Czech, and override their browser's default language choice. Download and examine snapshot 10 to compare your work with the state of the project at the end of this tutorial unit.



See Also





The NetBeans E-commerce Tutorial - Securing the Application

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

This tutorial unit focuses on web application security. When securing web applications, there are two primary concerns that need to be addressed:

  1. Preventing unauthorized users from gaining access to protected content.
  2. Preventing protected content from being read while it is being transmitted.

The first concern, access control, is typically a two-step process that involves (1) determining whether a user is who he or she claims to be (i.e., authentication), and then (2) either granting or denying the user access to the requested resource (i.e., authorization). A simple and common way to implement access control for web applications is with a login form that enables the server to compare user credentials with a pre-existing list of authenticated users.

The second concern, protecting data while it is in transit, typically involves using Transport Layer Security (TLS), or its predecessor, Secure Sockets Layer (SSL), in order to encrypt any data communicated between the client and server.

Upon reviewing the Affable Bean staff's list of requirements, we'll need to secure the application in the following ways:

  • Set up a login form for the administration console that enables staff members access to the console's services, and blocks unauthorized users.
  • Configure secure data transport for both the customer checkout process, and for any data transmitted to and from the administration console.

In order to implement the above, we'll take advantage of NetBeans' visual editor for the web.xml deployment descriptor. We'll also work in the GlassFish Administration Console to configure a "user group" that corresponds to Affable Bean staff members, and verify SSL support.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
MySQL database server version 5.1
AffableBean project snapshot 10

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.
  • Java EE security is an expansive topic that spans well beyond the scope of this tutorial unit. In order to fully appreciate the range of implementation options that are available to you, refer to the Java EE 6 Tutorial, Part VII: Security. This unit provides ample references to relevant sub-sections within the Java EE Tutorial.

Examining the Project Snapshot

The beginning state of the snapshot helps to illustrate the need for security in the application.

  1. Open the project snapshot for this tutorial unit in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project.
  2. Run the project ( Run Project button ) to ensure that it is properly configured with your database and application server.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.

  3. Test the application's functionality in your browser. This snapshot provides an implementation of the administration console, as specified in the customer requirements. To examine the administration console, enter the following URL in your browser:
    http://localhost:8080/AffableBean/admin/
    AffableBean administration console displayed in a browser
    The administration console enables you to view all customers and orders contained in the database. When you click either of the links in the left panel, the page will update to display a table listing customers or orders, depending on your choice. (The 'log out' link currently does not "log out" an authenticated user.)

    Note: The customers and orders that you see displayed in the administration console are dependent on the data stored in your database. You can create new records by stepping through the checkout process in the website. Alternatively, you can run the affablebean_sample_data.sql script on your affablebean database to have your data correspond to the records displayed in the following screenshots. (If you need help with this task, refer to step 2 in the setup instructions.)


    AffableBean administration console displaying all customer records
    You can view details for each customer record by hovering your mouse and selecting an individual record.
    Customer record selected in administration console
    Likewise, you can view an order summary for each customer either by selecting an order from the administration console's "orders" table, or by clicking the "view order summary" link in a "customer details" display.
    'view order summary' link being hovered over in a 'customer details' view
    Naturally, none of this information should be available to an anonymous site visitor. In the coming steps, you'll create login and error pages, so that when an unauthenticated user attempts to access the administration console, he or she will be directed to the login page. Upon successful login, the user is then redirected to the administration console's menu; upon login failure, the error page is displayed.
  4. Examine the project snapshot in the Projects window.
    Projects window displaying resources for administration console

    This implementation of the administration console primarily relies on the following project resources:

    • An admin directory within the project's webroot, which contains all page view files.
    • An AdminServlet, contained in the controller package, which forwards requests to page views within the admin directory.

    Also, the following files have been modified from the previous snapshot:

    • WEB-INF/web.xml: Contains a new <jsp-property-group> that includes the header and footer fragments for page views contained in the admin directory.
    • css/affablebean.css: Includes new style definitions for elements in the administration console

    If you have been following the NetBeans E-commerce Tutorial sequentially, you'll find that there is nothing contained in the implementation for the administration console which hasn't already been covered in previous units. Essentially, the AdminServlet processes requests from the admin/index.jsp page, EJBs and entity classes are employed to retrieve information from the database, and the information is then forwarded back to the admin/index.jsp page to be displayed.

  5. In the browser, return to the customer website by clicking the Affable Bean logo in the upper left corner of the web page. Step through the entire business process flow of the application and note that the checkout process is handled over a non-secure channel.

    When customers reach the checkout page, they are expected to submit sensitive personal information in order to complete their orders. Part of your task in this tutorial unit is to ensure that this data is sent over a secure channel. Because the administration console also enables authenticated users to view customers' personal information, it too needs to be configured so that data is sent over the Internet securely.

Setting up Form-Based Authentication

In this section, you set up form-based authentication for the AffableBean administration console. Form-based authentication enables the server to authenticate users based on the credentials they enter into a login form. With these credentials, the server is able to make a decision on whether to grant the user access to protected resources. In order to implement this, you'll create login and error pages, and will rely on declarative security by entering security settings in the application's web.xml deployment descriptor.

Before you begin implementing a form-based authentication mechanism for the AffableBean application, the following background information is provided to help clarify the security terms relevant to our scenario.

Declarative and Programmatic Security

With declarative security, you specify all security settings for your application, including authentication requirements, access control, and security roles, using annotations and/or deployment descriptors. In other words, the security for your application is in a form that is external to the application, and relies on the mechanisms provided by the Java EE container for its management.

With programmatic security, your classes, entities, servlets, and page views manage security themselves. In this case, security logic is integrated directly into your application, and is used to handle authentication and authorization, and ensure that data is sent over a secure network protocol when necessary.

For the AffableBean application, we'll use declarative security by declaring all security information in the web.xml deployment descriptor.

For more information on declarative and programmatic security types, see the Java EE 6 Tutorial: Overview of Web Application Security.

Choosing an Authentication Mechanism

An authentication mechanism is used to determine how a user gains access to restricted content. The Java EE platform supports various authentication mechanisms, such as HTTP basic authentication, form-based authentication, and client authentication. The authentication mechanism behind our login form will be form-based authentication. You'll learn what form-based authentication is when you begin setting up the login form for the AffableBean administration console below.

See the Java EE 6 Tutorial: Specifying Authentication Mechanisms for further information.


Form-based authentication has the advantage of enabling the developer to design the appearance of the login form so that it better suits the application which it belongs to. Our implementation for the form-based authentication mechanism can be divided into two steps. Begin by creating page views for the required login form and error message. Then add entries to the web.xml deployment descriptor to inform the servlet container that the application requires form-based authentication for access to the resources that comprise the administration console.

  1. Create Pages for Login and Login Failure
  2. Add Security Entries to the Deployment Descriptor

Create Pages for Login and Login Failure

In form-based authentication, the process of authentication and authorization is shown in the following four steps:

  1. The client sends a request to the server for a protected resource.
  2. The server recognizes that a protected resource has been requested, and returns the login page to the client.
  3. The client sends username and password credentials using the provided form.
  4. The server processes the credentials, and if an authorized user is identified the protected resource is returned, otherwise the error page is returned.
Diagram depicting process flow of form-based authentication

For more information on form-based authentication, see the Java EE 6 Tutorial: Form-Based Authentication.


The j_security_check keyword represents the destination in the servlet container that handles authentication and authorization. When implementing the HTML login form, you apply it as the value for the form's action attribute. You also apply the "j_username" and "j_password" keywords, as in the following template:

<form action="j_security_check" method=post>

    <p>username: <input type="text" name="j_username"></p>

    <p>password: <input type="password" name="j_password"></p>

    <p><input type="submit" value="submit"></p>
</form>

Perform the following steps.

  1. In the Projects window, right-click the admin folder node and choose New > JSP.
  2. Name the file login, then click Finish. The new login.jsp file is created and opens in the editor.
  3. Repeat the previous two steps to create a new error.jsp file. In the New JSP wizard, name the file error. When you finish, you'll have two new files listed in the Projects window.
    New login and error JSP files displayed in Projects window
  4. Open the project's web deployment descriptor. Press Alt-Shift-O (Ctrl-Shift-O on Mac) and in the Go to File dialog, type 'web', then click OK.
    Go to File dialog
  5. In the editor, scroll to the bottom of the web.xml file and note the <jsp-property-group> entry created for JSP pages in the administration console. Add the new login and error JSP pages as <url-pattern> entries. (Changes in bold.)
    <jsp-property-group>
        <description>JSP configuration for the admin console</description>
        <url-pattern>/admin/index.jsp</url-pattern>
        <url-pattern>/admin/login.jsp</url-pattern>
        <url-pattern>/admin/error.jsp</url-pattern>
        <include-prelude>/admin/jspf/header.jspf</include-prelude>
        <include-coda>/admin/jspf/footer.jspf</include-coda>
    </jsp-property-group>
    This step ensures that when these two pages are returned to a client, they will be prepended and appended with the defined header.jspf and footer.jspf fragments, respectively.

    You can equally configure the <jsp-property-group> entry from the web.xml's visual editor. Click the Pages tab along the top of the editor, and enter the URL patterns into the respective JSP Property Group.

  6. Press Ctrl-Tab to switch to the login.jsp file in the editor. Delete the entire template contents for the file, then enter the following HTML form.
    <form action="j_security_check" method=post>
        <div id="loginBox">
            <p><strong>username:</strong>
                <input type="text" size="20" name="j_username"></p>
    
            <p><strong>password:</strong>
                <input type="password" size="20" name="j_password"></p>
    
            <p><input type="submit" value="submit"></p>
        </div>
    </form>
    Note that the HTML form is based on the template provided above. Here, you use the "j_security_check" keyword as the value for the form's action attribute, and the "j_username" and "j_password" keywords as the values for the name attribute of the username and password text fields. The style of the form is implemented by encapsulating the form widgets within a <div> element, then defining a set of rules for the loginBox ID in affablebean.css.
  7. Press Ctrl-Tab and switch to the error.jsp file in the editor. Delete the entire template contents for the file, then enter the following.
    <div id="loginBox">
    
        <p class="error">Invalid username or password.</p>
    
        <p>Return to <strong><a href="login.jsp">admin login</a></strong>.</p>
    
    </div>
    The above content includes a simple message indicating that login has failed, and provides a link that allows the user to return to the login form.

Add Security Entries to the Deployment Descriptor

In order to instruct the servlet container that form-based authentication is to be used, you add entries to the web.xml deployment descriptor. This is essentially a three-step process, which can be followed by specifying settings under the three headings in the web.xml file's Security tab. These are: (1) Login Configuration, (2) Security Roles, and (3) Security Constraints.

  1. Open the project's web.xml file in the editor. (If it is already opened, you can press Ctrl-Tab and select it.)
  2. Click the Security tab along the top of the editor. The IDE's visual editor enables you to specify security settings under the Security tab.
  3. Expand the Login Configuration heading, select Form, then enter the following details:
    • Form Login Page: /admin/login.jsp
    • Form Error Page: /admin/error.jsp
    • Realm Name: file
    Visual editor for web.xml - Security tab
  4. Click the XML tab along the top of the editor and verify the changes made to the deployment descriptor. The following entry has been added to the bottom of the file:
    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>file</realm-name>
        <form-login-config>
            <form-login-page>/admin/login.jsp</form-login-page>
            <form-error-page>/admin/error.jsp</form-error-page>
        </form-login-config>
    </login-config>
    This entry informs the servlet container that form-based authentication is used, the realm named file should be checked for user credentials, and specifies the whereabouts of the login and error pages.
  5. Click the Security tab again, then expand the Security Roles heading and click Add.
  6. In the Add Security Role dialog, type in affableBeanAdmin for the role name, then click OK. The new role entry is added beneath Security Roles.
  7. Click the XML tab to examine how the file has been affected. Note that the following entry has been added:
    <security-role>
        <description/>
        <role-name>affableBeanAdmin</role-name>
    </security-role>
    Here we've specified the name of a security role used with the application. We'll need to associate this role with the protected resources that define the administration console (under the Security Constraints heading below), and later we'll create this role on the GlassFish server.
  8. Click the Security tab again, then click the Add Security Constraint button.
  9. Type in Admin for the Display Name, then under Web Resource Collection click the Add button. Enter the following details, then when you are finished, click OK.
    • Resource Name: Affable Bean Administration
    • URL Pattern(s): /admin/*
    • HTTP Method(s): All HTTP Methods
    Add Web Resource dialog
  10. Under the new Admin security constraint, select the Enable Authentication Constraint option and click the Edit button next to the Role Name(s) text field.
  11. In the dialog that displays, select the affableBeanAdmin role in the left column, then click Add. The role is moved to the right column.
    Edit Role Names dialog
  12. Click OK. The role is added to the Role Name(s) text field.
    Visual editor for web.xml - Security tab
  13. Click the XML tab to examine how the file has been affected. Note that the following entry has been added:
    <security-constraint>
        <display-name>Admin</display-name>
        <web-resource-collection>
            <web-resource-name>Affable Bean Administration</web-resource-name>
            <description/>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>affableBeanAdmin</role-name>
        </auth-constraint>
    </security-constraint>
    In these previous six steps, you've created a security constraint that specifies which resources need to be protected, and identifies the role(s) that are granted access to them. Since the administration console implementation is essentially everything contained within the application's admin folder, you use a wildcard (*). Although you've specified that all HTTP methods should be protected, you could have equally selected just GET and POST, since these are the only two that are handled by the AdminServlet. As previously mentioned, the affableBeanAdmin role that we declared still needs to be created on the GlassFish server.
  14. Run the project ( Run Project button ) to examine how the application now handles access to the administration console.
  15. When the application opens in the browser, attempt to access the administration console by entering the following URL into the browser's address bar:
    http://localhost:8080/AffableBean/admin/
    When you attempt to access the administration console, the login page is now presented.
    Browser display of login page
  16. Click the 'submit' button to attempt login. You see the error page displayed.
    Browser display of error page

Setting up Users, Groups and Roles

Much of our security implementation is dependent on configuration between the application and the GlassFish server we are using. This involves setting up users, groups, and roles between the two, and using one of the preconfigured security policy domains, or realms, on the server. Start by reading some background information relevant to our scenario, then proceed by configuring users, groups and roles between the application and the GlassFish server.

Understanding Users, Groups, and Roles

A user is a unique identity recognized by the server. You define users on the server so that it can be able to determine who should have access to protected resources. You can optionally cluster users together into a group, which can be understood as a set of authenticated users. In order to specify which users and/or groups have access to protected resources, you create roles. As stated in the Java EE 6 Tutorial,

A role is an abstract name for the permission to access a particular set of resources in an application. A role can be compared to a key that can open a lock. Many people might have a copy of the key. The lock doesn’t care who you are, only that you have the right key.

The role that a user or group is assigned to is what specifically allows the server to determine whether protected resources can be accessed. Users and groups can be assigned to multiple roles. As will be demonstrated below, you accomplish this by defining the role in the application, then mapping it to users and groups on the server.

The relationship between users, groups, and roles, and the process in which you establish them in the application and on the server, is presented in the following diagram.

Diagram depicting relationship of users, groups and roles between the application and server

For more information on groups, users, and roles, see Working with Realms, Users, Groups, and Roles in the Java EE 6 Tutorial.

Understanding Realms on the GlassFish Server

When you define users and groups on the server, you do so by entering details into a security policy domain, otherwise known as a realm. A realm protects user credentials (e.g., user names and passwords) through an authentication scheme. For example, user credentials can be stored in a local text file, or maintained in a certificate database.

The GlassFish server provides three preconfigured realms by default. These are the file, admin-realm, and certificate realms. Briefly, the file realm stores user credentials in a local text file named keyfile. The admin-realm also stores credentials in a local text file, and is reserved for server administrator users. The certificate realm, the server stores user credentials in a certificate database.

When defining users, groups and roles for the AffableBean administration console, we'll use the server's preconfigured file realm.


In order to set up users, groups and roles to satisfy the form-based authentication mechanism we've created, perform the following three steps corresponding to the diagram above.

  1. Create Users and/or Groups on the Server
  2. Define Roles in the Application
  3. Map Roles to Users and/or Groups

Create Users and/or Groups on the Server

In this step, we'll use the GlassFish Administration Console to create a user named nbuser within the preexisting file security realm. We'll also assign the new nbuser to a group that we'll create called affableBeanAdmin.

  1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node so that the GlassFish server node is visible.
  2. Ensure that the GlassFish server is running. If the server is running, a small green arrow is displayed next to the GlassFish icon ( GlassFish server node in Services window ). If you need to start it, right-click the server node and choose Start.
  3. Right-click the GlassFish server node and choose View Admin Console. The login form for the GlassFish Administration Console opens in a browser.
  4. Log into the Administration Console by typing admin / adminadmin for the username / password.
  5. In the Tree which displays in the left column of the Administration Console, expand the Configuration > Security > Realms nodes, then click the file realm.
    Tree displayed in GlassFish Administration Console
  6. In the main panel of the GlassFish Administration Console, under Edit Realm, click the Manage Users button.
  7. Under File Users, click the New button.
  8. Under New File Realm User, enter the following details:
    • User ID: nbuser
    • Group List: affableBeanAdmin
    • New Password: secret
    • Confirm New Password: secret
    New File Realm User panel in GlassFish Administration Console
    Here, we are creating a user for the file security realm, which we've randomly named nbuser. We have also assigned the new user to a randomly named affableBeanAdmin group. Remember the secret password you set, as you will require it to later log into the AffableBean administration console.
  9. Click OK. The new nbuser user is now listed under File Users in the GlassFish Administration Console.
    File Users panel displaying newly created user and group
    Optionally close the browser window for the GlassFish Administration Console, or leave it open for the time being. You will need to return to the Administration Console in the Map Roles to Users and/or Groups step below.

Define Roles in the Application

By "defining roles in the application," you specify which roles have access to EJB session beans, servlets, and/or specific methods that they contain. You can accomplish this declaratively by creating entries in the deployment descriptor, or using annotations. For the AffableBean administration console, we've actually already completed this step when we added the affableBeanAdmin role to the security constraint that we created when implementing form-based authentication. However, in more complicated scenarios you may have multiple roles, each with varying degrees of access. In such cases, implementation requires a more fine-grained access control.

The Java EE 6 API includes various security annotations that you can use in place of the XML entries you add to deployment descriptors. The availability of annotations primarily aims to offer ease of development and flexibility when coding. One common method is to use annotations within classes, but override them when necessary using deployment descriptors.

Using Security Annotations in Servlets

The following table lists some of the annotations available to you when applying roles to servlets.

Servlet 3.0 Security Annotations (specified in JSR 315)
@ServletSecurity Used to specify security constraints to be enforced by a Servlet container on HTTP protocol messages.
@HttpConstraint Used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods.

If we wanted to apply the Servlet 3.0 annotations to declare the affableBeanAdmin role on the AdminServlet, we could do so as follows. (Changes in bold.)

@WebServlet(name = "AdminServlet",
            urlPatterns = {"/admin/",
                           "/admin/viewOrders",
                           "/admin/viewCustomers",
                           "/admin/customerRecord",
                           "/admin/orderRecord",
                           "/admin/logout"})
@ServletSecurity( @HttpConstraint(rolesAllowed = {"affableBeanAdmin"}) )
public class AdminServlet extends HttpServlet { ... }

In this case, we could then remove the corresponding entry in the web.xml deployment descriptor. (Removed content displayed as strike-through text.)

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>file</realm-name>
    <form-login-config>
        <form-login-page>/admin/login.jsp</form-login-page>
        <form-error-page>/admin/error.jsp</form-error-page>
    </form-login-config>
</login-config>

<security-constraint>
    <display-name>Admin</display-name>
    <web-resource-collection>
        <web-resource-name>Affable Bean Administration</web-resource-name>
        <description/>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <description/>
        <role-name>affableBeanAdmin</role-name>
    </auth-constraint>
</security-constraint>

<security-role>
    <description/>
    <role-name>affableBeanAdmin</role-name>
</security-role>

Using Security Annotations in EJBs

The following table lists some of the annotations available to you when applying roles to EJBs.

EJB Security Annotations (specified in JSR 250)
@DeclareRoles Used by application to declare roles. It can be specified on a class.
@RolesAllowed Specifies the list of roles permitted to access method(s) in an application.

To demonstrate the use of EJB security annotations, we'll apply the @RolesAllowed annotation to a method that should only be called when a user has been identified as belonging to the affableBeanAdmin role.

  1. Reexamine the snapshot implementation for the AffableBean administration console. Note that in the CustomerOrderFacade session bean, a new findByCustomer method enables the AdminServlet to access a specified Customer.
  2. Open the CustomerOrderFacade bean in the editor, then add the @RolesAllowed annotation to the findByCustomer method.
    @RolesAllowed("affableBeanAdmin")
    public CustomerOrder findByCustomer(Object customer) { ... }
  3. Press Ctrl-Shift-I (⌘-Shift-I on Mac) to fix imports. An import statement for javax.annotation.security.RolesAllowed is added to the top of the class.

    The findByCustomer method is only called by the AdminServlet, which is previously authenticated into the affableBeanAdmin role using our implementation of form-based authentication. The use of the @RolesAllowed annotation here is not strictly necessary - its application simply guarantees that the method can only be called by a user who has been authenticated in the affableBeanAdmin role.

Map Roles to Users and/or Groups

We have so far accomplished the following:

  • Defined the affableBeanAdmin role for our form-based authentication mechanism (either in the web.xml deployment descriptor, or as an annotation in the AdminServlet).
  • Created a user named nbuser on the GlassFish server, and associated it with a group named affableBeanAdmin.

It is no coincidence that the group and role names are the same. While it is not necessary that these names be identical, this makes sense if we are only creating one-to-one matching between roles and groups. In more complicated scenarios, you can map users and groups to multiple roles providing access to different resources. In such cases, you would give unique names to groups and roles.

In order to map the affableBeanAdmin role to the affableBeanAdmin group, you have a choice of performing one of two actions. You can either create a <security-role-mapping> entry in GlassFish' sun-web.xml deployment descriptor. (In the Projects window, sun-web.xml is located within the project's Configuration Files). This would look as follows:

<security-role-mapping>
    <role-name>affableBeanAdmin</role-name>
    <group-name>affableBeanAdmin</group-name>
</security-role-mapping>

This action explicitly maps the affableBeanAdmin role to the affableBeanAdmin group. Otherwise, you can enable GlassFish' Default Principal To Role Mapping service so that roles are automatically assigned to groups of the same name.

The following steps demonstrate how to enable the Default Principal To Role Mapping service in the GlassFish Administration Console.

  1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node so that the GlassFish server node is visible.
  2. Ensure that the GlassFish server is running. If the server is running, a small green arrow is displayed next to the GlassFish icon ( GlassFish server node in Services window ). If you need to start it, right-click the server node and choose Start.
  3. Right-click the GlassFish server node and choose View Admin Console. The login form for the GlassFish Administration Console opens in a browser.
  4. Log into the Administration Console by typing admin / adminadmin for the username / password.
  5. In the Tree which displays in the left column of the Administration Console, expand the Configuration node, then click the Security node.
  6. In the main panel of the Administration Console, select the Default Principal To Role Mapping option.

    The Java EE 6 Tutorial defines the term principal as, "An entity that can be authenticated by an authentication protocol in a security service that is deployed in an enterprise. A principal is identified by using a principal name and authenticated by using authentication data." See Working with Realms, Users, Groups, and Roles: Some Other Terminology for more information.

  7. Click the Save button.

    At this stage, you have taken the necessary steps to enable you to log into the AffableBean administration console using the nbuser / secret username / password combination that you set earlier.
  8. Run the project ( Run Project button ). When the application opens in the browser, attempt the access the administration console by entering the following URL into the browser's address bar:
    http://localhost:8080/AffableBean/admin/
  9. When the login page displays, enter the username and password you set earlier in the GlassFish Administration Console (nbuser / secret), then click 'submit'.

    Using form-based authentication, the server authenticates the client using the username and password credentials sent from the form. Because the nbuser belongs to the affableBeanAdmin group, and that group is associated with the affableBeanAdmin role, access is granted to the administration console.
  10. Click the 'log out' link provided in the administration console. The nbuser is logged out of the administration console, and you are returned to the login page.

    The AdminServlet handles the '/logout' URL pattern by invalidating the user session:
    // if logout is requested
    if (userPath.equals("/admin/logout")) {
        session = request.getSession();
        session.invalidate();   // terminate session
        response.sendRedirect("/AffableBean/admin/");
        return;
    }
    Calling invalidate() terminates the user session. As a consequence, the authenticated user is dissociated from the active session and would need to login in again in order to access protected resources.

Configuring Secure Data Transport

There are two instances in the AffableBean application that require a secure connection when data is transmitted over the Internet. The first is when a user initiates the checkout process. On the checkout page, a user must fill in his or her personal details to complete an order. This sensitive data must be protected while it is sent to the server. The second instance occurs when a user logs into the administration console, as the console is used to access sensitive data, i.e., customer and order details.

Secure data transport is typically implemented using Transport Layer Security (TLS) or Secure Sockets Layer (SSL). HTTP is applied on top of the TLS/SSL protocol to provide both encrypted communication and secure identification of the server. The combination of HTTP with TLS or SSL results in an HTTPS connection, which can readily be identified in a browser's address bar (e.g., https://).

The GlassFish server has a secure (HTTPS) service enabled by default. This service uses a self-signed digital certificate, which is adequate for development purposes. Your production server however would require a certificate signed by a trusted third-party Certificate Authority (CA), such as VeriSign or Thawte.

You can find the generated certificate in: <gf-install-dir>/glassfish/domains/domain1/config/keystore.jks

Begin this section by verifying that GlassFish' HTTPS service is enabled. Then configure the application so that a secure HTTPS connection is applied to the checkout process and administration console.

Verify HTTPS Support on the Server

  1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node so that the GlassFish server node is visible.
  2. Ensure that the GlassFish server is running. If the server is running, a small green arrow is displayed next to the GlassFish icon ( GlassFish server node in Services window ). If you need to start it, right-click the server node and choose Start.
  3. Switch to your browser and type the following URL into the browser's address bar:
    https://localhost:8181/
    The browser displays a warning, indicating that the server is presenting you with a self-signed certificate. In Firefox for example, the warning looks as follows.
    Firefox warning for self-signed certificates
  4. Enable your browser to accept the self-signed certificate. With Firefox, click the Add Exception button displayed in the warning. The following pane displays, allowing you to view the certificate.
    Firefox window for confirming a security exception
    Click Confirm Security Exception. A secure connection is established on port 8181, and your local development server, GlassFish, is then able to display the following page.
    Browser welcome message for GlassFish webroot

    Aside from the HTTPS protocol displayed in the browser's address bar, Firefox indicates that a secure connection is established with the blue background behind localhost in the address bar. Also, a lock ( Firefox lock icon ) icon displays in the lower right corner of the browser. You can click the lock icon for secure pages to review certificate details.

    The following optional steps demonstrate how you can identify this security support in the GlassFish Administration Console.
  5. Open the GlassFish Administration Console in the browser. (Either type 'http://localhost:4848/' in your browser, or click the 'go to the Administration Console' link in the GlassFish server's welcome page, as displayed in the image above.)
  6. In the Tree which displays in the left column of the Administration Console, expand the Configuration > Network Config nodes, then click the Network Listeners node.

    The main panel displays the three network listeners enabled by default on the GlassFish server. http-listener-2, which has been configured to listen over port 8181, is the network listener used for secure connections.
    Network Listeners panel displayed in GlassFish Administration Console

    For more information on network listeners, see the Oracle GlassFish Server 3.0.1 Administration Guide: About HTTP Network Listeners.

  7. Under the Name column, click the link for http-listener-2. In the main panel, note that the Security checkbox is selected.
    Edit Network Listener panel in GlassFish Administration Console
  8. Click the SSL tab. Note that TLS is selected. In the lower portion of the SSL panel, you see the Cipher Suites that are available for the connection. As stated in the Oracle GlassFish Server 3.0.1 Administration Guide, Chapter 11: Administering System Security,
    A cipher is a cryptographic algorithm used for encryption or decryption. SSL and TLS protocols support a variety of ciphers used to authenticate the server and client to each other, transmit certificates, and establish session keys. Some ciphers are stronger and more secure than others. Clients and servers can support different cipher suites. During a secure connection, the client and the server agree to use the strongest cipher that they both have enabled for communication, so it is usually sufficient to enable all ciphers.
    At this stage, you have an understanding of how the GlassFish server supports secure connections out-of-the-box. Naturally, you could set up your own network listener, have it listen on a port other than 8181, enable SSL 3 instead of TLS (or both), or generate and sign your own digital certificates using Java's keytool management utility. You can find instructions on how to accomplish all of these tasks from the following resources:

Configure Secure Connection in the Application

This example demonstrates how to specify a secure connection using both XML in the web deployment descriptor, as well as Servlet 3.0 annotations directly in a servlet. You begin by creating an <security-constraint> entry in web.xml for the customer checkout process. Then, to create a secure connection for access to the administration console, you specify a TransportGuarantee constraint for the @HttpConstraint annotation in the AdminServlet.

  1. Open the project's web.xml file in the editor. (If it is already opened, you can press Ctrl-Tab and select it.)
  2. Click the Security tab along the top of the editor, then click the Add Security Constraint button.
  3. Type in Checkout for the Display Name, then under Web Resource Collection click the Add button. Enter the following details, then when you are finished, click OK.
    • Resource Name: Checkout
    • URL Pattern(s): /checkout
    • HTTP Method(s): Selected HTTP Methods (GET)
    Add Web Resource dialog

    Note: Recall that the /checkout URL pattern is handled by the ControllerServlet's doGet method, and forwards the user to the checkout page.

  4. Under the new Checkout security constraint, select the Enable User Data Constraint option, then in the Transport Guarantee drop-down, select CONFIDENTIAL.
    Checkout security constraint displayed under Security tab

    When you choose CONFIDENTIAL as a security constraint, you are instructing the server to encrypt data using TLS/SSL so that it cannot be read while in transit. For more information, see the Java EE 6 Tutorial, Specifying a Secure Connection.

  5. Click the XML tab along the top of the editor. Note that the following <security-constraint> entry has been added.
    <security-constraint>
        <display-name>Checkout</display-name>
        <web-resource-collection>
            <web-resource-name>Checkout</web-resource-name>
            <url-pattern>/checkout</url-pattern>
            <http-method>GET</http-method>
        </web-resource-collection>
        <user-data-constraint>
            <description/>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    Configuration for the customer checkout process is now complete. To ensure that a secure connection is applied for access to the administration console, simply specify that any requests handled by the AdminServlet are transmitted over a secure channel.
  6. Open the AdminServlet. Press Alt-Shift-O (Ctrl-Shift-O on Mac) and in the Go to File dialog, type 'admin', then click OK.
  7. Use the @HttpConstraint annotation's transportGuarantee element to specify a CONFIDENTIAL security constraint. Make the following change (in bold).
    @WebServlet(name = "AdminServlet",
                urlPatterns = {"/admin/",
                               "/admin/viewOrders",
                               "/admin/viewCustomers",
                               "/admin/customerRecord",
                               "/admin/orderRecord",
                               "/admin/logout"})
    @ServletSecurity(
        @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL,
                        rolesAllowed = {"affableBeanAdmin"})
    )
    public class AdminServlet extends HttpServlet { ... }
  8. Press Ctrl-Shift-I (⌘-Shift-I on Mac) to fix imports. An import statement for javax.servlet.annotation.ServletSecurity.TransportGuarantee is added to the top of the class.
  9. Run the project ( Run Project button ) to examine the application's behavior in a browser.
  10. In the browser, step through the AffableBean website by selecting a product category and adding several items to your shopping cart. Then click the 'proceed to checkout' button. The website now automatically switches to a secure channel when presenting the checkout page. You see the HTTPS protocol displayed in the browser's address bar, and the port is changed to 8181.
    Browser address bar showing HTTPS protocol for checkout request
    Also, in Firefox, note the lock ( Firefox lock icon ) icon displayed in the lower right corner of the browser.
  11. Investigate security for the administration console. Type in the following URL into the browser's address bar:
    http://localhost:8080/AffableBean/admin/
    The website now automatically switches to a secure channel when presenting the checkout page. You see the HTTPS protocol displayed in the browser's address bar, and the port is changed to 8181.
    Browser address bar showing HTTPS protocol for checkout request

    Note: You way wonder at this point how it is possible to switch from a secure connection back to a normal, unsecured one. This practice however is not recommended. The Java EE 6 Tutorial explains as follows:

    If you are using sessions, after you switch to SSL you should never accept any further requests for that session that are non-SSL. For example, a shopping site might not use SSL until the checkout page, and then it might switch to using SSL to accept your card number. After switching to SSL, you should stop listening to non-SSL requests for this session. The reason for this practice is that the session ID itself was not encrypted on the earlier communications. This is not so bad when you’re only doing your shopping, but after the credit card information is stored in the session, you don’t want a bad guy trying to fake the purchase transaction against your credit card. This practice could be easily implemented using a filter.

You have now successfully secured the AffableBean application according to the defined customer requirements. You've set up a login form for the administration console to authorize or deny access based on user credentials, and you configured the application and server to create a secure connection for access to the administration console, as well as the customer checkout process.

You can compare your work with the completed AffableBean project. The completed project includes the security implementation demonstrated in this unit, and also provides a basic implementation for web page error customization, such as when a request for a nonexistent resource is made, and the server returns an HTTP 404 'Not Found' error message.

Browser address bar showing HTTPS protocol for checkout request


See Also





The NetBeans E-commerce Tutorial - Testing and Profiling

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

Before delivering any application, it is important to ensure that it functions properly, and that it can perform acceptably for the demands expected of it. Web applications, especially e-commerce applications, by their very nature provide concurrent access to shared resources. In other words, the servers on which they are hosted must be able to respond to multiple users requesting the same resources over the same period of time. Be mindful of this fact when during development your application appears to behave correctly as you click through web pages in your browser. How will the application perform when handling 100 users simultaneously? Are there memory leaks that will degrade the server's performance after the application has been running for long periods of time? What steps can you take to ensure that your production server best handles traffic to your application?

This tutorial unit is designed to introduce you to the IDE's support for testing and profiling. You begin by installing the JMeter Kit plugin, which enables you to create test plans and open them in Apache JMeter from the IDE. You then create a basic test plan in JMeter, and proceed by exploring the tool's capacity for functional and performance testing. Finally, you explore the IDE's Profiler, and use it to examine GlassFish' memory consumption while you run the JMeter test plan against the AffableBean application over an extended period of time. This unit concludes by presenting various tips that enable you to tune the GlassFish server for your application in a production environment.

You can view a live demo of the application that you build in this tutorial: NetBeans E-commerce Tutorial Demo Application.



Software or Resource Version Required
NetBeans IDE Java bundle, 6.8 or 6.9
Java Development Kit (JDK) version 6
GlassFish server v3 or Open Source Edition 3.0.1
JMeter 2.2 or more recent
MySQL database server version 5.1
AffableBean project complete version

Notes:

  • The NetBeans IDE requires the Java Development Kit (JDK) to run properly. If you do not have any of the resources listed above, the JDK should be the first item that you download and install.
  • The NetBeans IDE Java Bundle includes Java Web and EE technologies, which are required for the application you build in this tutorial.
  • The NetBeans IDE Java Bundle also includes the GlassFish server, which you require for this tutorial. You could download the GlassFish server independently, but the version provided with the NetBeans download has the added benefit of being automatically registered with the IDE.
  • You can follow this tutorial unit without having completed previous units. To do so, see the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL.
  • You do not need to download JMeter for its use in this tutorial. Instead, you install the NetBeans JMeter Kit plugin, which includes the JMeter distribution. You will therefore require an Internet connection at the point when you install the plugin in the tutorial. JMeter can be downloaded independently from http://jakarta.apache.org/site/downloads/downloads_jmeter.cgi.
  • The JMeter Kit plugin for NetBeans 6.8 installs JMeter version 2.2 (released June 2006). The plugin for NetBeans 6.9 installs JMeter version 2.4 (released July 2010). There is a significant difference between these two versions.

Testing with JMeter

Begin by examining the AffableBean tutorial application. Then install the JMeter Kit plugin using the IDE's Plugins Manager. Launch JMeter from the IDE, and proceed by creating a test plan based on the tutorial use-case. Finally, explore some of JMeter's facilities for functional and load testing.

Install the JMeter Kit Plugin

  1. Open the AffableBean project in the IDE. Click the Open Project ( Open Project button ) button and use the wizard to navigate to the location on your computer where you downloaded the project.
  2. Run the project ( Run Project button ) to ensure that it is properly configured with your database and application server.

    If you receive an error when running the project, revisit the setup instructions, which describe how to prepare the database and establish connectivity between the IDE, GlassFish, and MySQL. If you want to log into the project's administration console (not required in this tutorial unit), you'll need to create a user named nbuser on the GlassFish server. This task is described in Unit 11, Securing the Application: Create Users and/or Groups on the Server.

  3. Open the IDE's Plugins Manager by choosing Tools > Plugins from the main menu. Select the Available Plugins tab, then type in 'jmeter' into the Search field. When you see JMeter Kit displayed from the filtered results, select it by clicking the checkbox under the Install column.
    JMeter Kit displayed under Available Plugins in the Plugins Manager
  4. Click Install. The IDE's installer informs you that two plugins will be installed: The JMeter Kit and the Load Generator, which provides a generic infrastructure for load generator engines registered in the IDE.
    JMeter Kit and Load Generator listed in the IDE's Plugin Installer
  5. Click Next. Accept the license agreement, then click Install.

    You require an Internet connection to download the selected plugins.

    The installer downloads, verifies, and installs the plugins. When installation has successfully completed, click Finish to exit the installer, then click Close to close the Plugins Manager.
  6. In the Projects window, note that a new Load Generator Scripts node displays in your project.
    Projects window displaying Load Generator Scripts node
    If you open the Files window (Ctrl-2; ⌘-2 on Mac), you'll see a new jmeter folder added to the project. (Recall that the Files window provides a directory-based view of projects, i.e., it displays the folder structure of projects as they exist on your computer's file system.) The jmeter folder corresponds to the Project window's Load Generator Scripts node, and will contain any load scripts that you later add to the project.

Create a Test Plan

To demonstrate how to create a test plan in JMeter, we'll base our plan on the tutorial use-case, which was presented in Designing the Application. A list of user-initiated requests to the server, based on the given use-case, might look something like the following:

Use-Case Server Request
Customer visits the welcome page... /AffableBean/
...and selects a product category. /AffableBean/category
Customer browses products within the selected category page, then adds a product to his or her shopping cart. /AffableBean/addToCart
Customer continues shopping and selects a different category. /AffableBean/category
Customer adds several products from this category to shopping cart. /AffableBean/addToCart
/AffableBean/addToCart
Customer selects 'view cart' option... /AffableBean/viewCart
...and updates quantities for cart products in the cart page. /AffableBean/updateCart
Customer verifies shopping cart contents and proceeds to checkout. /AffableBean/checkout
In the checkout page, customer views the cost of the order and other information, fills in personal data, then submits his or her details. /AffableBean/purchase
The order is processed and customer is taken to a confirmation page. The confirmation page provides a unique reference number for tracking the customer order, as well as a summary of the order. (n/a)

Let's proceed by creating a JMeter test plan that follows the above list of requests.

  1. Click the New File ( New File button ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
  2. Under Categories, select Load Testing Scripts.

    Instead of scrolling to the bottom of the list, simply begin typing 'load'. As shown in the image below, the Load Testing Scripts category displays.
    Load Generator Scripts category displayed in File wizard

  3. Expand the Load Testing Scripts category and select JMeter Plans. Under File Types, select New JMeter Plan, then click Next.
  4. Name the plan useCaseTest, then click Finish. The new test plan displays in the Projects window.
    New 'useCaseTest' test plan displayed in Projects window
  5. To begin customizing the plan in JMeter, right-click the useCaseTest.jmx node and choose External Edit. JMeter opens.
    NetBeans template plan displayed in JMeter

    Note: The NetBeans template plan includes various user-defined variables, as shown in the above image. Usage of several of these variables will become clear as we work with the test plan. For more information, see the Apache JMeter User's Manual: 18.4.13 User Defined Variables.

  6. Click the HTTP Request Defaults node in the left column. The HTTP Request Defaults panel enables you to set default values for all HTTP requests invoked from your test plan. Note that the entries for Server Name and Port Number are ${nb.server} and ${nb.port}, respectively. From the image above, you see that these equate to localhost and 8080, which you typically use when deploying NetBeans projects to GlassFish.
  7. Click the Thread Group node in the left column. In JMeter, a "thread" refers to a user. Let's rename the Thread Group to AffableBean Users. Type 'AffableBean Users' into the Name field under Thread Group.

    Let's begin recording requests for the test plan. To do so, we'll use JMeter's HTTP Proxy Server. Instead of entering test plan requests manually, we'll run the proxy server and have it record requests sent from the browser. For large test plans this technique is invaluable.
  8. In the left column, right-click WorkBench and choose Add > Non-Test Elements > HTTP Proxy Server.
  9. In the HTTP Proxy Server panel, change the port number from 8080 to another, random number, for example 9090. JMeter provides 8080 as its default port number for the proxy server. However, the GlassFish server also occupies the 8080 port, so we're modifying the proxy server's port number to avoid a port conflict.
  10. In the Grouping drop-down list, select 'Put each group in a new controller'. Also, deselect the 'Capture HTTP Headers' option. We do not require header information for each recorded request.
    JMeter HTTP Proxy Server - top panes
    Note that the 'Use Recording Controller' option is selected by default for the Target Controller field. When you begin recording requests, they will be stored in the Recording Controller that is listed in the left column.
  11. Switch to your browser and temporarily change its port number to 9090.

    If you have previously configured your browser's proxy, remember your settings so that you may be able to reenter them after completing this exercise.

    In Firefox, you can do this from the Options window (Preferences window on Mac).
    • Choose Tools > Options (Firefox > Preferences on Mac).
    • Select the Advanced > Network tabs.
    • Under the Connection heading, click Settings.
    • Select the 'Manual proxy configuration' option, then type in localhost and 9090 for the HTTP Proxy and Port fields, respectively.
    • Remove the 127.0.0.1 and localhost entries in the 'No Proxy for' field.
      Firefox Preferences window - proxy settings
    • Click OK.
  12. Clear your browser's cache before you begin recording requests. You want to make sure that the HTTP Proxy Server is able to record all resources required for displaying pages in the Affable Bean website, including images, JavaScript scripts and CSS stylesheets.

    In Firefox, you can do this by pressing Ctrl-Shift-Del (⌘-Shift-Del on Mac) to open the Clear Recent History dialog. Under 'Time range to clear', ensure that you've selected a range that extends to the first time the browser accessed the Affable Bean website. Select Cache, then click Clear Now.
    Firefox Clear Recent History dialog
  13. Return to the JMeter Test Plan panel (shown above) and change the values for nb.users and nb.rampup to 99.
    User-defined variables in JMeter
    The reason this is recommended is that JMeter automatically inserts user-defined variables throughout the test plan, wherever their values occur. So, for example, when the URL for /AffableBean/js/jquery-1.4.2.js is encountered, it will be recorded as: AffableBean/js/jquery-1.4.${nb.users}.js. Later, when we modify the value and rerun the test plan, URLs such as this will also change, which is not desired behavior. Here, we enter a random value (99), since we don't expect it to occur in the URLs that we are about to record.
  14. Return to the HTTP Proxy Server panel, then at the bottom of the panel, click the Start button. JMeter's proxy server is now listening on port 9090.
  15. Run the project ( Run Project button ) from the IDE. The project is deployed to GlassFish, and the welcome page opens in the browser.
  16. Switch to JMeter and inspect the Recording Controller in the left column. All of the requests generated for accessing the welcome page are listed under the Recording Controller in a node named after the first request (i.e., /AffableBean/).
    JMeter - Recording Controller in left column

    If you inspect the /AffableBean/ node, you'll note that it is a Simple Controller. Although dubbed a "Controller", the Simple Controller doesn't offer any functionality beyond enabling you to group elements together - as demonstrated here.

  17. Return to the browser and continue clicking through the website according to the use-case outlined above. You can select any of the categories and products. Stop when you reach the checkout page - the proxy server will not be able to record requests sent over HTTPS.[1]

    The elements within the Recording Controller will look as follows.
    JMeter - Recording Controller in left column
  18. Stop the proxy server. Click the Stop button in JMeter's HTTP Proxy Server panel.
  19. In your browser, change the proxy configuration so that it no longer uses port 9090. In Firefox for example, return to the proxy configuration window (displayed above) and select No Proxy.
  20. Manually create the request for /AffableBean/purchase. Perform the following steps:
    1. Click the Simple Controller in JMeter's left column, then press Ctrl-X (⌘-X on Mac) to cut the element.
    2. Click the Recording Controller, then press press Ctrl-V (⌘-V on Mac) to paste the element. The Simple Controller now displays beneath the /AffableBean/checkout request.
    3. Click the Simple Controller node, then in its main panel rename the controller to /AffableBean/purchase.
    4. Right-click the new /AffableBean/purchase node and choose Add > Sampler > HTTP Request.
    5. Click the new HTTP Request node, then in its main panel configure it as follows:
      • Name: /AffableBean/purchase
      • Server Name or IP: ${nb.server}
      • Port Number: 8181
      • Protocol: https
      • Method: POST
      • Path: /AffableBean/purchase
    6. Under 'Send Parameters With the Request', click the Add button and create the following entries:
      Name Value Encode? Include Equals?
      name Benjamin Linus
      email
      phone 222756448
      address DruĹľstevnĂ­ 77
      cityRegion 4
      creditcard 4444222233331111
    JMeter - HTTP Request panel
  21. Now, add an HTTP Cookie Manager to the test plan. Right-click the AffableBean Users thread group node in JMeter's left column, then choose Add > Config Element > HTTP Cookie Manager.

    Recall that the AffableBean application relies on a session-tracking mechanism (i.e., cookies or URL-rewriting) to remember which shopping cart belongs to which request. Therefore, we need to account for this in the test plan. JMeter acts as the client when sending requests to the server, however unlike a browser, it doesn't have cookies "enabled by default." We apply the HTTP Cookie Manager to the thread group so that the JSESSIONID cookie can be passed between client and server.

    Note: If you want to employ URL rewriting as the session-tracking mechanism, you would need to add the HTTP URL Re-writing Modifier to the thread group.

  22. Finally, add an element to the test plan that simulates a delay between user-initiated requests.
    1. Right-click the /AffableBean/ Simple Controller in the left column and choose Add > Sampler > Test Action.
    2. In the main panel, specify the following:
      • Name: user delay
      • Duration (milliseconds): ${nb.interleave}
      JMeter - Test Action panel
    3. In JMeter's left column, copy (Ctrl-C; ⌘-C on Mac) the new user delay Test Action node, then paste it (Ctrl-V; ⌘-V on Mac) into each of the other Simple Controllers ( Simple Controller icon ) that form the test plan, except for the final one (/AffableBean/purchase).

      When you finish, the final six Simple Controllers and their contents will look as follows.
      Test Action nodes shown in JMeter left column
  23. (Optional.) Clean up the test plan. You can remove the Loop Controller and Constant Timer. (Right-click and choose Remove.) Also, move all of the Recording Controller's child elements directly into the AffableBean Users thread group, then remove the Recording Controller. When you finish, the test plan will look as follows.
    Test plan displayed in JMeter left column

Load Testing

Load testing a web application involves making concurrent requests for resources, typically by simulating multiple users, and then examining the server's behavior. We can use the test plan we created for this purpose, and make adjustments to the number of users and other settings to determine how the server behaves under the given work load.

Load testing should be performed with specific goals in mind, such as determining the throughput for the anticipated average and peak numbers of users. It is also worthwhile to assess the response time for requests, to ensure that site customers are not having to wait too long to be served. In order to measure the response time, you need to take into account the time during which data spends traveling over the Internet. One way to do this is to compare test results between a local server, where network travel time is nearly non-existent, and results from testing the production server remotely. The following example demonstrates how you can perform tests using your local development server. Once you migrate an application to the production server, you can simply change the value for the server variable set under the test plan's User Defined Variables.

The results recorded in this and the following sections were arrived at by running tests on a computer with a 2.4 GHz Intel Core 2 Duo processor and 4 GB of memory. Naturally, the results you get depend on your computer's performance, and will likely not match those displayed here.

When you run load tests, you should be careful not to overload your computer. If you set too many threads (i.e., users), do not place adequate delay between individual requests, or continuously loop through the test plan, there is a chance that JMeter will expend your computer’s processing capacity or memory. JMeter will then become unresponsive and you may need to "force quit" the tool using your computer's task manager. It is therefore recommended that you open the task manager in order to monitor the computer's CPU and memory levels while the test is running. This will allow you to gauge the limits of your computer in terms of running the test plan.

  1. Open JMeter if it is not already opened. (In the IDE's Projects window, right-click useCaseTest.jmx and choose External Edit.)

    Note: If you did not create the JMeter test plan in the previous sub-section, you can download the complete useCaseTest.jmx file and add it to your project. To add it to the AffableBean project, copy it from your computer's file system (Ctrl-C; ⌘-C on Mac), then in the IDE, open the Files window (Ctrl-2; ⌘-2 on Mac), right-click the jmeter folder and choose Paste.

  2. Add several listeners to the test plan:
    • Right-click AffableBean Users and choose Add > Listener > Summary Report.
    • Right-click AffableBean Users and choose Add > Listener > View Results Tree.
    • Right-click AffableBean Users and choose Add > Listener > Graph Results.
    In JMeter, you require a listener to record and display the results of your test plan. The Summary Report displays a table, with each row corresponding to each differently named request in your test. The View Results Tree shows a tree of all sample responses, allowing you to view response details for any sample. The Graph Results listener displays a simple graph that plots all sample times.
  3. Click the JMeter Template Plan node, then make the following changes to User Defined Variables:
    • nb.users: 1
    • nb.interleave: 5000
    We begin the test by simulating just one user. The value for nb.interleave is used in the user delay Test Action that we created, and represents the duration of a pause in milliseconds. Therefore, the test will pause for 5 seconds between each user-initiated request.
  4. Click the Summary Report node so that you are able to view the test results while the test is running.
  5. Run the test plan. Choose Run > Start (Ctrl-R; ⌘-R on Mac) from the main menu.

    The test plan runs for approximately 50 seconds. Note that request samples are taken every three seconds, during which you can watch as results are added and updated. Note that values for the Average, Min, and Max columns are represented in milliseconds.
    JMeter - Summary Report

    From the results displayed in the above image, we can observe that:

    • The server, when loaded with a single user, provides a total throughput of approximately 41 per minute. In other words, the server is capable of serving all requests within the test plan 41 times within a minute. According to the JMeter User's Manual, the throughput is calculated as: (number of requests)/(total time), and includes any delay inserted between samples, as it is supposed to represent the load on the server. When we consider that the user delay occurs for 5 seconds between each request (9 times in total, 9 * 5 seconds = 45 seconds), we see that with the server would theoretically be utilized for only approximately 15 seconds.
    • The AffableBean/checkout request, recorded at 33 milliseconds, takes much longer to process than most other requests. This is likely due to the fact that the initial request is redirected to the HTTP + SSL protocol on port 8181. So there are essentially two requests taking place.
    • The AffableBean/purchase request, recorded at 147 milliseconds, takes the most time to be served. This is likely due to both the write operations required on the database, and the fact that client-server communication takes place over an encrypted channel (i.e., using HTTPS).
    • According to the Error % column, no errors occurred from running the test. In other words, all server responses included an HTTP 200 status.
    • The Avg. Bytes column represents the average size of the sample response. We see that the JQuery core library (jquery-1.4.2.js) is the largest file that is served in the test plan, at nearly 164 KB. Because the file is served each time a new user accesses the site, it may be worth linking to this file on a public content delivery network (CDN) instead of maintaining it on the server. "Unburdening" the server in this manner could have a notable effect on its overall performance.

      For further information, see the official jQuery documentation: CDN Hosted jQuery.

  6. Click the View Results Tree node. Here you see the individual results from each of the sample requests, listed in the order in which they occurred.
    JMeter - View Results Tree
    The green ( success icon ) icons indicate an HTTP status response of 200. In the above image, under 'Sampler result' in the right panel, note that the Thread Name for the selected sample is 'AffableBean Users 1-1'. The second '1' represents the thread (i.e., user) number. When testing multiple threads, you can use View Results Tree listener to pinpoint exactly when each thread makes a request within the test. Finally, in the image above, note that the 'HTML (download embedded resources)' option is selected in the lower left corner. When you select the 'Response data' tab in the right panel, JMeter attempts to render the response as it would display in a browser.

    Note: Red warning ( warning icon ) icons indicate that requests are not being handled properly (i.e., HTTP 404 status messages are being sent). While this begins to happen when a server reaches its performance capacity, 404 status messages under a normal load suggest that the application is not functionally stable. You should then check the server log to determine why requests are failing, and make changes to your application.

    In the coming steps, we'll add an increasing number of users to the test, and examine the server's overall throughput.

  7. Click the JMeter Template Plan node, then make the following changes to User Defined Variables:
    • nb.users: 20
    • nb.rampup: 20
    The nb.rampup variable is used in the AffableBean Users Thread Group panel, and specifies the ramp-up period in seconds. In this case, if we test 20 users and the ramp-up period is 20 seconds, then a new user will begin sending requests every second.
  8. Clear the results from the previous test by choosing Run > Clear All (Ctrl-E; ⌘-E on Mac).
  9. Click the Graph Results node so that you are able to view the test results while the test is running.
  10. Run the test plan. Choose Run > Start (Ctrl-R; ⌘-R on Mac) from the main menu. When the test plan runs, make the following observations:
    • A green square displays in the upper right corner of the interface, indicating that the test plan is running. Adjacent to the square is a ratio listing the number of active threads against the total number of threads being tested. For example, Green square with number of active threads demonstrates that the test is running, and that there are currently 15 active threads of a total of 20. Because of the ramp-up period, you should notice that the number of active threads increases each second to 20, remains at 20 for some time, then gradually decreases to zero, at which the square becomes gray indicating that the test has terminated.
    • You can filter the graphs you wish to display by selecting the checkboxes above the graph. For an explanation of Median and Deviation, refer to the JMeter User's Manual Glossary. The image below displays graphs for Average and Throughput only. The metric values provided at the bottom of the graph apply to the most recent sample.
    • From the green line designating throughput, we see that the server was able to maintain a nearly consistent value as the load increased to 20 users. Toward the end of the test, as user number decreases, we see that the throughput slightly lessens. We can assume that this is simply due to the fact that there are fewer requests per unit of time.
    • While the vertical line of the graph represents time (in milliseconds), this doesn't apply to the throughput measurement (nor the measurement for standard deviation, for that matter). The throughput represents the number of requests the server processes during the total time which the test plan runs. In the image below, note that the throughput value listed at the bottom of the graph is: 577.496/minute. Switching to the Summary Report, the total throughput value is listed as: 9.6/second. The two values equate: 577.496/60 = 9.6.
    • The blue line, designating the average time (in milliseconds), increases dramatically at the end of the test. If you examine the final request samples in the View Results Tree, you can get an idea why. The final samples taken are all /checkout and /purchase requests, which as we've already seen, take much longer than the other requests in the test plan.
    JMeter - Graph Results

Stress Testing

In the tests we've so far conducted, the throughput for a single user was calculated at 41/min, and for 20 users it was 577/min. You can continue to increase the demand on the server to see if it's possible to determine what the maximum throughput value can be, given your local setup. This is an example of stress testing, in which the system resources are purposely worked to their limits in order to arrive at a maximum capacity value.

You can adjust the User Defined Variables, then run the test plan and examine the results. For example, experiment by increasing the number of users, or decreasing the ramp-up period or delay between requests.

Important: When stress testing, you should monitor your computer's CPU and memory levels. If you see that JMeter is not able to record results under a specific load and becomes unresponsive, you can try to stop the test by choosing Run > Stop (Ctrl-.; ⌘-. on Mac). Otherwise, if JMeter does not respond, you may need to kill the JMeter process from your computer's task manager.

The following table lists results recorded in JMeter's Summary Report, from increasing the number of users with each test run.

Users Ramp-up
(seconds)
Average
(milliseconds)
Throughput Error %
1 (n/a) 11 41/min 0.00%
20 20 9 577/min 0.00%
50 25 8 22.2/sec 0.00%
80 25 8 35.3/sec 0.00%
100 25 7 44.1/sec 0.00%
120 25 7 52.9/sec 0.00%
150 25 7 66.0/sec 0.00%
200 25 11 87.5/sec 0.00%
250 25 16 109.5/sec 0.00%
300 25 35 130.1/sec 0.00%
350 25 54 150.4/sec 0.00%
400 25 120 164.3/sec 0.00%
450 25 394 158.4/sec 0.00%
500 25 355 182.9/sec 0.00%
550 25 369 198.4/sec 0.00%
600 25 446 206.4/sec 0.00%
650 25 492 219.9/sec 0.00%
700 25 599 225.9/sec 0.00%
750 25 668 231.9/sec 0.00%
800 25 875 225.6/sec 0.00%
850 25 976 230.5/sec 0.00%
900 25 1258 220.9/sec 0.00%
950 25 1474 215.8/sec 0.00%
1000 25 1966 190.8/sec 0.00%

Notes and observations:

  • Maximum throughput was recorded at 231.9/sec for 750 users. Throughput is generally much quicker for requests in the first part of the test plan, and then decreases as /checkout and /purchase requests are served. Because the elapsed time for these requests begins to dramatically increase beyond 750 users, the overall throughput begins to decrease beyond this number.
  • When testing for 500 users, JMeter became unresponsive and it was necessary to shut it down from the task manager. It is likely that JMeter was running out of memory to record and display results for the Graph Results and View Results Tree listeners. These two listeners were removed from the test plan, and results for 500 - 1000 users were then recorded using the Summary Report listener only.
  • In all tests, the Error % column remained at 0.00%. The server was able to successfully respond to all requests, even when the computer's CPU levels were at a maximum, and JMeter was lagging in its ability to display results. This would indicate that the bottleneck in these tests was the computer's processing resources. (The computer had available memory for all tests.)
  • The Average represents the average elapsed time (in milliseconds) for all requests serviced in the test plan. While the average values for the most demanding tests were still under 2 seconds, the Summary Report's Maximum values recorded for elapsed time were much higher, reaching nearly 70 seconds for the /purchase request. When determining what resources are required for a normal load, consider that these results do not include network time, and that most users are willing to wait at most 4 - 8 seconds for a response.[2]

If the production server is on a machine that has resources similar to those of your development environment, and assuming your computer is not running other CPU-intensive processes while tests are conducted, you can get a rough idea of how many users can be served by examining your computer's CPU usage during tests. For example, if it has been decided that CPU levels for normal and peak loads will be approximately 30% and 70%, respectively, you can watch the CPU monitor as you increase the number of users with each run of the test plan. The following images suggest 150 users could be served during a normal load, and 400 during a peak load.

CPU levels for 150 users CPU levels for 400 users
CPU graph for 150 users CPU graph for 400 users

Keep in mind that when running tests in this manner, your local server is competing with JMeter for the computer's resources. Eventually, you'll want to test your production server remotely to get more accurate results. See the following resources for more information:


Using the NetBeans Profiler

The NetBeans Profiler is an award winning development utility that enables you to profile and monitor your application's CPU and memory usage, and thread status. The Profiler is an integral component of the IDE, and offers a click-of-the-button profiling environment that aids you when handling memory and performance-related issues. For an overview of the Profiler's features, see NetBeans IDE 6.9 Features: Profiler.

When profiling web applications, you can use the Profiler to work in tandem with a load script, such as a test plan created in JMeter. Often, problems start to arise only after your application has been running in a host environment for a certain period of time, and has begun serving multiple concurrent requests. In order to get an idea of how the application will perform before it is migrated to a production environment, you can launch the Profiler, run a test script on the application, and examine the results in the Profiler's interface.

About Memory Leaks

In Java, memory leaks occur when objects continue to be referenced even after they are no longer needed. This prevents Java's built-in garbage collection mechanism from destroying these objects, and consequently they remain in existence throughout the life of your application. When these objects are regularly created, the Java Virtual Machine (JVM) heap will continue to grow over time, ultimately resulting in an OutOfMemoryError when the heap is eventually exhausted.

The JVM heap represents memory that is dynamically allocated by the Virtual Machine during runtime. Because the GlassFish server runs on Java, it relies on the JVM heap for memory resources during execution. All applications that are deployed to the server can be perceived as extensions to this rule; in other words when your web application runs, it consumes resources from the JVM heap.

When building web applications, you need to be mindful of memory allocation. Aside from avoiding memory leaks in your code, you must ensure that the JVM heap is large enough to accommodate all user sessions at a given time, and that your system is able to support the maximum heap size set by your server.

Monitoring your Application

The following example aims to familiarize you with the Profiler's interface, and demonstrates how you can utilize its functionality to ensure that the AffableBean application will continue to perform efficiently after it has been serving client requests for some time. In this example, you download and add a new JMeter test plan, useCaseTestRandom.jmx, to the project. The new test plan is an advanced version of the one you created earlier in this unit. It makes use of JMeter's conditional and random controllers to adapt a slightly more realistic simulation of the tutorial's use-case.

Consider that only a small fraction of visits to an e-commerce site will result in a completed order. If you recall from units 8 and 9, Managing Sessions and Integrating Transactional Business Logic, the application terminates the user session upon a successfully completed order. In other words, with each completed order, the server is able to free up any resources that were previously tied to the session. Now, consider the far more common scenario of a user not completing an order, but simply navigating away from the site. Based on the session time-out which you specified in the application's web deployment descriptor, the server will need to wait a period of time before it can free any resources tied to the session. The new load script, useCaseTestRandom.jmx, is configured so that on average one in ten user threads completes an order. Our goal by running this load script is to determine whether the application's host environment (i.e., the GlassFish server running locally on your computer) has enough memory capacity to provide continuous, fast service for an extended period of time.

Note: Recall that in Managing Sessions: Handling Session Time-Outs, you set the AffableBean session time-out to 10 minutes.

  1. Download useCaseTestRandom.jmx and add it to the AffableBean project. To add it to the project, copy it from your computer's file system (Ctrl-C; ⌘-C on Mac), then in the IDE, open the Files window (Ctrl-2; ⌘-2 on Mac), right-click the jmeter folder and choose Paste.
    JMeter test plans displayed in Files window

    NetBeans 6.8 note: The useCaseTestRandom.jmx script is not compatible with the JMeter Kit plugin for NetBeans 6.8. Because the script utilizes various logic controllers which unfortunately are not available in JMeter version 2.2, it will not run on the JMeter implementation in NetBeans 6.8. In order to become familiar with the Profiler, use useCaseTest.jmx in this exercise instead. If you use useCaseTest.jmx, you need to set the load script to run continuously. To do so, open the script in JMeter, select the AffableBeanUsers thread group, then in the main panel, select the 'Forever' checkbox for the Loop Count field.

  2. If you are running the Profiler for the first time, you need to perform a calibration step on the JDK. To do so, choose Profile > Advanced Commands > Run Profiler Calibration. For more information, refer to the NetBeans User FAQ wiki: What exactly does the Profiler Calibration mean?.
  3. Click the Profile Project ( Profile Project button ) button. When a project is profiled for the first time, its build script must be modified to enable profiling. The IDE warns you that it will modify the project's build script.
    Profiler dialog box warning that build script will be modified

    Note: You can undo this action at a later point by choosing Profile > Advanced Commands > Unintegrate Profiler from the main menu. Alternatively, you can switch to the Files window, delete your project's build.xml file, then rename the build-before-profiler.xml file to build.xml.

  4. Click OK. The project's build file is modified, and the Profiler window opens for the project. The window enables you to select from one of three profiling tasks:
    • Monitor Application: Provides obtain high-level information about properties of the target JVM, including thread activity and memory allocations.
    • Analyze Performance: Provides detailed data on application performance, including the time to execute methods and the number of times the method is invoked.
    • Analyze Memory: Provides detailed data on object allocation and garbage collection.
  5. Click the Monitor button in the left column. Select the 'LoadGenerator Script' option, then choose useTestCaseRandom.jmx from the drop-down list.
    Profiler window - Monitor Application
  6. Click Run. The IDE takes the following actions:
    • Starts the GlassFish server in profile mode. (If the server is already running, it is first stopped.)
    • Deploys the web application to GlassFish.
    • Starts a profiling session, attaches the profiler to the server, and opens the Profiler Control Panel in the IDE.
    • Runs the associated load script (useTestCaseRandom.jmx).

    Note: If the profiler does not run the load script after starting the application in profile mode, you can invoke it yourself. From the Projects window, right-click the script and choose External Edit. Then, in JMeter, press Ctrl-R (⌘-R on Mac) to run the script. If the left-hand graph displayed by the VM Telemetry Overview depicts the purple area as remaining horizontal (shown below), you can be fairly certain that the load script is not running.

    VM Telemetry Overview - JVM Heap
  7. In the Profiler Control Panel, click the Threads ( VM Telemetry button ) button. The Threads window opens to display all threads maintained by the server while the application is running. You can select Live Threads Only, or Finished Threads Only in drop-down at the top of the window in order to filter the display according to live or finished threads.
    Threads window

    You can select the Enable Threads Monitoring option in the Profiler window (displayed above). This will trigger the Threads window to open by default when running the Profiler.

  8. In the Profiler Control Panel, click the VM Telemetry ( VM Telemetry button ) button.

    Similar to the VM Telemetry Overview, the VM Telemetry window provides views on the JVM heap, garbage collection (GC), as well as threads and loaded classes.
  9. Ensure that the Memory (Heap) tab is selected at the bottom of the window, then allow the Profiler to monitor the heap while the load script runs against the application.

    You can hover your cursor over the graph to view real-time measurements of the heap size versus the used heap.
    Popup displaying heap measurements in the Memory (Heap) tab of the VM Telemetry window

    Click the Scale to Fit ( Scale to Fit button ) button above the graph to maintain a continuous view of the entire monitoring session.


    The image below shows the state of the heap after monitoring the server for approximately three hours while running the useTestCaseRandom.jmx script continuously with 150 simultaneous users. The AffableBean application running on the GlassFish server uses under 175 MB of the JVM heap.

Evaluating Heap Contents with the HeapWalker

The HeapWalker is a tool that is built into the NetBeans Profiler, which allows you to examine JVM heap contents. You can use it to browse classes and instances of classes on the heap, fields of each instance or class, and references to each instance.

The HeapWalker is particularly useful when locating the cause of memory leaks in your code. You can set the Profiler to automatically take a heap dump if an OutOfMemoryError occurs when you are profiling an application. You can then use the HeapWalker to inspect the heap dump and determine which objects were consuming the most memory.

This functionality is enabled by default, but you can view and modify Profiler settings from the IDE's Options window (Tools > Options; NetBeans > Preferences on Mac). From the Options window, select Miscellaneous, then select the Profiler tab. In the On OutOfMemoryError field, note that 'Save heap dump to profiled project' option is selected.

Options window - Profiler options

For example, if the GlassFish server utilizes 512 MB of memory, and the JVM attempts to allocate more than 512 MB of memory to the JVM heap (represented by the pink area in the heap size graph of the VM Telemetry monitor, shown above), an OutOfMemoryError will occur, and the IDE will ask you if you would like to view the heap in the HeapWalker.

To take a heap dump while your application is being profiled, choose Profile > Take Heap Dump from the main menu.

Profiler menu

The following example depicts a heap dump from running the useCaseTestRandom.jmx script at 500 users, ramp-up period at 100 seconds, and with a loop count of 5. The HeapWalker's Summary provides an Inspect panel which enables you to locate the largest objects in the heap. Specify the number of objects you want to search for, then click Find.

HeapWalker - Summary - Inspect panel

In the above image, you can see that for the AffableBean application, the largest object in the heap dump is an instance of the org.apache.catalina.session.StandardManager class, with a retained size of nearly 79 MB.

Clicking the object name enables you to open the Instances view on the object. When you do so, you can see the instances of the class that exist on the heap (left column), the fields contained in the class, and their values (right column, top), and other objects on the heap referring to the instance (right column, bottom).

HeapWalker - Instances view

In the above image, it appears that 706 StandardSession objects were active on the heap, a result of the load script simulating multiple user sessions. The server must have sufficient memory resources to maintain session objects during periods of high traffic.

You can save (Ctrl-S; ⌘-S on Mac) heap dumps. When you do so, they become listed in the Profiler Control Panel under Saved Snapshots.

Profiler Control Panel - Saved Snapshots

Tuning the GlassFish Server

In order to gain optimum performance for your application when it is deployed to GlassFish, you should become acquainted with various tuning parameters which can be adjusted from the Administration Console. The following tips are taken directly from the white paper, Optimize GlassFish Performance in a Production Environment. Although the paper focuses on GlassFish v2, the tuning tips can be directly applied to GlassFish v3 or Open Source Edition 3.0.1.

There are various mapping changes that occurred between GlassFish v2 and v3. Tables listing changes are provided on the GlassFish wiki: GrizzlyConfig One Pager.

The GlassFish Administration Console can be accessed from the IDE's Services window:

  1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node so that the GlassFish server node is visible.
  2. Ensure that the GlassFish server is running. If the server is running, a small green arrow is displayed next to the GlassFish icon ( GlassFish server node in Services window ). If you need to start it, right-click the server node and choose Start.
  3. Right-click the GlassFish server node and choose View Admin Console. The login form for the GlassFish Administration Console opens in a browser.
  4. Log into the Administration Console by typing admin / adminadmin for the username / password.

From the GlassFish Administration Console, you can view and make adjustments to the following parameters.

Tip 3: Java Heap Size

From Optimize GlassFish Performance in a Production Environment:

The size of the heap is determined by the Java options -Xmx (maximum) and -Xms (minimum). While a larger heap can contain more objects and reduce the frequency of garbage collection, it may result in longer garbage collection times especially for a full GC cycle. The recommendation is to tune the heap based on the size of total available memory in your system, process data model (32-bit or 64-bit) and operating system.
  1. In the Tree which displays in the left column of the Administration Console, expand the Configuration node, then click JVM Settings.
  2. In the main panel, select the JVM Options tab.
  3. Scroll the list of options and note the -Xmx option:
    -Xmx512m
    The GlassFish server (v3 and Open Source Edition 3.0.1) sets the heap to 512 MB by default. If you wanted to increase the heap size to 1 GB, you would enter '-Xmx1024m', click the Save button in the upper right corner, and then restart the server.

Tip 6: HTTP Request Processing Threads

From the Sun Java System Application Server 9.1 Performance Tuning Guide:

The [Max Thread Pool Size] parameter specifies the maximum number of simultaneous requests the server can handle. The default value is 5. When the server has reached the limit or request threads, it defers processing new requests until the number of active requests drops below the maximum amount. Increasing this value will reduce HTTP response latency times.

In practice, clients frequently connect to the server and then do not complete their requests. In these cases, the server waits a length of time specified by the Idle Thread Timeout parameter.
[900 seconds, i.e., 15 minutes, is the default entry for GlassFish v3 and Open Source Edition 3.0.1.]

Also, some sites do heavyweight transactions that take minutes to complete. Both of these factors add to the maximum simultaneous requests that are required. If your site is processing many requests that take many seconds, you might need to increase the number of maximum simultaneous requests.

Adjust the thread count value based on your load and the length of time for an average request. In general, increase this number if you have idle CPU time and requests that are pending; decrease it if the CPU becomes overloaded. If you have many HTTP 1.0 clients (or HTTP 1.1 clients that disconnect frequently), adjust the timeout value to reduce the time a connection is kept open.

Suitable Request Thread Count values range from 100 to 500, depending on the load. If your system has extra CPU cycles, keep incrementally increasing thread count and monitor performance after each incremental increase. When performance saturates (stops improving), then stop increasing thread count.
  1. In the Administration Console Tree, expand the Configuration node, then click Thread Pools.

    The GlassFish server provides two thread pools by default. The http-thread-pool thread pool is configured for use by network listeners, while thread-pool-1 is configured for use by the ORB (object request broker) for RMI/IIOP requests. (A stand-alone web application deployed over a non-distributed environment, such as the AffableBean application, relies on the http-thread-pool by default.)
  2. Under the Thread Pool ID column, click http-thread-pool.
  3. In the Max Thread Pool Size field, adjust the maximum number of threads available to the thread pool.
  4. Click the Save button in the upper right corner, and then restart the server.

Tip 10: JDBC Tuning

From Optimize GlassFish Performance in a Production Environment:

If your application uses Java DataBase Connectivity (JDBC) software for database access, it may be beneficial to tune your database connection pool. A general rule of thumb is to tune the value for max-pool-size and steady-pool-size to the same number of HTTP request processing threads. If your JDBC driver supports this feature, it is advisable to use JDBC drivers that use statement caching to re-use prepared statements.
  1. In the Administration Console Tree, expand the Resources > JDBC > Connection Pools node, then click the AffableBeanPool node.
  2. In the General tab under Pool Settings, specify values for the following fields:
    • Initial and Minimum Pool Size: (steady-pool-size) Minimum and initial number of connections maintained in the pool.
    • Maximum Pool Size: (max-pool-size) Maximum number of connections that can be created to satisfy client requests.
    • Pool Resize Quantity: (pool-resize-quantity) Number of connections to be removed when pool idle timeout expires.
    • Idle Timeout: (idle-timeout-in-seconds) Maximum time that connection can remain idle in the pool.
    • Max Wait Time: (max-wait-time-in-millis) Amount of time caller waits before connection timeout is sent.
  3. Click the Save button in the upper right corner, and then restart the server.

Connection pool settings can also be specified in the sun-resources.xml descriptor:

<jdbc-connection-pool max-pool-size="32"
                      steady-pool-size="8"
                      pool-resize-quantity="2"
                      idle-timeout-in-seconds="300"
                      max-wait-time-in-millis="60000">
    ...
</jdbc-connection-pool>


See Also


References

  1. ^ Actually, in JMeter version 2.4, using the HTTP Proxy Server to record HTTPS requests should be possible. See the JMeter User's Manual, 2.2.4 SSL Encryption for more details.
  2. ^ The acceptable response time for retail web page response times is debatable, but general concensus seems to waver between 4 and 8 seconds. For example, see:




The NetBeans E-commerce Tutorial - Conclusion

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

Congratulations! You have now finished developing the AffableBean application. By following this tutorial, you incrementally built a simple e-commerce application using Java-based technologies. In the process, you became familiar with the NetBeans IDE, and have learned how to use it for the development of Java EE and web projects. Referring back to the customer requirements, you can confirm that each requirement has been fully implemented, and through continuous feedback from the Affable Bean staff, you are confident that they'll be satisfied with the final product. At this stage however, you may ask, "What specifically needs to be delivered to the customer?" and "How can the application become deployed to the customer's production server so that it functions online?" This tutorial unit briefly discusses next steps in terms of handing off deliverables, and concludes with a discussion on how using a framework such as JavaServer Faces could improve the application and benefit your experience when developing future projects.

You can view a live demo of the AffableBean application: NetBeans E-commerce Tutorial Demo Application.

The completed AffableBean project is also available for download.



Delivering your Work

When delivering your work, you should prepare both a WAR (web archive) file, which is a compiled, ready-to-deploy version of your project, and a source distribution, which contains all the source files you created during the development phase.

  1. WAR File Distribution: A WAR file is basically a compressed collection of classes, files and other artifacts that constitute the web application. You can create a WAR file for your project using the IDE. In the Projects window, right-click your project node and choose Clean and Build. When your project is built, a WAR file is generated and placed in a dist folder in your project. You can verify this by examining your project in the Files window (Ctrl-2; ⌘-2 on Mac). (Refer back to Setting up the Development Environment).
  2. Source Distribution: A package containing all source and configuration files, typically in an archive file format (e.g., ZIP, TAR). You can use your NetBeans project as part of your source distribution. Before compressing your project, make sure to clean it (In the Projects window, right-click the project node and choose Clean) in order to delete build and dist folders, if they exist. You should also remove any of your environment-specific details included in the project. To do so, navigate to the project on your computer's file system, then expand the project's nbproject folder and delete the private folder contained therein. (When the project is opened again in the IDE, the private folder and its files are regenerated according to the current environment.)

    As part of your source distribution, you would need to also provide any scripts or artifacts that are necessary for setup, configuration, and population of the database. In this scenario, that would include the MySQL Workbench project from Unit 4, Designing the Data Model, the DDL script that creates the affablebean database schema, and possibly a separate script that populates the category and product tables with business data.

As was indicated in the tutorial Scenario, a "technically-oriented staff member is able to deploy the application to the production server once it is ready." Aside from necessary performance tuning (GlassFish tuning is discussed in Unit 12 Testing and Profiling) the person responsible for this would need to ensure that the database driver is accessible to the server (i.e., place the driver JAR file in the server's library folder). He or she would also need to know the JNDI name of the data source used by the application to interact with the database. This is found in the persistence unit (persistence.xml file) and, as you may recall, is: jdbc/affablebean. This is the only "link" between the application itself and the back-end database server.

Note: Recall that the sun-resources.xml file, which you created in Unit 6, Connecting the Application to the Database contains entries that instruct the GlassFish server to create the JDBC resource and connection pool when the application is deployed. The sun-resources.xml file is a deployment descriptor specific to the GlassFish server only. Therefore, if the customer isn't using GlassFish as the production server, the file should be deleted before the application is deployed. If the sun-resources.xml file isn't removed from the WAR distribution however, it would simply be ignored by the server it is deployed to.

In terms of security, it would be necessary to set up a user and group on the production server, so that the server can authenticate persons wanting to log into the administration console. Also, SSL support for the production server would need to be enabled, and you would need to acquire a certificate signed by a trusted third-party Certificate Authority (CA), such as VeriSign or Thawte.

Once the database is created and tables are populated with necessary data, the connection pool and JDBC resource are set up on the production server, and security measures have been taken, the application WAR file can be deployed to and launched on the production server. Using GlassFish, it is possible to deploy your applications via the Administration Console. (Select Applications in the left-hand Tree, then click the Deploy button to deploy a new application.)

The GlassFish plugin support in NetBeans also enables you to connect to a remote instance of GlassFish. You can therefore work with a GlassFish production server from the IDE for monitoring, profiling, and debugging tasks. If you are interested in using GlassFish as a production server, refer to the See Also section below for a list of web hosting solutions.

Portability is among the key benefits of Java EE. As your application adheres to the technology specifications, it can theoretically be deployed to any server that supports the same specifications. Recall that the Introduction lists the specifications that you have used in this tutorial. All of these specifications are part of the Java EE 6 platform specification (JSR 316). Therefore, any server that is Java EE 6-compliant would be a candidate for running the AffableBean application.




Using the JavaServer Faces Framework

Having developed a Java web application from scratch puts you in a great position to begin appreciating how a framework can benefit your work. This section briefly introduces the JavaServer Faces (JSF) framework, then examines the advantages of applying the framework to the AffableBean application.

What is the JavaServer Faces Framework?

The JavaServer Faces framework (JSR 314) is an integral part of the Java EE platform and aims to facilitate web development by providing the following:

  • a user interface component model: JSF includes a standard component API, which enables you to use and create custom UI components for your applications. A UI component is a widget that has a specific appearance and guarantees certain behavior. For example, this can be a simple text field that includes built-in data validation and conversion with accompanying error messages, or it can be a complex data table that interacts with a back-end data store and offers scrolling and column sorting for users. Being able to reuse UI components for your application's interface (or acquire custom components from third-party vendors) becomes increasingly important as your application grows in size and complexity.
  • an MVC development infrastructure: The framework provides a FacesServlet which works behind the scenes to dispatch requests to their appropriate handlers (usually backing beans that you create). You author page views using Facelets, the default view handler technology for JSF 2.0. These features, when operating in tandem with JSF's request processing lifecycle (described below), encourage your work to adhere to the MVC paradigm.

The JSF framework manages the request-response cycle by automating events that typically need to occur for each client request. These events are qualified into six distinct phases that are together known as the JSF request processing lifecycle. The book, JavaServer Faces 2.0: The Complete Reference by Ed Burns and Chris Schalk, describes the lifecycle phases as follows:

[T]he request processing lifecycle performs all of the necessary back-end processing for which one would otherwise have to write his or her own code. The lifecycle directs the processing of incoming request parameters, and it manages a server-side set of UI components and synchronizes them to what the user sees in a client browser. It also satisfies follow-up requests for images, style sheets, scripts, and other kinds of resources required to complete the rendering of the UI.[1]

The six lifecycle phases, according to JavaServer Faces 2.0, are defined as follows:

  1. Create or Restore View: Restores or creates a server-side component tree (View) in memory to represent the UI information from a client.
  2. Apply Request Values: Updates the server-side components with fresh data from the client.
  3. Process Validations: Performs validation and data type conversion on the new data.
  4. Update Model Values: Updates any server-side Model objects with new data.
  5. Invoke Application: Invokes any application logic needed to fulfill the request and navigate to a new page if needed.
  6. Render Response: Saves state and renders a response to the requesting client.[2]
JSF request processing lifecycle

One important concept of the JSF framework is the server-side UI component tree, or Faces View. This component tree is built and maintained in server memory for each client request, and is primarily associated with the first and last phases of the request processing lifecycle depicted above. Consequently, the application is able to maintain state between requests in a way that doesn't involve any manual coding on the part of the developer. In other words, the request processing lifecycle handles synchronization between the server-side View and that which is presented to the client. This enables you, the Java web developer, to focus on code that is specific to your business problem.

How Can JSF Benefit Your Project?

To understand JSF's benefits, let's take a second look at the AffableBean project and consider how the framework could be applied.

Strong Templating Support

Rather than creating your application page views in JSP pages, you'd be using Facelets technology instead.[3] Facelets is a first-rate templating technology that enables you to maximize markup reuse and reduce redundancy in your page views. Also, because Facelets pages use the .xhtml file extension, you are able prepare views using standard XHTML syntax.

In the AffableBean project, we took measures to reduce redundancy by factoring out the header and footer markup for all page views into separate JSP fragment files, and then included them in views by using the <include-prelude> and <include-coda> elements in the deployment descriptor. Aside from the header, the layouts for each of the application's five page views were unique. However, many websites maintain the same layout across multiple pages. This is where templating comes in especially handy.

With Facelets templating, you have more control over which portions of markup get displayed for individual page views. For example, you could create a template layout that is common to all page views, and insert view-specific content into the template to render your views. In this manner, you could specify a title for each page view. (Notice that in the AffableBean application, the title remains the same for all page views.)

No Need to Handle Incoming Request Parameters

Upon reexamining the AffableBean's ControllerServlet, you can see that each time we implemented code for the supported URL patterns, it was necessary to manually extract user parameters using the request's getParameter method. When working in JSF, you often create backing beans, which are Java classes that are conceptually bound to a specific page view. Parameters are automatically extracted from a request (during phase 2 of the request processing lifecycle), and set as properties for the backing bean. JSF also takes care of casting the String values of your request parameters into the types that you have defined for your backing bean properties. For example, if you have a property defined as an int, and your incoming request parameter is a String whose value is "33", JSF automatically converts the value to an int before storing it in the backing bean.

No Need to Programmatically Configure Navigation

In order to set up navigation, we followed a certain pattern when implementing the ControllerServlet: For each incoming request, the getServletPath method is called to determine the requested URL pattern. After logic related to the URL pattern is performed, a RequestDispatcher is attained, and the request is forwarded to the appropriate page view. In numerous cases, the appropriate page view is specified by hard-coding the path using the userPath variable.

None of this is necessary when using JSF - navigation is handled by the framework. Your job would be to either associate page views with URL patterns and any logical outcomes using a Faces configuration file, or take advantage of JSF 2.0's implicit navigation feature, which automatically forwards a request to a view that has the same name as the requested URL pattern.

Built-in Validation Support

JavaServer Faces provides built-in server-side validation support. In the AffableBean project, we created a Validator class and manually coded logic to perform all validation. Using JSF, server-side validation would automatically occur at phase 3 of the request processing lifecycle.

It would be worthwhile to take advantage of this validation for the AffableBean checkout form, however some preliminary steps would be in order. Specifically, the HTML markup for form elements would need to be replaced with comparable tags from JSF's Standard HTML Library. This step converts the form elements into JSF UI components, which we can then specify validation actions on using JSF's Core Library. To give an idea, the side-by-side comparison below demonstrates an adaptation of the checkout form's "name" field.

HTML Markup
<label for="name">name:</label>
<input type="text"
       id="name"
       size="30"
       maxlength="45"
       value="${param.name}" />

<c:if test="${!empty nameError}">
    Value is required.
</c:if>
JSF HTML Tag Library
<h:outputLabel value="name: " for="name">
    <h:inputText id="name"
                 size="30"
                 maxlength="45"
                 required="true"
                 value="#{checkoutBean.name}" />
</h:outputLabel>

<h:message for="name" />
                        

The <h:outputLabel> tag renders as an HTML <label> tag, whereas <h:inputText> renders as an <input> tag whose type is set to "text". Note the required attribute, which is set to true (shown in bold). This is all that's needed to ensure that the field is not left blank by the user. The <h:message> tag identifies the location where any validation error messages for the field should display. JSF's default error message for a field that requires user input is, "Value is required."

Continuing with the example, if we wanted to check whether input for the field hasn't exceeded 45 characters, we could apply the <f:validateLength> tag.

<h:outputLabel value="name: " for="name">
    <h:inputText id="name"
                 size="30"
                 maxlength="45"
                 required="true"
                 value="#{checkoutBean.name}">

        <f:validateLength maximum="45" />
    </h:inputText>
</h:outputLabel>

<h:message for="name" />

Well-Defined Division of Labor

As stated in the Java EE 6 Tutorial, "One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation for web applications." If you are working on a large project that involves a team of developers, the framework functions as a blueprint which allows team members to focus on different areas of development simultaneously. For example, front-end developers can implement page views using tags from JSF's HTML Library, while programmers responsible for implementing component logic and behavior can "plug their work into" existing HTML library tags.

Ability to Render the View with Other Markup Languages

Suppose that the Affable Bean staff commission you at a later point to prepare a mobile version of their site, so users can access it using a hand-held device. JSF APIs are a flexible rendering technology that enable you to attach multiple renderers to the component tree (i.e., View) of a JSF-enabled application. In other words, it is possible to create custom components that, for example, render HTML when requested by a browser, or WML when requested by a PDA.


See Also


About the NetBeans E-commerce Tutorial

AffableBean logo

The NetBeans E-commerce Tutorial and sample application were conceived of and written by Troy Giunipero. The application began as a project arising out of Sun's SEED program, and was developed from January 2009 to November 2010. The tutorial was prepared as part of ongoing efforts to provide documentation for the IDE's Java EE & Java Web Learning Trail.



Acknowledgments

Many people have helped with this project. I am especially grateful to following individuals for their help, support and contributions:

  • Ed Burns, who was my SEED mentor, for his patience and guidance, and his willingness to share his technical expertise in our numerous discussions concerning Java web technologies.
  • My managers, Patrick Keegan, for originally approving this project, and David Lindt, who showed continuous support.
  • David Konecny and Andrei Badea for their invaluable help and advice, especially in regard Java Persistence, working with EclipseLink, and integrating EE 6 technologies.
  • Don McKinney for providing the three beautiful diagrams used in Designing the Application.
  • Eric Jendrock and the Java EE Tutorial team, for granting permission to adapt and reproduce diagrams from the Java EE 5 Tutorial. Diagrams were used in Securing the Application, and are based on Figure 28-6: Mapping Roles to Users and Groups and Figure 30-3: Form-Based Authentication.
  • Jan Pirek, for coordinating and setting up necessary resources to make the live demo a reality.
  • Ondrej Panek for providing a Czech translation of text used in the sample application.
  • Also, special thanks to cobalt123 for graciously permitting usage of several photos, including Fresh Picks and Give Us Our Daily Bread #1.

Disclaimer

This tutorial and sample application are solely available for educative purposes. Although the sample application demonstrates a real-world scenario, there are several aspects that are decidedly not "real-world". For example, e-commerce sites do not typically store customer credit card details, but allow payment to be managed by a reputable third-party service, such as PayPal or WorldPay. Furthermore, although not discussed in the tutorial, customer trust is a hard-earned commodity. An e-commerce site's privacy policy, as well as the terms and conditions surrounding placed orders should be made easily available to customers and site visitors.

The sample application and project snapshots are provided "AS IS," without a warranty of any kind. If you aim to use or modify this software for your own purposes, please comply with the license presented at http://developers.sun.com/berkeley_license.html.


References

  1. ^ Adapted from JavaServer Faces 2.0: The Complete Reference, Chapter 3: The JavaServer Faces Request Processing Lifecycle.
  2. ^ Ibid.
  3. ^ You can certainly use JavaServer Pages in a JSF application. Facelets is the default view handler technology for JSF version 2.0. For previous JSF versions, the default is JSP. In fact, when creating a new JSF 2.0 project in the IDE, you are able to specify the view technology you want to use (Facelets or JSP).




The NetBeans E-commerce Tutorial - Setup Instructions

Content on this page applies to NetBeans IDE, versions 6.8 and 6.9

If you want to follow a tutorial unit without having completed previous units, you need to perform some preliminary steps in order to set up your development environment.

  1. Set up your MySQL database server. Follow the steps outlined in: Communicating with the Database Server.
  2. Create the affablebean schema on the database server, and populate the database with sample data:
    1. Click on affablebean.sql and copy (Ctrl-C; ⌘-C on Mac) the entire contents of the file.
    2. Open the IDE's SQL editor. In the Services window (Ctrl-5; ⌘-5 on Mac), right-click the affablebean database connection ( Database connection node ) node and choose Execute Command.
      Services window - Execute command menu option
      The IDE's SQL editor opens.
    3. Paste (Ctrl-V; ⌘-V on Mac) the entire contents of the affablebean.sql file into the editor.
    4. Click the Run SQL ( Run SQL button ) button in the editor's toolbar. The script runs on your MySQL server. Tables are generated for the database, and sample data is added to the product and category tables.
  3. Create a connection pool and JDBC resource on GlassFish.
    1. In the Services window (Ctrl-5; ⌘-5 on Mac), expand the Servers > GlassFish Server 3 node and choose Properties. In the Servers window that displays, make sure the 'Enable JDBC Driver Deployment' option is selected. If your project requires the MySQL Connector/J driver, this option will ensure that the driver is deployed to GlassFish when your project is deployed. (If the server is already running, you'll need to restart the server.)
    2. In the Services window, right-click the GlassFish Server 3 node and choose Start.
    3. Once the server is running, right-click the GlassFish Server 3 node and choose View Admin Console.
    4. Log into the console (default username/password is: admin/adminadmin).
    5. In the Admin Console, in the Tree on the left, expand the Resources > JDBC node, then click the Connection Pools node.
    6. In the Connection Pools interface, click the New button, and enter the following details:
      • Name: AffableBeanPool
      • Resource Type: javax.sql.ConnectionPoolDataSource
      • Database Vendor: MySql
      GlassFish Admin Console - Connection Pools interface
    7. Click Next. Accept all defaults and click Finish.
    8. In the Connection Pools interface, click on your newly created AffableBeanConnectionPool to make the following change under the General tab:
      • Datasource Classname: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
      GlassFish Admin Console - Connection Pools interface
    9. Click Save.
    10. Click the Additional Properties tab and ensure that the following three properties have been set. (There may be other properties listed - these are default settings, however the following three must be set manually.)
      • User: root
      • Password: nbuser
      • URL: jdbc:mysql://localhost:3306/affablebean
      GlassFish Admin Console - Connection Pools interface
    11. Click Save.
    12. Click the General tab, then click Ping. You should see a message indicating that the ping succeeded. The AffableBeanPool connection pool can now connect to your MySQL database server.
      GlassFish Admin Console - Connection Pools interface
    13. In the Admin Console's Tree in the left column, click the Resources > JDBC > JDBC Resources node. The JDBC Resources interface opens in the main window.
    14. Click the New button to create a new JDBC resource, then enter the following details:
      • JNDI Name: jdbc/affablebean
      • Connection Pool: AffableBeanPool
      GlassFish Admin Console - JDBC Resource interface
    15. Click OK.

You have set up the MySQL server and can connect to it from the IDE's Services window. You created a database named affablebean, and populated the database's product and category tables with sample data. You then started the GlassFish server, and created a connection pool that enables the server to connect to the affablebean database. Finally, you created a JDBC resource which your application can use to reference the server's connection pool.

You can now open and run any of the project snapshots provided for you in the tutorial units.

get support for the NetBeans

Support


By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2018, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo