P. 1
J2EE Spell

J2EE Spell

|Views: 499|Likes:

More info:

Published by: Arthanarisamy Annamalai on Sep 16, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

01/03/2013

pdf

text

original

Sections

  • 1.1 Introduction
  • 1.2 The Enterprise Today
  • 1.3.1 2-Tier Architecture
  • 1.3.2 3-Tier Architecture
  • 1.3.3 n-Tier Architecture
  • 1.3.4 Enterprise Architecture
  • 1.4.1 Platform Independence
  • 1.4.2 Reusability
  • 1.4.3 Modularity
  • 1.5 The J2EE Platform
  • 1.6 J2EE Architecture – Containers
  • 2.1 Introduction to Servlets
  • 2.2 Why use Servlets?
  • 2.3 Resources for Writing Servlet
  • 2.4 The Servlet Architecture
  • 2.5 Servlet Lifecycle
  • 2.6 Creating a Simple Servlet
  • 2.7 Development Phases of J2EE Applications
  • 3.1 Session Management
  • 3.2 Session Tracking
  • 3.3 Cookies
  • 4.1 Servlet Collaboration
  • 4.2 Servlet Chaining
  • 5.1 Introducing JSP
  • 5.2 The Nuts and Bolts
  • 5.3.1 The page Directive
  • 5.3.2 The Include Directive
  • 5.3.3 The taglib Directive
  • 5.4.1 Declarations
  • 5.4.2 Scriptlets
  • 5.4.3 Expressions
  • 5.5.1 jsp:useBean
  • 5.5.2 jsp:setProperty
  • 5.5.3 jsp:getProperty
  • 5.5.4 jsp:param
  • 5.5.5 jsp:include
  • 5.5.7 jsp:plugin
  • 5.6 Implicit Objects
  • 5.7 Scope
  • 6.1 Tag Extension 101
  • 6.2 Anatomy of a Tag Extension
  • 6.3.1 The javax.servlet.Jsp.tagext.Tag Interface
  • 6.3.2 The javax.servlet.jsp.tagext.BodyTag Interface
  • 6.3.3 The javax.servlet.jsp.tagext.BodyContent Class
  • 6.3.4 Convenlence Classes
  • 6.3.5 The javax.servlet.jsp.tagext.TagExtraInfo Class
  • 6.3.6 The Simple Example Revisited
  • 6.4 Tag Library Descriptors
  • 6.5 Using Tag Extensions in JSP Pages
  • 6.6.1 No Packaging
  • 6.6.2 WAR
  • 7.1 Introduction to Databases
  • 7.2.1 Two-Tier Database Design
  • 7.2.2 Three-Tier Database Design
  • 7.3 Overview of ODBC (Open Database Connectivity)
  • 7.4.1 How does JDBC work?
  • 7.4.2 Security Model
  • 7.4.3 JDBC API Components
  • 7.5 The java.sql Package
  • 7.6.1 Type 1: The JDBC-ODBC Bridge Driver
  • 7.6.2 Type 2: The Native Library-to-Java Driver
  • 7.6.3 Type 3: The Network Protocol Driver
  • 7.6.4 Type 4: The Native Protocol Driver
  • 7.7.1 Using Type 1 Driver(JDBC ODBC Bridge Driver)
  • 7.7.2 Using Type 2 Driver (The Native Library-to-Java Driver)
  • 7.7.3 Using Type 4 Driver (The Native Protocol Driver)
  • 7.8 The ResultSetMetaData Interface
  • 8. Servlet Inter-Communication (Send Redirect):
  • 9. JSP Directive:
  • 10. Jsp Scripting:
  • 11. Jsp & Servlets:
  • 12. Jsp, Servlets & JDBC:

J2EE Servlets & JSP

===========================================================================================================================

Chapter: 1 JAVA AND THE J2EE PLATFORM

Topics Discussed
  

 

Introduction Enterprise Today System Architecture 2-Tier Architecture 3-Tier Architecture n-Tier Architecture Enterprise Architecture Is Java the Answer? Platform Independence Reusability Modularity The J2EE Platform J2EE Architecture – Containers

1.1 Introduction Java, as a programming language is still young. However, the evolution of Java from a means of developing applets for running in browsers, to a programming model capable of driving today’s’ enterprise applications has been remarkable. Java has been around for only five years, yet it has attracted a very high level of interest in the technical and business communities, fuelling a considerable range of applications. From its inception, Java has triggered new programming models and technologies in different domains – ranging from devices, to telephony applications, to the enterprise. At the same time, Java has acted as a catalyst in making certain technology domains take more robust and secure shapes. Java’s enterprise computing platform, a.k.a. the Java 2 Platform, Enterprise Edition (J2EE) is one such domain. There were times in the history of Java, when debates on whether Java is a programming language or a platform used to surface in the media as well as technical circles. However, J2EE is one of the most successful attempts by Sun and its associates at making Java credible as a platform for enterprise computing. But what is J2EE? Why is it relevant? Why should you choose this technology for building enterprise-level application – from client-server to Internet to mobile? This chapter gives one perspective, and assists you in answering these questions. We hope that the rest of this book will help you to successfully build and manage such applications. In this introductory chapter, we’ll focus on

The J2EE technical architecture

1

J2EE Servlets & JSP

===========================================================================================================================

  

What makes J2EE credible as a platform What are the challenges it addresses

What technologies constitute the J2EE platform

First however, let us start with the challenges of developing applications for the enterprise today. 1.2 The Enterprise Today With the advent of the Internet, many businesses realized that a whole new market had opened up to be exploited, however, we doubt if many had realized what a radical effect it would have on the economy. Through the Internet and the recent growth of e-commerce, an organization’s information assets have now become more valuable. This shift to an information economy is forcing many businesses to rethink even their most basic business practices. In order to maintain a competitive edge, the adoption of new technologies has become a key factor in a company’s ability to best exploit its information assets. More importantly, adapting these new technologies to work in tandem with the existing, legacy systems has become one of the foremost requirements of the enterprise. One place these shifts in business practices have been felt most keenly is at the application development level. The funding and the time allocated to application development have been shrinking, while demands for complexity have increased. Although the emphasis on information is a small hurdle for developers, the whole revolution is being driven by the rapidly changing technological and economic landscape, which has created some new challenges for today’s enterprise application developers:

Responsiveness Although timeliness has always been important, the high-placed, fastchanging information-driven economy means that responding quickly to new directions and information is critical in establishing and maintaining a competitive edge. Programming Productivity Direct adoption of new technologies is insufficient unless they are properly utilized to their full potential and appropriately integrated with other relevant technologies. Thus, the ability to develop and then deploy applications as effectively and as quickly as possible is also important. Achieving this can be complicated by the sheer variety of technologies and standards that have been developed over the years, requiring highly developed skill sets, the acquiring of which and keeping up with which is a problem in itself. Moreover, the rapid pace of change in `standards’ themselves poses significant challenges to ensuring efficient meshing of technologies. Reliability and Availability In today’s Internet economy downtime can be fatal to the success of a business. The ability to get your web-based operations up and running, and to keep them running, is critical to success. As if that wasn’t’ enough, you must also be able to guarantee the reliability of your business transactions so that they will be processed completely and accurately.

2

J2EE Servlets & JSP

===========================================================================================================================

Security The Internet has not only exponentially increased the number of potential users but also the value of a company’s information, thus the security of that information has become of prime concern. What’s more as technologies become more advanced, applications more sophisticated, and enterprises more complex, the ability to implement an effective security model become increasingly difficult. Scalability The ability for the application to grow to meet new demand both in its operation and user base is important when an application’s potential user base may be millions of individual users through the Internet. To scale effectively requires not only the ability to handle a large increase in the number of clients but also effective use of system resources. Integration Although information has grown to be a key business asset, much of this information exists as data in old and outdated information systems. In order to maximize the usefulness of this information, applications need to be able to integrate with the existing information system – not necessary an easy task as current technologies have often advanced far ahead of some of these legacy systems. The ability to combine old and new technologies is key to the success of developing for today’s enterprises.

None of these problem domains is especially new to the enterprise developer! But solving these problems in a comprehensive and economical manner is still crucial. You may be aware that there have been several technologies to address one or more of the above demands. However, what has been missing is a comprehensive platform with a rich infrastructure and numerous architectural possibilities that also promotes a rapid development environment. 1.3 System Architecture When discussing enterprise application development, it is appropriate to introduce the concept of n-tier architecture. Typical client/server systems are based on the 2-tiered architecture, whereby there is a clear separation between the data and the presentation/business logic. These are generally data driven, with the application existing entirely on the client machine while the database server is deployed somewhere in the organization. While this approach allows us to share data across the enterprise, it does have many drawbacks. 1.3.1 2-Tier Architecture In a traditional 2-tiered application, the processing load is given to the client PC while the server simply acts as a traffic controller between the application and the data. As a result, not only does the application performance suffer due to the limited resources of the PC, but the network traffic tends to increase as well. When the entire application is processed on a PC, the application is forced to make multiple requests for data before even presenting anything to the user. These multiple database requests can heavily tax the network.

3

Multiple user interfaces can be built and deployed without ever changing the application logic. you are still faced with updating every single client installation. This can result in different client installation using different versions of the application. there are many different sources of enterprise data that your applications can access.2 3-Tier Architecture To address these issues. or even a directory service like an LDAP server. a set of XML documents (data that has been stored in documents conformant to the XML specification). The middle tier. or business layer. provided the application logic presents a clearly defined interface to the presentation layer. In addition to the traditional relational database storage mechanism. The presentation layer then receives the data and formats it for display. The middle tier (application logic) is basically the code that the calls upon (through the presentation layer) to retrieve the desired data. some users may not be ready for a full rollout and ignore the changes while another group insists on making the changes immediately. 4 . consists of the application or business logic and the third tier – the data layer – contains the data that is needed for the application. each with a well-defined set of interfaces.J2EE Servlets & JSP =========================================================================================================================== Application DB Another problem. What’s more. The separation of application logic from the user interface adds enormous flexibility to the design of the application. the software community developed the notion of a 3-tier architecture. including an enterprise database such as Oracle or Sybase. Even if it’s possible to automate the process. An application is broken up into three separate logical layers. The third tier contains the data that is needed for the application.3. Even the smallest of changes to an application might involve a complete rollout to the entire user base. The first tier is referred to as the presentation layer and typically consists of a graphical user interface of some kind. with a 2-tiered approach is that of maintenance. This data can consist of any source of information. 1.

3. often through the interaction with the application’s data. 1. n-tier architecture then breaks down like this:  A user interface that handles the user’s interaction with the application.J2EE Servlets & JSP =========================================================================================================================== User Interface Application Logic DB XML Document s However. there is no hard and fast way to define the application layers for an n-tier system. a heavier desktop application or even a wireless device Presentation logic that defines what the user interface displays an dhow a user’s request are handled – depending own hat user interfaces are supported you may need to have slightly different versions of the presentation logic to handle the client appropriately Business logic that models the application’s business rules. such as messaging. transactional support. Infrastructure services that provide additional functionality required by the application components. etc. The data layer where the enterprise’s data resides. we’re not quite finished with our subdivision of the application. this can be a web browser running through a firewall. We can take the segregation one final step to create an n-tier architecture.     5 . an n-tier system can support a number of different configurations.3 n-Tier Architecture As the title suggests. In fact. In an n-tier architecture the application logic is divided by function rather than physically.

What this ultimately means is that the data (the model) is separated from how the information is presented (the view). an application is designed based on these three functional components (model. we might end up with many different applications – possibly even with different architectures – all of which don’t communicate with one another. These application objects must cash have an interface that allows it to work together with the others. view. we are looking to create a more cohesive whole.4 Enterprise Architecture So far we have really been concentrating on a single application’s architecture. Rather than a change in architecture – enterprise architecture is basically just ntier – we need a change in perception.3. To turn an n-tier system into an enterprise system. In between this is the application/business logic (the controller) that controls the flow of the information. Each object states through its interface that it will accept certain parameters and return a specific set of results.J2EE Servlets & JSP =========================================================================================================================== Browser Firewall Application Client Presentation Logic Business Logic Service DB XML Document s Applications based on this architecture are employing the Model-ViewController (MVC) pattern. Therefore. however. and controller) interacting with each other. we simply extend the middle tier by allowing for multiple application objects rather than just a single application. Application objects communicate with each other using their interfaces: 6 . In an enterprise. we are in danger of considering these application as ‘stovepipes”. In other words. An interface can be thought of as a contract. 1.

4. Microsoft has Windows DNA (and the new. 1. are relatively simple and quick. Sun has J2EE. it is a good idea to make the interface as generic as possible to avoid changes later on. Since other objects communicate with the interface and not the object itself. 1. This promotes the standardization of business practices by creating a single set of business functions for the entire organizations to access. It is important to note that when designing an object and its interface. you are probably wondering what makes Java such a great choice. it’s interface and subsequently any object that accesses the interface. Oracle has the Oracle 8i Internet Platform.net architecture). If a business rule changes. if necessary. changes to the object.1 Platform Independence 7 . and so on. With so many choices for server-side development. then changes have to be made to the business object only and.J2EE Servlets & JSP =========================================================================================================================== HTML Form HTML Form HTML Form Interface Application component Interface Application component Interface Application component Database Middleware Remote Systems DB XML Document s With enterprise architecture. we can have multiple applications using a common set of components across an organization.4 Is Java the Answer? So far we have discussed system architecture from an implementation agnostic perspective and there exist many potential paths that you can take to actually implement your enterprise. and not the interface.

J2EE Servlets & JSP

===========================================================================================================================

With a enterprise’s information spread disparately across many different platforms and applications it is important to leverage a programming language that can work equally well throughout the enterprise without having to resort to awkward, inefficient translation mechanisms. A unifying programming model also reduces the difficulties encountered from integrating many of the different technologies that grow up specific to certain platforms and applications. 1.4.2 Reusability Code reuse is the holy grail of all programming. Segregating an application’s business requirements into component parts is one way to achieve reuse; using object-orientation to encapsulate shared functionality is another. Java uses both. Java is an object-oriented language and, as such, provides mechanisms for reuse. However, unlike objects, components require a more complex infrastructure for their construction and management. Basic object oriented concepts do not provide such a framework; however, the Enterprise Edition of Java provides a significantly stringent architecture for the reuse of components. 1.4.3 Modularity When developing a complete server-side application, your programs can get large and complex in a hurry. It is always best to break down an application into discreet modules that are each responsible for specific task. When you do this, it makes your application much easier to maintain and understand Java servlets, JavaServer Pages, and Enterprise JavaBeans provide ways to modularize your application - breaking your application down into tiers and into tasks. Despite the above features in its favor, it was not until early 2000 that Java developed a unifying programming model for applications on the enterprise scale – not that it lacked the capabilities but rather it was disorganized. Sun recognized this shortcoming and released the Java 2 Platform, Enterprise Edition (J2EE). The idea behind the J2EE platform is to provide a simple, unified standard for distributed applications through a component-based application model.

1.5 The J2EE Platform As you’ll see in the rest of this book, J2EE is one of the best solutions that we’ve had so far for meeting the demands of today’s enterprise. J2EE specifies both the infrastructure for managing your applications, and the service APIs for building them. The J2EE platform is essentially a distributed application server environment – a Java environment that provides the following:
 

A runtime infrastructure for hosting applications. A set of Java extension APIs to build applications

The applications that you can develop with the above may be programs to drive web pages, or components to implement complex database transaction, or even Java applets – all distributed across the network.

8

J2EE Servlets & JSP

===========================================================================================================================

1.6 J2EE Architecture – Containers As discussed in the previous section, a typical commercial J2EE platform includes one or more containers. But what’s a container? A J2EE container is a runtime to manage application components, and to provide access to the J2EE, APIs. Beyond the identity associated with the runtime, J2EE does not specify any identity for containers. This gives a great amount of flexibility to achieve a variety of features within the container runtime. This architecture shows two containers:
 

A web container for hosting Java servlets and JSP pages An EJB container for hosting Enterprise JavaBean components Apart from these two, the J2EE also specifies two more containers - an applet container to run applets, and an application client container for running standard Java application clients. In this book, our focus is limited to web and EJB containers only.

In the above figure, the vertical blocks at the bottom of each container represent the J2EE APIs. Apart from access to these infrastructure-level APIs, each container also implements the respective container-specific API (Java Servlet API for the web container, and the EJB API for the EJB container). The stacks of rectangles (servlets, JSP pages, and EJBs) in this figure are the programs that you develop and host in these containers. In the J2EE parlance, these programs are called application components. The following figure shows the architecture of J2EE.

Web Container Application Clients Java Servlets JSP Panes RMI/IIOP,JNDI,JTA, JDBC,JMS,javaMail, JAF

EJB Container

Enterprise JavaBeans

RMI/IIOP,JNDI,JTA, JDBC,JMS,javaMail, JAF

J2EE Application Server Databases and Other Resources
9

DB

J2EE Servlets & JSP

===========================================================================================================================

So we can also say that a container is a Java 1.2 (Java 2 Standard Edition 1.2) runtime for application components.

In this architecture, there are primarily two types of clients.

Web clients normally run in web browsers. For these clients, the user interface is generated on the server side as HTML or XML, and is downloaded and then rendered by the browsers. These clients use HTTP to communicate with web containers. Application components in web containers include Java servlets and JSP pages. These components implement the functionality required for web clients. Web containers are responsible for accepting requests from web clients, and generating responses with the help of the application components. EJB clients are applications that access EJB components in EJB containers. There are two possible types of EJB clients. The first category is application clients. Application clients are stand-a-alone applications accessing the EJB components using the RMI-HOP protocol. The second category of application clients is components in the web container. That is, Java servlets and JSP pages can also access the EJB components via the RMI-HOP protocol in the same way as the application clients.

In either case, clients access application components via the respective container. Web clients access JSP pages and Java servlets via the web container, and EJB clients access the EJB components via the EJB container.

10

The Web page uses information from corporate databases or other such sources.1 Introduction to Servlets The evolution of Internet has led to the development of the Java language. The following are the basic steps of using servlets: • The client makes a request. A servlet accesses requests from the client. The data changes frequently. and programs that process orders for e-commerce sites do this as well. and returns results. the focus has been on the client-side development of applets and GUI components.J2EE Servlets & JSP =========================================================================================================================== Chapter: 2 SERVLETS Topics Discussed           Introduction to Servlets Why use Servlets? Resources for Writing Servlet The Servlet Architecture Servlet Lifecycle Creating a Simple Servlet Development Phases of J2EE Applications Development Phases of J2EE Applications The Servlet API Handling HTTP Requests 2. perhaps returning a previously built page if it is still up to date. • The Web server forwards the request to the servlet after receiving it from the client. A servlet can be thought of as a server-side applet. Servlets are loaded and executed by a Web server in the same manner as the applets are loaded and executed by a Web browser. Building Web pages on the fly is useful (and commonly done) for a number of reasons: • • • The Web page is based on data submitted by the user. For example. For example. 11 . you would use this for making a Web page at an on-line store that lists current prices and number of items in stock. Till date. in this chapter. • Some kind of process is done by the servlet after receiving the request. you will be introduced to the other side of the client/server computing – the Servlets. which is incomplete as far as clientserver computing is concerned. a weather-report or news headlines page might build the page dynamically. performs some task. It serves as a complete client/server solution where programs are dynamically downloaded onto the client. For example the results pages from search engines are generated this way. Therefore. Servlets are programs that run on a Web server and build Web pages on the fly.

they run continuously. 2. which allows a servlet to access only certain directories on your file system.J2EE Servlets & JSP =========================================================================================================================== • • A response is returned back to the web server from the servlet. Different levels of security can be allowed for different servlets by taking advantage of Java’s security framework. There is heavy start-up overhead for this reason. You have to set the environment variable CLASSPATH.2 Why use Servlets? Servlets have various benefits over other technologies that are used for writing server side programs. You have to create different versions of plug-ins for running the same CGI program on a different hardware platform or a different operating system. For example. 12 . as associated with applets.jar. Figure 2. One such technology is CGI (Common Gateway Interface) scripts. then your servlets is secure as well. 2. The following section distinguishes between Servlets and CGI-based Web programs in detail. The CGI program that handles the request for the server is terminated as soon as the request is processed whereas Servlets continue to run even after the request is processed. but rely instead of on a collection of ad hoc rules. Servlets can run on any platform that supports Java. 2. Request Web Server Client Response Fig. to the required location so that your servlets can find the servlet packages. sample services for Windows 95 and NT. CGI programs do not have a basic security framework. This eliminates the heavy start-up overhead. The CGI program must store the information in a database or a file and read it again the next time it starts up when it needs to maintain information across the network. Servlets have less start-up cost. This kit includes the Java servlet and Sun servlet packages. are not applied with servlets because servlets are executed on the server and if you Web server is secure behind a firewall.3 Resources for Writing Servlet You have to install JavaSoft’s Java Servlet Development Kit (JSDK) before creating any servlet. and ServletRunner to test servlets.1 Working of a servlet Servlet The security issues. with the JSDK installed in the C:\2sdk: Classpath: c:\j2sdk\j2sdk.1 shows how a web server processes a request and the response sent to the client. The following environment variable need to be set for Windows systems. Path: c:\j2sdk\bin. The web server will forward the response to the client. and they are platform-independent. a security policy. can be defined.

you need a Web server that supports the Servlet API. There are various other vendors that are providing server implementations for this purpose. The service() method is invoked by the server so that the servlet can perform its services. The Java Servlet Development Kit is included as a part of JDK 1. 3. Vendor Apache ATG Cybotics IBM KonaSoft Lotus Novocode O’Reilly Tandem W3C WebLogic Product Apache jserv Dynamo Application Server Cybotics Search Engine Internet Connection Server KonaSoft Enterprise Server Domino Go Webserver NetForge Web Server Website Professional iTP Webserver Jigsaw HTTP Server Tengah Application Server Table 2.J2EE Servlets & JSP =========================================================================================================================== The JSDK can be downloaded from the JavaSoft home page (http://java. It takes two parameters one of the ServletRequest interface and the other of the ServletResponse Interface.sun. The Servlet interface provides methods that manage the servlet and its communications with clients. the init () and destroy() methods are used to start and stop a servlet. Let us discuss some of them that are essential for working of a servlet. While HTML is lightweight and is supported by Java enabled web browsers. 4. The Servlet Interface All servlets implement the Servlet interface. If you are still using JDK 1. This client application can be provided in form of HTML or applets. While developing a servlet. Some of them are given in Table 2. If your Web server is not running.1 separately. Direct the browser to the particular URL that refers to the new servlet. 2.2. For example. Run your browser.com). We will be using J2EE (Java 2 Enterprise edition 1. 13 .4 The Servlet Architecture There are various interfaces and classes that are used to implement a simple servlet. Another thing to remember while creating servlets is that you need to create some kind of client application that invokes the servlet. We will be using both HTML and applets to communicate with servlets. To run Servlets. 2.1 List of products supporting Java Servlets The following steps are required to run any servlet: 1.2. applets are beneficial as they solve the portability and distribution problems.1) to run servlets. We will be developing our applications using HTML.1 you should download the JSDK 1.1. either directly or by extending a class that implements it such as GenericServlet. you need to provide implementations for all or some of these methods. start it.0. Configure the Web server to install the servlet.

and the names of the remote host (getRemoteHost () method) that made the request and the server that received it. and will not call it again unless it is reloading the servlet. Let us now see how a servlet is loaded and run on a web server. The ServletRequest interface encapsulates the communication from the client to the server. Servlets run until they are removed from the service. Initialization is allowed to complete before client requests are handled (i. 2.5 Servlet Lifecycle Servlets run on servers as we have discussed earlier. the protocol (scheme) being used by the client. Subclasses of ServletResponse give the servlet more protocol-specific capabilities. through which the servlet gets data from clients that are using application protocols such as the HTTP POST and PUT method. The ServletResponse interface gives the servlet methods for replying to the client. and provides an output stream. After the server loads and initialize the servlet. There are various other methods that are used to give additional capabilities to a servlet. and a Writer though which the servlet can send the reply data. ServletOutputStream. while the ServletResonse interface encapsulates the communications from the servlet back to the client. The classes and interfaces described above make up a basic Servlet. Each client’s request has its call to the service method run in its own servlet thread: the method receives the client’s request.2. 14 . HttpServletResponse contains methods that allow the servlet to manipulate HTTP-specific header information. Subclasses of ServletRequest allow the servlet to retrieve more protocol-specific data. it runs the servlet’s destroy method. when it loads the servlet. The server cannot reload a servlet until after it has removed the servlet by calling the destroy method. When a server loads a servlet. For example. When a server removes a servlet. a request of a system administrator. it receives objects from the ServletRequest and ServletResponse interfaces. It allows the servlet to set the content length and mime type of the reply. ServletOutputStream. before the service method is called) or the servlet is destroyed. for example. The server calls the init method once. For example. the servlet is able to handle client requests. The servlet lifecycle is given in Figure 2. the server will not run it again after it reloads and reinitializes the servlet. A detailed explanation of these classes and interfaces is given later in the chapter.J2EE Servlets & JSP =========================================================================================================================== Service/Response and ServletRequest Interface When a servlet accepts a call from a client. HttpServletRequest contains methods for accessing HTTP-specific header information.e. Servlets can run multiple service methods at a time. The method is run once. It processes them in its service method. The ServletRequest interface allows the servlet access to information such as the names of the parameters passed in by the client. It also provides the servlet with access to the input stream. it runs the servlet’s init method. and sends the client its response.

*.servlet.println ("The name of the server running is "+getServletInfo() ). The init() and destroy() methods are typically used when the program needs to initialize or release some resources. print the request string to the PrintStream.io. out.println ("Hello "+ req.*. Let us write a simple servlet program with the help of the above methods. This servlet will respond to the client with the server’s information.2 The Servlet Lifecycle 2. 15 . 2.getRemoteHost()).6 Creating a Simple Servlet The basic steps required for writing servlets are as follows: • • • • Step 1: Extend the GenericServlet class. public class SimpleServlet extends GenericServlet { public String getServletInfo( ) { return "Localhost ". import javax. Step 6: Finally.J2EE Servlets & JSP =========================================================================================================================== d Server Server Code Loa Server Code Server Server Code Handle Client Requests Client Client Unload Server Fig. (The init() and destroy() methods are not overridden to make the program simpler. out.getOutputStream() ). } public void service(ServletRequest req. ServletResponse res) { try { PrintStream out = new PrintStream (res.println ("The following is the information about the environment in which the servlet is running "). out. Step 2: Override the service() method. import java.) Step 3: Get the output stream from the ServletResponse object and create a PrintStream object with it.

Figure 2. Compile it using the javac compiler as given below: C:\ServletExample> javac SimpleServlet.ear file) 16 Deployment J2EE Server Phase .J2EE Servlets & JSP =========================================================================================================================== } catch (Exception e) {} } } The above servlet extends the GenericServlet class and overrides the getServletInfo() and the service() method. the HTML file. Now let us look a next stage of developing a J2EE application.e. The web component i. have already been created. The service() method implements the actual request handling and response handling. Web Component (.3 shows how a web component can be assembled in a J2EE application (. We will see this while assembling the servlet. The getServletInfo() method returns a string that provides information about the servlet. The server passes the ServletRequest and ServletResponse arguments to the servlet.7 Development Phases of J2EE Applications The servlet that is created will be assembled and run on a J2EE server. The HTML is given below: <html> <head> Servlet Example </head> <form Method = "GET" Action = "SimpleServletAlias" > <INPUT NAME= "Test" Type=SUBMIT VALUE="test"> </input> </form> </html> Save this file as Servlet. The getRemoteHost() method returns the name of the host that made the request. This is the alias name that should be provided while deploying the servlet using J2EE.e. it passes through these development phases: • • • • Web Component Creation J2EE Application Client Creation J2EE Application Assembly J2EE Application Deployment The first two stages are already accomplished. i.WAR file) Assembly Phase J2EE Application (. The Web server invokes it when the URL of the servlet is requested.html in the folder ServletExample. Save this file in the folder ServletExample. This involves J2EE application Assembly and deployment. The Action attribute of the Form tag takes the alias name of the Servlet. As a J2EE application evolves. which will invoke this servlet. the servlet and the client application.java Now let us write the HTML.ear file) and then deployed on the server. 2.

servlet defines all the classes and interfaces associated with the Servlet SPI. The Servlet Interface and its Methods The Servlet Interface allows the developer to create servlets by providing the necessary functions.3 J2EE application assembly and deployment • The Servlet API The Servlet API was defined by Sun Microsystems for writing servlets. The init () method might be called to reset the servlet after it has been used.2: Method public void service( ServletRequest req. The following section describes the Servlet API classes and interfaces in detail. This method gets a servletContext object that is associated with information about the environment in which the servlet is running. and ServletOutputStream classes. you have to be careful that only initialization is performed in this init () method. This method gets a servletContext object that is associated with information about the environment in which the servlet is running. The package javax. This method is called by the system when the servlet is first loaded. This interface includes the methods listed in Table 2. the developer has to use the four interfaces to make the server comply with the servlet API and then use the server’s implementations of this interface along with the ServletInputStream. Some of the interfaces defined inside the Servlet API are: • • • • Servlet ServletContext ServletRequest ServletResponse And the classes are: • • ServletInputStream ServletOutputStream To write servlets. This main purpose of the parameters is to access the input and output streams that are connected to the client browser. ServletResponse res) Description This method is used to service a single request from a client.J2EE Servlets & JSP =========================================================================================================================== Fig. This method is used to log a message to the servlet log. It is basically used for general initialization of the servlet. 2. Hence. Log is generally public void init() ServletContext getServletContext() ServletContext getServletContext() void log (String mesg) 17 .

This method does not return the values associated with the parameters. if an URL is given as. The returned string is of the form <Protocol/major-version>. This method is used to return the name of the host who made the request. gets input streams from the client. It returns –1 if the size is unknown. http://localhost:8080/servlets/Myservlet>mesg=Hello.2 Servlet Interface Methods • The ServletRequest Interface The ServletRequest interface defines methods. These log entries depict the accesses the Web server receives. To obtain the associated values. some browsers specify content types of text / plain to indicate that the data is of no special type. the method call getParameter(“mesg”) would return the string value Hello. Table 2. For instance.<minor-version>. This method is used to release the servlet.J2EE Servlets & JSP =========================================================================================================================== String getServletInfo() Public void destroy() written into a directory called log under the server’s home directory. The precise set of headers will depend on the browser being used to issue the request. The Content type depends on the browser. You can get the header information through some methods described later in this chapter. This method is used to return a string that represents the host name of the server.3 lists the methods of this interface: Method int getContentLength() String getContent Type() Description This method is used to return the size of the input data to be supplied (in bytes). Table 7. as a string. and extracts path and query information from the requested URL. String getProtocol() String getParameter( String parameter-name) Enumeration getParameterNames( ) InetAddress getRemoteAddr() String getRemoteHost() String getQueryString() String getServerName() 18 . The header information defines general aspects of the connection. This method returns nil if the client has not specified the content type. and some use application / octet-stream. This method is used to return an enumeration of strings representing the names of the parameters defined in the URL. This method is used to return a string that represents only the query string part of the Servlet URL. This method is used to return a string that is associated with the MIME content type for the data that is to be sent to the servlet from the client browser. This method is used to return the protocol and version of a Web browser client. call the getParameter() method. This method is used to return the IP address of the client who sent the request. This method returns the information about the servlet. collects the header information. For example. This method is used to return the value of the parameter (Query string defined in the URL) associated with the name of the parameter passed as an argument to this method. Some use content / unknown.

and setting the status of the response.3 ServletRequest Interface Methods • The ServletResponse Interface The ServletResponse interface methods that are used for getting an output stream directed at the client. sending errors to the client. To obtain the header_field use the method getParameterNames(). This interface allows you to send information to the client’s browser. This method is used to write the status and message headers for the response to the output stream. Table 2. This method is used to return the path information that describes the path on the server machine from which the servlet was loaded. The following are the variables: • • • • • • • • • SC_OK SC_CREATED SC_NO_CONTENT SC_MOVED_PERMANENTLY SC_MOVED_TEMPORARILY SC_BAD_REQUEST SC_UNAUTHORIZED SC_FORBIRDDEN SC_NOT_FOUND Table below lists the methods of ServletResponse interface: Method ServletOutputStream getOutputStream() void setContentLength(int length) void setContentType (String type) Description This method is used to return the output stream for writing responses to the client browser. The content types are the MIME types discussed earlier. void write-Headers() void setStatus (int status) void setStream (int status) 19 . This method is used to write the status and message headers for the response to the output stream. The response status can be set through a list of static integer variables defined by the ServletResponse interface. This method returns the input stream for reading the request data. This method is used to set the content type for the response. This method is used to return the header information associated with the header_field.J2EE Servlets & JSP =========================================================================================================================== int getServerPort() String getPathTranslated() String getHeader(String header_field) ServletInputStream getInputStream() This method is used to return an integer that represents the port number through which the request is received. (Refer note for more details about MIME). setting the header information. This method is used to set the content length of the response. This method is used to set the status code and a default message for the response.

Handling HTTP Requests We have written a program by extending the GenericServlet class. The methods normally overridden are: 20 .).http. etc. Note: The MIME Types area allows you to manage the list of suffixes and MIME type mapping for the Web service. This method used to return an enumeration of all the available servlets in this context. the most common way to develop servlets is by extending the javax. which the file extension is mapped to.4 ServletResponse Interface Methods. The format of MIME type is Type/Subtype. The HttpServlet class. The type defines the generic file category (such as audio.wav) so that the Web service knows what type of file is being handled. thus you can map an extension (such as ` wav’ ) to a particular MIME type (such as audio/x. Table 2.J2EE Servlets & JSP =========================================================================================================================== void setHeader( String String header_value) header_field. servlet writers must subclass it and override at least one method. • The ServletContext Interface The ServletContext interface allows you to find out information about the environment in which the servlet is running. Table 2. servlets are likely to use HTTP as the basis of their communication.servlet. Table 2. A MIME type is a way to determine the contents of a file. image. Method String getServerInfo() String getServlet() Enumeration getServlets() Description This method is used to return a string that represents the name and the version of the server running. Because it is an abstract class. which extend the ServletRequest and ServletResponse interfaces described earlier. jpeg. The HttpServlet class extends the GenericServlet base class and provides a framework for handling the HTTP protocol.5 ServletRequest Interface methods Since the basic Servlet interface is not protocol-specific. These interfaces are HttpServletRequest and HttpServletResponse. etc. The Servlet API provides two additional interfaces that can be used with the HttpServlet class.) and the subtype defines the exact type within the generic type (such as x-wav.HttpServlet class. This method is used to set the value of a header field. a class that implements the Servlet interface is provided to give additional support methods that are useful when handling this protocol.5 lists the methods through which you can find these details. This method is used to return a string that represents the name of the servlet. Because most servlets are implemented on web services that use the HTTP protocol to interact with clients.

println(“<HEAD><TITLE> SimpleServlet Output </TITLE> </HEAD.setStatus ( HttpServletResponse. supports standard HTTP requests by dispatching them to appropriate methods. if HTTP POST requests are supported.servlet. out. such as the methods listed above that have the prefix “do”.2) that provided information about the environment in which the servlet is running.J2EE Servlets & JSP =========================================================================================================================== • • • • • • doGet.println(“<h1> SimpleServlet Output </h1>”).servlet. }catch(Exception e) { } } } Write the HTML file for the above servlet similar to the one give in the last program. import javax. Remember to use the Get request for the Method attributed of the form 21 . res. Servlets that do not manage resources do not need to specialize these methods. The service method. which will be interpreted by the client browser.4). doPut.*. out. public class GetServlet extends HttpServlet { public void doGet (HttpServletRequest req.getServerInfo()). out. if HTTP GET requests are supported. Let us write a program that extends the HttpServlet class and uses the ServletContext interface to get an object of the ServletContext (through getServletContext() method.println (“</BODY>”). as provided.5) is then used to display information about the server. The method getServerInfo() (refer Table 2.io. Overriding the doGet method automatically also provides support for the HEAD and conditional GET operations.SC_OK). res. if the servlet writer needs to manage resources that are held for the lifetime of the servlet. getServletInfo. doPost.getOutputStream()). Notice that the service method is not typically overridden.*. out.</BODY>”). The program is as follows: import java. doDelete. PrintStream out = new PrintStream( res. Now the response given by the Web server will be in HTML text.setContentType( “text/html”). out.”). to provide descriptive information through a service’s administrative interfaces.refer Table 2.http.*.println (“The name and version of the server running is “+sc. The lifecycle methods init and destroy. We will also change the MME type in the setContentType() method to text/html (refer Table 2. if HTTP PUT requests are supported.println(“<P>This output is from GetServlet. if HTTP DELETE requests are supported.close(). out. import javax. HttpServletResponse res ) { try{ ServletContext sc=getServletContext().

HttpServletResponse res)throws ServletException. //Open the file for writing the survey results.println(“Your Login name is “ + LoginName ).4 Output of the program Let us write another servlet that receives two parameters from the client.servlet. This servlet overrides the doPost method and uses the getParameter() (refer Table 2. IO Exception { // first. toClient. The output produced is given in Figure 2.http.println(“<title>Thank you!</title>”) toClient. toClient. String pwd = req.getWriter().getParameter (“Login”).println(“</html>”). Compile the servlet and then deploy the servlet following the same steps as given before.close (). toClient. //Get the response’s PrintWriter to return text to the client.getParameter (“pwd”).4: Fig. String LoginName = req.println(“<html>”). set the “content type” header of the response res. import java.J2EE Servlets & JSP =========================================================================================================================== tag and the Action name should be the same as the alias name provided while deploying the servlets in J2EE.println(“Thank you for registering <br>”). *.3) method to get the value of the parameter.io*. toClient. import javax.*. PrintWriter toClient = res. 2. } } 22 .servlet.*. import java. the Login name and the password and responds back to the client with a thanks message. // Close the writer.setContentType (“text/html”).util. // Respond to client with a thank you toClient. import javax. public class Servlet2 extends HttpServlet { public void doPost (HttpServletRequest req. the response is done.

The HTML page as given in Figure 2. Remember to give the Alias name as test1Alias as given in the HTML file here.5 will be displayed. click on the Login button. The following output will be displayed on the screen. Open the Web browser and type the URL.J2EE Servlets & JSP =========================================================================================================================== The HTML for the above servlet is given below: <html> <head><title>Login Form</title></head> <body> <form action="testAlias" method="POST"> <BR><BR> Login <input type=text name=Login > </BR><BR> Password <input type=password name=pwd> <BR></BR> <input type=submit value = Login> <input type=reset value=Cancel> </form> </body> </html> Deploy the servlet and the HTML file using the J2EE server. 23 . 2.5 The Login form After you give the Login name and the password. Fig.

1 Session Management Data needs to be managed in case of multiple HTTP requests. A session consists of requests that are made during a single browser invocation.6 Response from the servlet Chapter: 3 SESSIONS IN SERVLET Topics Discussed    Session Management Session Tracking Cookies 3. 3.J2EE Servlets & JSP =========================================================================================================================== Fig 2. storing that identifier with the client and then making the client provide that identifier with each HTTP request to the server. in case of a shopping system. As you know that unlike TCP. This means that HTTP does not maintain a connection to the server for the duration of a session. the server should be able to distinguish clients from one another and also provide a way to store data for each individual client. you need to identify each client session uniquely. For example. In other words. This can be done by assigning an identifier to each client. The Servlet API provides a powerful model for keeping track of session information. a session starts when you open a browser and ends when you close it. For tracking sessions. In order to do this.2 Session Tracking 24 . the list of items that are in a customers cart should be maintained. http is a stateless protocol.

) Invalidating the Session  Invalidating a session means to remove the HttpSession object and its values from the system. • • • Get a session (an HttpSession object) for a user. public class counter10 extends HttpServlet { public void service (HttpServletRequest req.getWriter().) Storing and Getting Data from a Session The HttpSession interface provides methods that store and return: • • Standard session properties. import java. Let us now write a program that illustrates session tracking. such as a session identifier Application data. To properly maintain the session.J2EE Servlets & JSP =========================================================================================================================== Session tracking is a mechanism that services use to maintains state about a series of requests from the same user (i. then you must call getSession before accessing the Writer. new Integer (1)).HttpServletResponse res) throws ServletException. To manually invalidate a session. not just before sending any response data.servlet.servlet.intValue()+1 hs. new Integer(count)). (If you respond using a Writer. When you call the method with it’s create argument as true.getAttribute ("counter")==null) { hs. Store or get data from the HttpSession object. PrintWriter pw = res. the implementation creates a session if necessary.http. Invalidate the session (optional). A user’s session can be invalidated manually or. import javax. if (hs. depending on where the servlet is running.setAttribute("counter". use the session’s invalidate() method. } else { int count= ((Integer) hs.util. Obtaining a Session  The getSession method of the HttpServletRequest object returns a user’s session.e.io. import javax. you must call getSession before any output is written to the responses.Dictionary. Some web servers automatically invalidate a session when there has been no page request for some period of time.*.*.getSession(true).getAttribute ("counter")) . 25 .setAttribute ("counter". requests originating from the same browser) across some period of time. IOException { res.*. To use session tracking. This program keeps track of the number of times a web page has been visited. HttpSession hs = req. which is stored as a name-value pair.setContentType ("text/html"). automatically. (This is like java. where the name is a String and the value is an object in the Java programming language.

Cookies that a client stores for a server are returned by the client to that sever and only that server.J2EE Servlets & JSP =========================================================================================================================== } pw. To write a Cookie. you will get the output as given in Figure 3. such as a web browser. 3.1 Output of Session Tracking Example 3. Fig.getAttribute ("counter") + " no of times</h1>"). but we still have not discussed how a unique session id is maintained between a client and the server. version number. It can contain properties like comment. The server embeds a cookie value in a response header and the browser returns this cookie value with each request. you need to 26 . A cookie is a piece of data that can be embedded in HTTP request or response. This can be done using cookies.3 Cookies Till now we have seen how to track session using the Servlet API. } } The HTML for the above program is as follows: <body> <form method = get action =”testAlias”> <input type=submit> </form> </body> After you deploy and run the servlet in a Web browser. of at least four kilobytes each. A cookie can store information like the session ID to bind a particular HTTP request to a session. the following steps are taken: To send a cookie  To send a cookie.1.println ("<h1>you have visited the page"+hs. and maximum lifetime. Client software. A server can provide one or more cookies to a client. is expected to support twenty cookies per host.

• Set Attributes of the Cookie There are various methods that can be used to set various cookie values and attributes. • Sending Cookies 27 . retrieve all cookies from the user’s request find the cookie or cookies with the name that you are interested in. setSecure(boolean0 Indicates to the user agent that the cookie should only be sent using a secure protocol (https).1 Methods to set cookie values and attributes. setValue(String) Sets the value of the cookie should only be sent using a secure protocol (https).http. Table 3.) In addition. setDomain(String) This cookie should be presented only to hosts satisfying his domain name pattern. Method Description setComment(String) If a user agent (web browser) presents this cookie to a user. You can change the value inside the cookie later in the program by using the setValue() method. one for the name and the other for the value. instantiate the Cookie object set its attributes send the cookie. The value of the cookie can be any string. 2.servlet.cookie is used to create a cookie object. you need to: 1. using standard programming techniques get the values of the cookies that you found. Table 3. (Alphanumeric strings qualify as tokens. this creates a cookie with the initial name and value. 3. the cookie’s purpose will be described using this comment. setMaxAge(int) Sets the maximum age of the cookie. names that start with the dollar-sign character (“$”) are reserved and cannot be used. 3. 2. The constructor of this class takes two parameters. setVersion(int) Sets the version of the cookie protocol used when this cookie saves itself. To get information from a cookie  To do this.1 lists some such methods. The name of the cookie must be an HTTP/1.J2EE Servlets & JSP =========================================================================================================================== 1.1 token. Let us discuss each of these steps in detail: • Instantiate the Cookie object The javax. setPath(String) This cookie should be presented only with requests beginning with this URL. Tokens are strings that contain none of the special characters. though null values are not guaranteed to work the same way on all browsers.

Cookie c1 = new Cookie ("Emp_Name". Let us now write a program that adds three cookies and sets their maximum age using the setMaxAge() method (refer Table 3.addCookie (c1). } } The HTML file is given below: <body> <form method = get action = “soma”> 28 . • Getting the value of a cookie Values of a cookie can be obtained by using the getValue() method.servlet. c1. Since multiple cookies can have the same name.setMaxAge (10000). "8000").print("<h1> Thank U </h1>"). To retrieve any cookie. IOException { res.*.J2EE Servlets & JSP =========================================================================================================================== Cookies are sent as headers of the response to the client. PrintWriter p = res. name of a particular cookie can be obtained by using the getName() method.print ("<html><body>"). p. they are added with the addCookie method of the HttpServletResponse class. p. res.*.1) and displays a message on the Web browser. p. res. The getCookies() method returns an array of Cookie objects.HttpServletResponse res) throws ServletException.servlet. c. public class cookie1 extends HttpServlet { public void service (HttpServletRequest req.addCookie (c2).io. Cookie c2 = new Cookie ("User-id".setMaxAge (10000). • Retrieving the Cookies Clients return cookies as fields added to HTTP request headers.print ("<body> Response sets 3 cookies</body><br>"). you must retrieve all the cookies using the getCookies() method of the HttpServletRequest class. java. res. c2. import import import javax.getWriter (). Cookie c = new Cookie ("EmpNo".setContentType ("text/html"). If you are using a Writer to return text data to the client. "Ganesh_in"). javax.http.*. you must call the addCookie() method before calling the HttpServletResponse’s getWriter method.setMaxAge (10000). "Ganesh").addCookie (c). which you can search to find the cookie or cookies that you want.

Fig.2 Output of the Cookie Program The cookies are saved on your machine. 3. As you can see from the Figure 7.26. You can have a look at the folder named cookies on your machine and open the file with the name you specified for the context root (while deploying). The file is given in Figure 7. The following will be displayed in the Web Browser.J2EE Servlets & JSP =========================================================================================================================== <input type=”submit”> </form> </body> Deploy this application on J2EE and run it in Web Browser. 29 .26. You can retrieve the cookies using the getCookies () method as discussed earlier. three cookies have been added.

In this case the servlet is not responsible for response generation.J2EE Servlets & JSP =========================================================================================================================== Chapter: 4 IMPLEMENTING INTERSERVLET COMMUNICATION Topics Discussed    Servlet Collaboration Servlet Chaining Request Dispatching 4. Although this is not Java Servlet API specification. a JSP page. processes application logic. this approach used to be called `inter-servlet communication’. A servlet receives an HTTP request from a client. which is equivalent to a servlet at run-time).  Request Dispatching: Request dispatching allows one servlet to dispatch the request to another resource (a servlet. executes some application logic. and then hands over the request to another servlet. a servlet receives an HTTP request. and of the servlet engine vendors. and has been replaced by request dispatchers. The second servlet completes the application logic. This completes one requestresponse trip for the client. the servlets is not completely responsible for processing a request. Instead.  In both the scenarios. Instead. it delegates the processing to another servlet (or a JSP page. there are several scenarios in which this basic model is not adequate:  Several receive an HTTP request from a client. you’ll This was once a very widely used approach. for the sake of find a short description below. and either prepares the response.1 Servlet Collaboration In the default servlet model. The API for supporting inter-servlet communication has now been deprecated. or any other resource). 30 . and a JavaServer Page drives the response.2 of the servlet API. There are two types of solutions for addressing the above requirements:  Servlet chaining: supported by some supported by the completeness. Prior to version 2. However. and processes application logic partially. the JSP page is responsible for dynamic content. or requests a JSP page to drive the response. and prepares the response.

The servlet engine sends all requests for this alias to servlet A. Servlet chaining was initially introduced in the Java Web Server. After executing sever A’s service method. The final response is then sent to the client. you specify the order in which these servlets should be invoked.2 Request Dispatching 31 . you should consider using the request dispatching approach. this is servlet chaining. After developing these servlets. the servlet engine invokes the servlets in the specified order. C). Instead. Refer to the figure below for an overview of this approach: Servlet Engine Alias Client (Browsers) Servlet A Servlet B Servlet C The key feature of servlet chaining is that you configure the servlet engine to do the chaining. Briefly. The idea of servlet chaining is very simple: you design a set of servlets. During setup. you configure your servlet engine to specify a chain of servlets for a given URL path alias. B.J2EE Servlets & JSP =========================================================================================================================== 4. Suppose you’ve servlets A. and its component model.2 Servlet Chaining Servlet chaining predates J2EE. followed by C’s service method. where output of one program becomes input for another program in the pipe. 4. This is similar to piping on Unix. Once the servlet engine receives a request for this alias. Consider a browser sending a request to the URL path pointing to this alias. B. each of which does a single task. and C executing three parts of a request-response process for a single customer service. You’ll still find some books talking about servlet chaining. the servlet engine invokes servlet B’s service method. but was never part of the servlet APT specification. but be advised that this non-standard feature is not supported by most of the Web containers today. Let’s assume that / custService is the alias given to this chain (/custService=A.

(or a JSP page. This is a process of the web container dispatching a request to a servlet.servlet. • The include() Method public void include (ServletRequest request. after the calling servlet has finished any preliminary processing. • The forward() Method special interface called public void forward(ServletRequest request. In simple terms. ServletResponse response) throws ServletException. the first servlet should be able to obtain a reference to the second servlet.servlet. which allow you to delegate the requestresponse processing to another resource. The Java Servlet API has a javax. java.IOException This method lets you forward the request to another servlet or a JSP page. • Obtaining a RequestDispatcher Object There are three ways in which you can obtain a RequestDispatcher object for a resource: javax. • RequestDispatcher Interface public Interface RequestDispatcher This interface encapsulates a reference to another web resource at a specified path within the scope of the same servlet context.IOException This method lets you include the content produced by another resource in the calling servlet’s response. A javax. or an HTML file on the server. java.io.ServletContext methods get RequestDispatcher() getNameDispatcher(): public RequestDispatcher getRequestDispatcher(String path) public RequestDispatcher getNameDispatcher(String name)  and 32 .io. When the web container receives a request. Using this reference. the first servlet can dispatch a request to the second servlet. or even a plain HTML page). This interface has two methods. it constructs request and response objects and invokes one of the servlet’s service methods with the request and response objects. What if this servlet wants to dispatch the same request to another servlet after some preliminary processing? For this purpose. ServletResponse response) throws ServletException.RequestDispatcher for this purpose. which will then be responsible for any further processing and for generating the response.servlet.J2EE Servlets & JSP =========================================================================================================================== Request dispatching allows a servlet or a JSP page to dispatch a request to another servlet. this resource then takes over responsibility for producing the response.RequestDispatcher object can be used to dispatch requests to other servlets and JSP pages. this is request dispatching.

if you have a servlet /myWebApp/servlet1. you should specify the complete path relative to the root context.ServletContext requires the absolute path (that is. the getRequestDispatcher() method on javax. A javax. However. and the absolute path is /servlet/servlet2. The two getRequestDispatcher() methods accept an URL.servlet. The code of the HTML file is as follow: The HTML file <html> <head><title>Login Form</title></head> </body> <form action="testAlias" method="POST"> <BR><BR> Login <input type=text name=name> </BR><BR> Password <input type=password name=pass> <BR></BR><input type=submit value = Login> <input type=”reset” value=Cancel> </form> </body> </html> The Dispatch Servlet will do the following or including according to the parameters we pass through the text box in the HTML page. Example program for demonstrating the Servlet chaining is given below. Note that the target resource (except for static resources) should implement the same type of HTTP request that the original servlet receives.servlet.path referring to the target resource. and want to get the RequestDispatcher object for /myWebApp/servlet/servlet2.servlet.ServletRequest is associated with a URL path. the path name should be begin with a/).servlet. This is the same name that you specify the deployment descriptor in the<servlet-name> element. Here the root context is /myWebApp. In the above example. The HTML file with two fields name and password will be is posted to the Dispatch Servlet. you could now also servlet2 as the path. The Dispatch Servlet is as follows 33 . For example. and the web container can use this to resolve relative paths into absolute paths.ServletRequest accepts both absolute and relative paths. The getNameDispatcher () method is a convenience method that accepts a name associated with the servlet.J2EE Servlets & JSP ===========================================================================================================================  javax.ServletRequest method getRequestDispatcher(): public RequestDispatcher getRequestDispatcher(String path) Although these methods serve the same purpose. the usage depends on what information is available to you. The same method on javax.

} } The IncludeServlet is the Servlet which is the one when included in between when the condition satisfied .equals("Smitha")==false) { rd=req.*.forward(req.*. IOException { res.include(req.println("So it is forwarded to the Forward Servlet").getWriter ().HttpServletResponse res) throws ServletException.getParameter("pass"). The ForwardServlet.servlet.java import javax.HttpServletResponse res) throws ServletException.http. import javax. The IncludeServlet. } else { rd=req. } p.getRequestDispatcher("/include").getParameter("name"). String name=req.java is the Servlet to which the control is forwarded if the condition not satisfied.io. rd. String name=req. import javax.getParameter("name"). p. public void service (HttpServletRequest req.In this servlet the name alone is extracted and printed and the pass word will be printed in the calling servlet only. if (name.println("The password given is "+pass).io.println("The username given is "+name).servlet. rd.setContentType ("text/plain"). import java. p.res).http.java 34 . IOException { res. } } The ForwardServlet.setContentType ("text/plain").*.getRequestDispatcher("/forward"). PrintWriter p = res.*. import java. String pass=req.res).*. public class ForwardServlet extends HttpServlet { public void service (HttpServletRequest req.*.getWriter (). public class Dispatch extends HttpServlet { RequestDispatcher rd. PrintWriter p = res.J2EE Servlets & JSP =========================================================================================================================== import javax.servlet.servlet.

IOException { res. String name=req. PrintWriter p = res.servlet.*. import javax. public class IncludeServlet extends HttpServlet { public void service (HttpServletRequest req. 35 .getWriter ().servlet. p. } } The inputs and outputs can be verified from the following figures.*.io.http. import java.println("Back to the called servlet").HttpServletResponse res) throws ServletException.getParameter("name").*.J2EE Servlets & JSP =========================================================================================================================== import javax. p.println("The username given got in the Include page is "+name).setContentType ("text/plain").

36 . For the above input the control is forwarded to the ForwardServlet and the name is printed there in the ForwardServlet.J2EE Servlets & JSP =========================================================================================================================== For the above input the Include servlet is invoked in between and the output will be as above.

Whereas services force you to mix the code with the static content. JSPs can use beans with a specified scope to separate the code out. servlets tend to mix the dynamic content into the static part to generate HTML. In doing so. The resulting servlet is a combination of the HTML from the JSP file and embedded dynamic content specified by the new tags.1 Introducing JSP JSP is not a product but. JSPs are basically files that combine standard HTML 9or XML) and new scripting tags. or tag extensions. JSPs. or of custom tags that refer to externally compiled classes. on the other hand. by separating content and presentation. They execute on the server and intercept browser requests. which are covered in Chapters 12 and 13. are more in line with the J2EE model of separating static and dynamic content – separating presentation and logic – in a web application. a specification provided by Sun Microsystems for vendors to implement. acting as a sort of middle layer between clients and other applications.J2EE Servlets & JSP =========================================================================================================================== Chapter: 5 JAVA SERVER PAGES Topics Discussed      Introducing JSP The Nuts and Bolts JSP Directives The page Directive The Include Directive The taglib Directive Scripting Elements Declarations Scriplets Expressions Standard Actions The goal of the JavaServer Pages (JSP) specification is to simplify the creation and management of dynamic web pages. JSPs therefore look somewhat like HTML. (This is not to say that JSPs must contain HTML: a JSP page might be composed only of Java code. So what differentiates JSPs from servlets?   Servlets are Java’s answer to CGIs. 37 . like other Java APIs. but they get translated into Java services the first time they are invoked by a client. the JSP specification builds on the functionality provided by the servlet specification. That I the prime objective: Simplifying the dynamic presentation layer in a multi-tiered architecture.) In this chapter we will look at: 5.

an optional body. but an alternative XML-based syntax is also available. that even though JSPs contain special scripting tags.J2EE Servlets & JSP =========================================================================================================================== Keep in mind. The structure of a JSP page is a cross between a servlet and an HTML page. as we shall see in Chapters 12 and 13. toString() %> </body> </html> 5. with Java code enclosed between the constructs <% and %> and other XML-like tags interspersed. can be used (just as in HTML) if quotes are a part of the attribute value itself. which is not based on XML. JSP tags fall into three categories:  Directives: These affect the overall structure of the servlet that results from translation Scripting elements: These let you insert Java code into the JSP page (and hence into the resulting servlet) Actions: These are special tags available to affect the runtime behavior of the JSP You can also write your own tags. A simple JSP might look like this: <%@page import=”java. The special strings &apos.2 The Nuts and Bolts Let us jump head-on into writing JSPs. Tags based on XML syntax have either a start tag with optional attributes.util.    Some general rules are applicable to JSP pages:   JSP tags are case-sensitive. 38 . under the hood they are nothing but servlets. and &quot. either single or double quotes can be used. Directives and scripting elements have a syntax. or they have an empty tag (possibly with attributes – see example below):  <somejsptag attributename=”attribute value”> body </somejsptag> or: <somejsptag attributename=”attribute value” />  Attribute values in tags always appear quoted. and a matching end tag.Date”%> <html> <body> The current time is <%=new Date().

The value is a fully qualified class name of the superclass that the generated) must extend. Directives have scope for the entire JSP file.J2EE Servlets & JSP ===========================================================================================================================  Any whitespace within the body text of a document is not significant. in other words.1 The page Directive The page directive is used to define and manipulate a number of important page-dependent attributes that affect the whole JSP (the entire compiled class file). A page can contain any number of page directives. (An exception is the import attribute: there can be multiple imports. there can be only one occurrence of any attribute/value pair defined by the page directives in a given JSP. URLs used by JSPs follow servlet conventions. a directive affects the whole JSP file. to use %. and a URL starting with a /.. however. and communicates these attributes to the JSP container. Directives start with <%@ and end with %>.  The character \ (backlash) can be used as an escape character in a tag (for example.) If the URL does not start with a / it is interpreted relative to the current JSP. etc. anywhere in the JSP. as well will see later. They are used to set global values such as class declarations.3.) The general syntax of the page directive is: <%@ page ATTRIBUTES %> where the valid attributes are name value pairs as described overleaf: Attribute language extends Description Defines the scripting language to be used.3 JSP Directives JSP directives serve as message sent to the JSP container from the JSP. but only that file. the general syntax is: <%@ directivename attribute=”value” attribute=”value” %> There are three main directives that can be used in JSP:    The page directive The include directive The taglib directive 5. the sequence \ % can be used). in any order.   5. (The ServletContext is available as an implicit object within JSP pages. methods to be implemented. output content type. For future use if JSP containers support multiple languages. They are all assimilated during translation and applied together to the page. Default value “Java” Omitted by default 39 . and do not produce any output to the client. but is preserved during translation into a servlet. is interpreted with reference to the web application to which the JSP page belongs. called a context-relative path.

Defines an informative string that can subsequently be obtained from the page’s implementation of the Servlet.getServletInfo() method. Omitted by default “true” buffer Implementation dependent. then no buffering occurs and all output is written directly through to the ServletResponse by a PrintWriter. and only used with extreme caution. If “false”. and processes them one at a time. because JSP engines usually provide specialized super-classes with a lot of functionality to be extended by the generated servlet classes. When “true” the implicit object named session (which refers to the javax. Defines the level of thread safety implemented in the page. If “false” then the JSP processor queues up client requests sent to the page for processing. If the value is “none”.HttpSession) is available and can be used to access the current/new session for the page.J2EE Servlets & JSP =========================================================================================================================== import session This attribute should normally be avoided. the output buffer to the client is flushed automatically when it is full. a runtime exception is raised to indicate buffer overflow. just like import statements in usual Java code. Use of the extends attribute restricts some of the decisions that a JSP container can make.servlet. in the order they were received.SingleThreadModel interface in a servlet. at least 8kb autoFlush “true” isThreadSafe “true” info Omitted by default errorPage Omitted by default 40 . Specifies whether the page participates in an HTTP session. If a buffer size is specified (such as “24kb”) then output is buffered with a buffer size not less than that value. If “true”. If the value is “true” the JSP engine may send multiple client requests to the page at the same time.http. Comma separated list of packages or classes. Specifies the buffering model for the output stream to the client. This is the same as implementing the javax. Defines a URL to another JSP page.servlet. If “false’. the page does not participate in a session and the implicit session object is unavailable.

jsp. must be the OIANA value for a character encoding. See the isErrorPage attribute below. the default value for the CHARSET is ISO-8859-1. CHARSET.J2EE Servlets & JSP =========================================================================================================================== isErrorPage which is invoked if an unchecked runtime exception is thrown.2 The Include Directive The include directive instructs the container to include the content of the resource in the current JSP. Example The following JSP.util. contains an attribute-rich page directive: <%@ page language=”Java” import=”java. pageDirective. “false” contentType The default value for the MIMETYPE is text/html. if specified. charset=CHARSET” with an optional whitespace after the’. java. in the JSP in place of the directive. </body> </html> 5.lang.Throwable thrown at run-time by the JSP causing the error. If “true”. inline. This can have either the form “MIMETYPE” or “MIMETYPE.rmi. The page implementation catches the instance of the Throwable object and passes it to the error page processing. Indicates if the current JSP page is intended to be another JSP page’s error page.3. then the implicit variable exception is available and refers to the instance of the java. Of course the file specified should be accessible and available to the JSP container. by inserting it.jsp” isErrorpage=”false” isThreadSafe=”false”%> <html> <head> <title>Page directive test page</title> </head> <body> <hl>Page directive test page</hl> This is a JSP to test the page directive.*.*” session=”true” buffer=”12kb’ autoFlush=”true” info=”my page directive jsp” errorPage=”error. Unrecognized attributes result in fatal translation errors. Defines the character encoding for the JSP and the MIME type for the response of the JSP page.”. 41 . or character encoding.

<html> <head> <title>Include directive test page 1</title> </head> <body> <h1>Include directive test page 1</h1> <%@ include file="included. The server may. compilation. Example The included file can be either a static file (such as an HTML file) or another JSP.jsp.html"%> </body> </html> included. includeDirective. however. the resulting output is as follows: during 42 . file. choose whatever mechanism it prefers to read the included file. of a copyright file containing HTML legal disclaimers.html contains the following: <font color="red" size="12"> This is the content from the included HTML page <font> On placing both these files in the C:\ProJavaServer\Chapter8\JSPExamples directory and requesting http://localhost:8080 /JSPExamples/includeDirective.jsp. requests the inclusion.J2EE Servlets & JSP =========================================================================================================================== It is important to note that the content of the included file is parsed by the JSP and this happens only at translation time (when the JSP page is compiled into a servlet). The syntax of the include directive is: <%@ include file=”Filename” %> The only available attribute. as we will see later. The example below. The include action is used to include resources at runtime. specifies the filename of the file to include. Most JSP containers usually keep track of the included file and recompile the JSP if it changes (they may choose not to recompile).

save both these files to the C:\ProJavaServer\Chapter8\JSPExamples directory. The result on requesting http://localhost:800/JSPExamples/includeDirective2.jsp is: When includedirective2.Date” %> Current date is <%= new Date() %> Again. striped of comments. out. jsp: <html> <head> <title>Include directive test page 1</title> </head> <body> <h1>Include directive test page 1</h1> <%@ include file="included.html"%> </body> </html> The included JSP included.J2EE Servlets & JSP =========================================================================================================================== The new example shows how a JSP can be included.util.print (“ + new Date()). out. looks like this: out. out.jsp is translated.print (“Current date is “ ). Consider the file includeDirective2.write (“\r\n </body<\r\n</html>\r\n”).\r\n <title>Include directive test page 2</title>\r\n </head>\r\n <body>\r\n <h1>Include directive test page 2</h1>\r\n\r\n “). out.write(‘\r\n”). out. the relevant portion of the resulting servlet code. 43 .write (“\r\n).write(“<html>\r\n <head.jsp is: <%@ page import=”java.

Tag libraries are a very powerful. 5. 5. A tag library descriptor is used to uniquely name the set of custom tags and tells the container what to do with the specified tags. and will be covered in detail in coming Chapters. For example if this value is mytag then when the container comes across any element that starts like <mytag:tagname … /> in the JSP. concept. The syntax of the taglib directive is: <%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %> and the available attributes are: Attribute uri Description A URI (Uniform Resource Identifier) that identified the tag library descriptor. java. Declarations are initialized when the JSP page is initialized.3.4. it references the tag library descriptor specified in the URI. Defines the prefix string in prefix:tagname that is used to define the custom tag.3 The taglib Directive The taglib directive allows the page to use tag extensions (customs tags) – see Chapters 12 and 13. and have `class’ scope in the generated servlet. 44 . scriptlets (arbitrary Java code). and expressions – to be inserted into your JSP page. and often misunderstood. jspx.4 Scripting Elements JSP scripting elements allow java code – variable or method declarations. The prefixes jsp. sun. servlet.1 Declarations A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated servlet. The engine uses this tag library to find out what to do when it comes across the custom tags in the JSP. and sunw are reserved. so that anything defined in a declaration is available throughout the JSP to other Default value Not specifying a value causes a compilation error tagPrefix Not specifying a value causes a compilation error. It names the tag library that contains compiled Java code defining the tags to be used.J2EE Servlets & JSP =========================================================================================================================== You can see that the code from the included file has been inlined into the translated servlet. javax. 5.

J2EE Servlets & JSP =========================================================================================================================== declaration. When declaration. declaration. public String sayHello(String name) return "Hello.*. // … more import statements 45 . the output is as follows: { %> The generated servlet contains the declarations code: import javax.jsp: <%! int numTimes = 3. </p> </body> </html> This declares an int variable called numTimes. A declaration block is enclosed between <% ! and %> and does not write anything to the output stream. " + name + " ! " . expression elements (to be shortly) are used to return the value of numTimes to the browser and to invoke the sayHello () method.jsp is saved to the C:\ProJavaServer\Chapte8\JSPExamples directory and http: // localhost. and a sayHello () method that greets the requested person. 8080/JSPExamples/declaration. Further down the page. jsp is requested.</p> <p>Saying hello to reader: " <%= sayHello("reader") %>".servlet. expressions. } %> <html> <head> <title>Declaration test page </title> </head> <body> <h1>Declaration test page</h1> <p>The value of numTimes is <%= numTimes %>. and code. The syntax is: <%! Java variable and method declaration(s) Example Consider the simple JSP below.

Multiple scriptlets are combined in the generated servlet class in the order they appearing the JSP. ( 5.println ("<b>Hello World.jsp. i++) { out. “ + name + “ !” . public String sayHello (String name) return “Hello. In Tomcat.4.out.jsp below. to the console window within which Tomcat is running). in the order in which it appeared. The syntax for scriplets is: <% Valid Java code statements %> Example In scriplet. } // More generated code.out stream " + i). Scriptlets. and can include producing output for the client.i< 10. and is enclosed between <% and %> tags.2 Scriptlets A scriptlet is a book of Java code that is executed during the request-processing time. The output to the browser window should be: 46 . It is therefore processed for every request that the servlet receives.out stream (in other words. This is a scriptlet test " + i +"</b><br>").J2EE Servlets & JSP =========================================================================================================================== public class 0002fdeclaration0002ejspdeclaration_jsp_1 extends HttpJspBase ( int numTimes = 3. can modify objects inside them as a result of method invocations. like any other Java code block or method. System.println ("This goes to the System. printing out a message each time to the browser window (using the implicit object out) and to the System. } %> </body> </html> Save scriplet. as is. a scriptlet executes a loop 10 times. all the code appearing between the <% and %> tags in the JSP gets put into the services() method of the servlet. <html> <head> <title>Scriptlet test page</title> </head> <body> <h1>Scriptlet test page</h1> <% for(int i=0.jsp to the C:\ProJavaServer\Chapter1\JSPEampales\directory and request http://localhost:8080/JSPExamples/scriptlet. What the scriptlet actually does depends on the code itself.

The syntax is: <%= Java expression to be evaluated %> Example Consider the example JSP overleaf (expression. If the result of the expression is an object.4. the conversion is done by using the object’s toString() method. scriptlets. and the result is converted to a String and displayed. which sets up a simple counter and shows declarations.jsp – again. The expression is evaluated at HTTP request processing time. An expression is enclosed in the <%=and%> tags.3 Expressions An expression is a shorthand notation for a scriptlet that sends the value of a Java expression back to the client. save it in C:\ProJavaServer\Chapter8|JSPExamples). and expressions working together: <html> <head> <title>Expression test page</title> </head> <body> <h1>Expression test page</h1> <%! int i=0 . %> <% i++. %> Hello World! <%= "This JSP has been accessed " + i + " times" %> </body> </html> 47 .J2EE Servlets & JSP =========================================================================================================================== 5.

an expression is used to printout the value of I. irrespective of the implementation. The standard action types are:        <jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:param> <jsp:include> <jsp:forward> <jsp:plugin> 48 . and includes the output produced by myjsp.J2EE Servlets & JSP =========================================================================================================================== An int variable is declared. We will examine the semantics of this action in detail in a while.5 Standard Actions Standard actions are tags that affect the runtime behavior of the JSP and the response sent back to the client. jsp. They have to be provided by all containers. the container comes across this tag and replaces it with Java code the corresponds to the required predefined task. For example when it comes across the standard include action. the browser will display. Finally. and initially has the value 0. together with some surrounding text. 5. compiles it (if necessary). in place of the action tag. Each time this instance of the generated servlet is called (when the browser requests http://localhost:8080\JSPEamples\expression.jsp” flush=”true” /> it takes the JSP myjsp. During compilation into a servlet. jsp) the variable is incremented by the scriptlet. <jsp:include page=”myjsp. Effectively. The standard actions serve to provide page authors with basic functionality to exploit for common tasks.jsp in the response. a standard action is a tag that can be embedded in a JSP page. After this JSP has been requested a number of times.

it would be a good idea to encapsulate the code in a Java object (a JavaBean).5. We can also specify the lifetime of the object by giving it a specific scope (we cover this later in detail).Beans class. The <jsp:useBean>. The fully qualified class name. and assigns it to a variable name (or id). and then instantiate and use this object within our JSP. and <jsp:getProperty> tags assist with this task.beans. in the appropriate scope as specified in the tag. or even from other JSPs. depending on the scope. and ‘application”.c. or locates an existing bean instance. The syntax for the <jsp:useBean> action is: <jsp:useBean id=”name” scope=”scopeName” beandetails where and beandetails is one of:     /> class=”className” class=”className” type=”typeName” beanName=”beanName” type=”typeName” type=”typeName” The attributes available are: Attribute id scope Description The case sensitive name used to identify the object instance. “request”.’. 9See the javaBeans specification for more details.” is either a class.1 jsp:useBean To separate code from presentation. These values will be explained shortly. The scope within which the reference is available. and a Default values No default value “page” class beanName No value No value default default The beanName follows the standard bean specification and can be of the form “a. The object can be referenced using as associated id from within the JSP. with the specified id. or the name of a serialized resource in which case it is resolved as ‘a/b/c. where “a.b.)s 49 .J2EE Servlets & JSP =========================================================================================================================== 5.er”. <jsp:setProperty>.c. and omit the class attribute. </jsp:useBean> ensures that the object is available. as you would supply to the instantiate() method in the java. “session”. The <jsp:useBean> action is used to instantiate a JavaBean. It is permissible to supply a type beanName. The name of a bean.b. Possible values are “page”. This attribute can also be a request time expression.

the new object reference is associated with the given id. If the object is found. in the specified scope. If the request is forwarded to another JSP using the <jsp:forward> action. but in brief:  Page scope means that the object is associated with this particular request to this page.Beans is invoked. and follows standard java casting rules. If a new bean instance has been instantiated and the <jsp:useBean> element has a non-empty body. If the object is not found in the specified scope.      The meanings of the possible values of the scope attribute will be covered in more detail shortly. if the object is not of this type then java. with the beanname as an argument. if necessary. in the specified scope. and no class or beanName is specified in the tag. session scope means that the object will be available during any requests made by the name client within the current session. application scope means that the object will be available in any JSP page with the same web application. in the specified scope.    50 . or the bean’s class itself. If the object is not found in the specified scope and a beanName is specified. and the class can be instantiated. the object will available. the body is processed. an InstantiationException is thrown. Scriptlets or the <jsp:setProperty> standard action can be used to initialize the ban instance. during this processing the new variable is initialized and available.ClassCastException can be thrown at request time.lang. or if another JSP is included using the <jsp:include> action. then this is done. The type implemented by it. the container tries to cast the found object to the specified type. request scope means that the object is associated it this particular client request. If this fails then an InstantiationException is thrown. Just like any casing operation. If this method succeeds.J2EE Servlets & JSP =========================================================================================================================== type This optional attribute specifies the type of the scripting variable to be created. A ClassCastException is thrown if the cast fails. and a reference to the object is associated with the given id. and a type has been specified in the tag. The value of the class attribute Let us examine the underlying semantics that occur because of this tag in the order they occur:  The container tries to locate an object that has this id.beans. If the object is not found in the specified scope. then the instantiate(1) method of java.

to set the value of bean properties. <jsp:setProperty name=”help” property=”word” /> The <jsp:setProperty> action uses bean introspection to discover what properties are present. We will see an example of the <jsp:useBean>action once we have looked at <jsp:setProperty> and <jsp:getProperty>.5. their names.2 jsp:setProperty The <jsp:setProperty> standard tag is used in conjunction with the <jsp:useBean> action described in the proceeding section.class file either under the WEB-INF\classes directory in your web application. and their accessor and mutator methods. The properties in a bean can be set either:    At request time from parameters in the request object At request time from an evaluated expression From a specified string (or hard coded in the page) When setting bean properties from the request object. place the compiled . Bean properties can be either simple or indexed. The syntax of the <jsp:setProperty> action is: <jsp:setProperty name=”beanName” propertydetails when propertydetails is one of:     /> property=”*” property=”propertyName” property=”propertyName” param=”parameterName” property=”propertyName” value=”propertyValue” and propertyValue is a string or a scriptlet. The attributes are: 51 . If you are creating a bean of a class you have written yourself. their type. whether they are simple or indexed. or in a JAR file in the WEB-INF\lib directory. 5. the JSP can choose to set all properties in the bean via the standard action: <jsp:setProperty name=”help” property=***/> or a single property can be set explicitly by an action such as.J2EE Servlets & JSP =========================================================================================================================== The container looks for the Java class you specified in the CLASSPATH for that web application.

if it is a primitive. request-time expressions can be assigned to properties of any type. If there is no request parameter with this name.lang. Converts the value directly to a String.valueOf (String) method is used. in which case the bean property is left unaltered. and prints to the output stream to the client.println() method. it is assumed that the request parameter and the bean property have the same name. unless a request parameter has the value “”.setProperty> and the one for <jsp:useBean> must be the same. This can be a request-time attribute.5. The value to assign to the bean property. it is not necessary for the bean have the same property names as the request parameters. the tag looks through all the parameters in the request object and tries to match the request parameter names and types to property names and types in the bean. or it can accept an expression as its value. (A tag cannot have both param and value attributes. or if it has the value “ “. conversion is applied using the standard Java conversion methods. the action has no effect on the bean. the action:   Invokes the toString () method on the property. However. if a bean property is of type double or Double the java.3 jsp:getProperty The <jsp:getProperty> action is complementary to the <jsp:setProperty> action. and is used to access the properties of a bean. The name of the bean property whose value is being set. To convert the property to a String. and the container performs no conversion.) param value When properties are assigned from String constants or request parameter values. using the valueOf() method of the corresponding wrapper class for the primitive type This is just like the behavior of Java’s System. 5. for example. the value must be an array. which must already have been defined by a <jsp:useBean> tag. If the param value is not specified. It accesses the value of a property. if it is an object. This attribute is used to specify the name of the request parameter whose value you want to assign to a bean property. The values in the request are assigned to each matching bean property.Note that the name is <jsp. converts it to a String. 52 . When setting bean properties from request parameters.J2EE Servlets & JSP =========================================================================================================================== Attribute name property Description The name of a bean instance. If the property attribute has the value “ * “.Double.out. For indexed properties.

Having seen the <jsp:useBean>.html.</p> <p>Your favorite language is <jsp:getProperty name="languageBean" property="language" />. <input type="text" name="name"> <br>What is your favorite programming language? <select name="language"> <option value="Java">Java <option value="C++">C++ <option value="Perl">Perl </select> </p> <p><input type="submit" value="Submit information"> </form> </body> </html> This sends a POST request to beans. Of course. The HTML form page.jsp"> <p>Please enter your username. beans.beans1.LanguageBean"> <jsp:setProperty name="languageBean" property="*" /> </jsp:useBean> <html> <head> <title>useBean action test result</title> </head> <p>Hello.jsp language. you must create a bean before using <jsp:getProperty>. is very simple: <html> <head> <title>useBean action test page</title> </head> <body> <h1>useBean action test page</h1> <form method="post" action="beans1. Our example will ask the user for their name and their favorite programming language.J2EE Servlets & JSP =========================================================================================================================== The syntax is: <jsp:getProperty name=”name” property=”propertyName” and the available attributes are: Attribute name property /> Description The name of the bean instance from which the property is obtained. let’s build a simple example using all three. <jsp:getProperty name="languageBean" property="name"/>. </body> 53 . <jsp:setProperty>. this is the instance variable in the bean. Names the property to get. and then issue a verdict on their choice. by using <jsp:useBean> or by instantiating the object by a new operator. two parameters: name and <jsp:useBean id="languageBean" scope="page" class="bean1. and<jsp:getProperty> actions.jsp is also quite simple.

public LanguageBean(){} public void setName (String name) { this.java to C:\ProJavaServer\Chapter8\JSPExamples\src. simple class with a no-argument constructor. private String languageComments. It can then use the <jsp:getProperty> action to retrieve the values of these properties. } public void setLanguage (String language) { this. and uses the property=”*” form of the <jsp:setProperty> action to set the bean’s name and language properties. beans .\WEB-INF\classes LanguageBean. and also the languageComments property.. } public String getName() { return name. and languageBean.jsp and beans . } } This is a nice.java from the src directory.jsp to C:\ProJavaServer\Chapter8\JSPExamples.jsp creates an instance of LanguageBean with page scope.name = name.language = language. This last method uses the value of the language property to issue some comments on the user’s chosen language – this is invoked by the <jsp:getProperty name=”languageBean” property=”languageComments”/> action in beans. and also a getLanguageComments () method. } public String getLanguage() { return language.html: 54 .J2EE Servlets & JSP =========================================================================================================================== </html> All the Java code has been removed to the LanguageBean class. private String language. Finally. Save beans. Compile the bean into C:\ProJavaServer\Chapte8\JSPExamples\WEB-INF\classes (create this directory first) by running the command: javac -d . Then point your browser at http: // localhost: 8080/JSPExamples/beans. set and get methods for the name and language properties. public class LanguageBean { private String name. the source of LanguageBean is as follows: package bean1.jsp.

. The syntax is: <jsp:param name=”paramname” value=”paramvalue” and the available attributes are: /> 55 .4 jsp:param The <jsp:param> action is used to provide other tags with additional information in the form of name-value pairs.<jsp:forward>. Removing the logic to the languageBean class has made our JSP page much more readable.5. 5. then click the Submit information button: The advantage of this approach over that used in previous examples (in which we freely mixed Java code and HTML) should be clear.J2EE Servlets & JSP =========================================================================================================================== Enter your name and choose your favored language. and its use is described in the relevant sections that follow. and more easily edited by someone who is a skilled web designer but does not understand the details of Java programming. It is used in conjunction with the <jsp:include>. and <jsp:plugin> action.

1 this value must always be “true”. if the request has a parameter paraml=myvalue1.RequestDispatcher’s include () method. The augmented attributes can be extracted from the request using the getParameter (String paramname) method in the javax. For example.ServletRequest interface. and it cannot set headers or cookies. If the value is “true”. The syntax of the <jsp:include> action is: <jsp:include page=”URL” flush=”true” or: <jsp:include page=“URL” flush=“true”> <jsp:param name=“paramname” value=“paramvalue” /> … </jsp:include> the attributes of the <jsp:include> action are: Attribute filename flush Description The resource to include. and precludes the included page from containing general JSP code. myvalue1. The value of the attribute. An included page has access to only the JspWriter object. and the new parameters specified using the <jsp:param> tag. In JSP 1.servlet. (Attributes are key-value pairs. the old values are kept intact.J2EE Servlets & JSP =========================================================================================================================== Attribute name value Description The key associated with the attribute. providing additional name-value pairs.servlet. the request received on the second JAP will have param=myvalue2. to be included in the current JSP at request processing time. and “false” is not supported. 5. The included page can access the original request object.5. but the new values take precedence over the existing values. /> A <jsp:include> action may have one or more <jsp:param> tags in its body. It is important to understand the difference between the include directive and this include action. If the parameter names are the same. The URL format is the same is described earlier for the include directive. This constraint is equivalent to that imposed on javax. If the page output is buffered then the buffer is flushed prior to the inclusion. The include action pays a small penalty in efficiency. specified by a URL. and a parameter param1-myvalue2 is specified in the <jsp:param> tag.5 jsp:include This action allows a static or dynamic resource. A request-time exception will be thrown if this is attempted. the buffer in the output stream is flushed before the inclusion is performed. the difference is summarized in the table below: Include Syntax Done when Included Parsing 56 . which is what servlets use if they want to do this type of inclusion. which will contain both the original parameters.

html" %> <%@ include file="include2.html" flush="true" /> <jsp:include page= "include2.util. Let’s look at an example.jsp" %> <h2>Using the include action</h2> <jsp:include page="include2.html: <p>This is some static text in the html file</p> and include2.\PreoJavaServer\Chapter8\JSPExamples and requesting http://locahost:8080/JSPExamples/includeAction. The JSP below. Use the include action when the resource is frequently changing or is dynamic.jsp: <%@ page import="java. for both a static and a dynamic resource: <html> <head> <title>Include Action test page</title> </head> <body> <h1>Include Action test page</h1> <h2>Using the include directives</h2> <%@ include file="include2. includeAction. The include action includes files at request-processing time. we get: 57 .jsp" flush="true" /> </body> </html> The two included files are include2.jsp.jsp. shows both the include types. Use the include directive if your resource is not going to change frequently.Date" %> <%= "Current date is " + new Date() %> Saving these files in C.J2EE Servlets & JSP =========================================================================================================================== type directive action <%@ include file=”filename” %> <jsp:include page=” filename” /> Compilation time Request processing time content Static Static Dynamic or Parsed by container Not parsed but included in place The include directive lets you include resources into multiple pages but requires you to update the modification date on the pages doing the include if the resource changes (in other words the container has to translate them again to reflect the changes).

{ String _jsqpx_qStr = “ “. out. pageContext.write (“\r\n “).write (“r\n”).\r\n <title>Include Action test page</title>\r\n <head>\r\n <body>\r\n <h1>Include Action test page</h1>\r\n\r\n <h2>Using the include directives</h2>\r\n\r\n “). out.J2EE Servlets & JSP =========================================================================================================================== Even though the output from the two types of includes may look identical. // … public void _jspService (HttpServletRequest request. out.html” + _jspx_qStr).write (“<h3>This is some static text in the html file</h3>”). //… } The highlighted lines in the above code show how the container in-lines the resources for the include directive. HttpServletResponse response) throws IOException. out.html so that it contains: 58 . Change include2. and invokes them dynamically for the include action. out.print ( “Current date is “ + new Date() ).flush() . ServletException { // … out. } out. { String _jspxqStr = “ “. see what happens when the included resources are changed (without changing the parent JSP that includes them).flush().html” + _jspx_qStr).include (“include2.write (“\r\n\r\n </body>\r\n<html>\r\n). Let us look at an excerpt from the generated servlet class.write (“\r\n\r\n <h2>Using the include action</h2>\r\n\r\n “). To reiterate the difference. } out. pageContext.include (“include2. out.write (“<html>\r\n <head. tidied up a little. out.write (“\r\n “). there is a subtle difference.

jsp) has not changed and hence is not recompiled. and some output has been written to it.IllegalStateException.lang. the output now looks like this The parts included using the include directive are not altered. depending on the intercepted request.servlet.J2EE Servlets & JSP =========================================================================================================================== <p>This is some new text in the html file</p> and change icnlude2. the parts included using the include action are changed. or to a static resource.jsp so that its contents are now: <p>This is the new JSP</p> When the page is requested again. a <jsp:forward> action will throw a java. This is particularly useful when you want to separate the application into different views. to a servlet. 59 . the buffer is cleared. The behavior of this action is exactly the same as the forward () method of the javax. If the output stream was not buffered. We saw this design approach with servlets in Chapter 9. and will see more of it later in this chapter. because the parent JSP (includeAction. because the include action performs the inclusion afresh each time the parent JSP is requested. Execution in the current JSP stops when it encounters a <jsp:forward> tag. however. The syntax is: <jsp:forward page=“URL” /> <jsp:forward page=“URL”> <jsp:param name=”paramname” value=paramvalue” … </jsp:forward> /> The resource to which the request is being forwarded must be in the same context as the JSP dispatching the request.5. 6 jsp: forward The <jsp:forward> action allows the request to be forwarded to another JSP. and the request is modified (this is a server-side redirect and the response buffer is cleared when it is processed) to assimilate any additionally specified parameters in the same way as described for the <jsp:include> action.RequestDispatcher. 5.

equals ("Richard")) && (request.html" <% } %> The checks whether the username and password are acceptable to the system.jsp presents the successfully logged-in user with a welcome page. is straightforward.jsp is the first JSP page we have seen that contains no HTML code: <% if ((request. Since the original request. including the form parameters.equals ("xyzzy"))) { %> <jsp:forward page="forward2.jsp" <% } else { %> %> /> <%@ include file="forward. has been forwarded to this JSP.jsp: <html> <head> <title>Forward action test page</title> </head> <body> <h1>Forward action test page</h1> <form method="post" action="forward. forward2. if the login attempt fails. sending a POST request to forward.getParameter ("password"). it uses the include directive to present the login form to the user again. and the whole application would probably be secured using HTIPS. in forward.html. Finally. the Java code would be removed to a JavaBean or a tag extension.J2EE Servlets & JSP =========================================================================================================================== Let’s see a simple example of the <jsp:forward> action in use – a simple login form. we can use the request object to display the user’s name: <html> <head> 60 .getParameter ("username").jsp"> <p>Please enter your username: <input type="text" name="username"> <br>and password: <input type="password" name="password"> </p> <p><input type="submit" value="Log in"> </form> </body> </html> forward . The login form itself. and if so forwards the request to forward2.jsp. In a real-world example the password-checking code would check against a database or a JNDL server.

the login form is displayed again. we get to this page: If any other username or password is entered.getParameter("username") %> </body> </html> Save all these files in C:\ProJavaServer\Chapter8|JSPExamp[les and request http://localhost:8080/JSPExamples/forward.J2EE Servlets & JSP =========================================================================================================================== <title>Forward action test: Login successful!</title> </head> <body> <h1>Forward action test: login successful</h1> <p>Welcome. <%= request. 61 .html: Entering the username Richard and the password xyzzy.

or an Applet Same as HTML syntax Same as HTML syntax Same as HTML syntax Same as HTML syntax Same as HTML syntax Required Yes Yes No No No No. to pass additional parameters to the Applet or JavaBeans component. <jsp:fallback>.  The available attributes for the <jsp:plugin> tag are: Attribute type code codebase align archive height Details Identifies the type of the component: a Bean. The <jsp:fallback> tag does that the HTML ALT attribute and <NOFRAMES> tag do. etc. These abstractions encapsulate the object’s implementation.6 Implicit Objects The Servlet API includes interfaces that provide convenient abstractions to the developer. but some browsers do not allow an object of zero height due to security issues No No hspace jreversion Same as HTML syntax The Java runtime environment version needed to execute this object Default is “1.7 jsp:plugin The <jsp:plugin> action is used in pages to generate client browser specific HTML tags (<OBJECT> or <EMBED>) that result in the download of the Java Plug-in software. to specify the content to the displayed in the client browser if the plugin cannot be started because the generated tags are not supported. but some browsers do not allow an object of zero width due to security issues No iepluginurl be No 5. The <jsp:plugin> tag can optionally have two additional support tags: <jsp:param>. such as HttpServletRequest. followed by the execution of the applet or JavaBeans component that is specified in the tag. the 62 . HttpSession.5.J2EE Servlets & JSP =========================================================================================================================== 5. if required.1” Same as HTML syntax Same as HTML syntax Same as HTML syntax Same as HTML syntax name vspace title width nspluginurl URL where Java plugin can downloaded for Netscape Navigator Default is implementation defined URL where Java plugin can downloaded for Internet Explorer Default is implementation defined be No No No No. HttpServletResponse. for example.

the object itself will be a protocol and implementations-specific subclass of javax. etc. and has session scope. you have used a session=”false” attribute in the page directive. of course. The pageContext Object The pageContext object provides a single point of access to many of the page attribute and is a convenient place to put shared data within the page. Again.jsp. It has page scope. since the output stream is buffered).HttpSession. Sessions are created automatically. and has page scope.and implementation-specific subclass of javax. These objects are accessed using standard variables. and provides convenient methods like getParameter().ServletResponse. It has request scope. form parameters.servlet. It is the HttpServletRequest that provides access to the incoming HTTP headers (for example.J2EE Servlets & JSP =========================================================================================================================== HttpServletRequest interface represents the HTTP data sent from the client along with headers.http. and are automatically available for use in your JSP writing any extra code. The response Object The response object is the HttpServletResponse instance that represents the server’s response to the request. Strictly speaking.. The implicit objects available in a JSP page are:         request response pageContext session application out config page The request Object The request object represents the request that triggered the service() invocation. request type (GET/POST). strictly speaking. It is of type javax.servlet.ServletRequest. and getHeader() that extract relevant data from the request. based on the servlet API. in which case variable will not be available). and this variable is available even when there is no in-coming session (unless. among other things. JSP provides certain implicit objects. 63 . for cookies). but few of any). the object itself will. and request parameters.PageContext. It is legal to set HTTP status codes and headers in the JSP page once output has been sent to the client (even though it is not permitted in servlets.servlet. JSP containers currently support non-HTTP servlets. The session Object The session object represents the session created for the requesting client. It is of type javax.servlet. be a protocol.

PageContext. It is of type javax. a servlet executes in a context (an instance of ServletContext. Everything that the servlet needs to know about its server can be extracted from this context.servlet. and everything the server wants to communicate to the servlet goes through the context. this is a buffered version of the java.JspWriter.servlet. as it may span several client requests and pages. the session object has a scope. A context provides an invisible container for resources. JSP scopes internally rely on contexts. for example. The page object can be thought of as a synonym to this within the page. and an interface for them to communicate with the environment. To make the response object useful.io. For example. A rule of thumb: Everything in JSP is associated with a context. and from which JSPs. the object will be available. It is of type java. and every context has a scope. and has page scope.ServletContext and has application scope. in fact). which exceeds that of a page. and is of type javax. It is of type javax. What happens when a bean tag is compiled for the different values of scope can be seen below: Page Scope An object with page scope is bound to the javax. The page Object The page object is the instance of the page’s implementation servlet class that is processing the current request.jsp. 5.ServletConfig.Object.7 Scope The scope of JSP objects – JavaBeans and implicit objects – is critical.jsp. for as long as this page is responding to the current request.servlet.lang.J2EE Servlets & JSP =========================================================================================================================== The application Object The application object represents the servlet context. as it defines the how long. The out Object The out object is the object that writes into the output stream to the client.servlet. The config Object The config object is the ServletConfig for this JSP page. The application object can provide services to a group of JSP pages that together represent a web application.PrintWriter class. The buffer size can be adjusted via the buffer attribute of the page directive. and has page scope. obtained from the servlet configuration object. This is relatively simple – It means that the object is placed in the PageContext object. An object 64 .

and can be accessed by invoking the getValue() methods on the implicit session object. The underlying. 65 . passed to the PageContext and made available to the JSP. Object value) method in the HttpServletRequest.servlet. a session always ran under a separate session context. This too is transparent to the JSP author. Application Scope Application scope means that the object is bound to the javax. even if the request is forwarded to different pages. all clients access the same object as they all access the same ServletContext. This is not unique to individual clients and. Session Scope An object with session scope is bound to the javax. The object is distinct for every client request (in other words it is created afresh and destroyed for each new request). Request Scope request scope means that the object is bound to the javax.() methods on the implicit application object This is the most persistent scope.ServletRequest. an implementation for the HttpSessionContext interface is still available on most servers.jsp. when the page is fully processed by the servlets generated from the JSP). this is transparent to the JSP author. The object reference is available as long as the HttpRequest object exists. The generated servlet relies on binding the object to the HttpSession using the setAttribute (String key. (Though deprecated for security reasons.ServletContext. and can be accessed by invoking the getAttribute() methods on the implicit request object. When generating the servlet.service() (in other words. Object value) method in the ServletContext. and is available as long as the client’s session is valid. This is the default scope for objects used with the <jsp:useBean> action. It allows you to get a list of sessions or a particular session by its ID – and that’s not really that secure.) These days. The object is distinct for every client.PageContext. the only session ID you can get at is the one that’s part of the request from the client. consequently. Object value) method. The object reference is discarded upon completion of the current Servlet. An object with this scope can be accessed by invoking the getAttribute. This object is created and destroyed for each client request to the page.servlet. the servlet engine creates an object in the service() method which follows the usual object scope conversion in java. In earlier implementations of the servlet API.servlet.J2EE Servlets & JSP =========================================================================================================================== with this scope can be accessed by invoking the getAttribute() methods on the implicit pageContext object. The generated servlet relies on binding the object to the ServletContext using the setAttribute (String key. generated servlet relies on binding the object to the HttpServletRequest using the setAttribute (String key. or if the <jsp:include> action is used.

BodyContent Class Convenlence Classes The javax. They have a special meaning to a JSP engine at translation time. XML) tags embedded in a JSP page.jsp.jsp.TagExtraInfo Class Objects Available to Tag Handlers The Simple Example Revisited Tag Library Descriptors Using Tag Extensions in JSP Pages Deploying the Packaging Tag Libraries No Packaging WAR From the point of view of the JSP developer. However.Jsp. and enable application functionality to be invoked without the need to write Java code in JSP scriptlets.BodyTag Interface The javax.servlet.servlet. the only significant new feature of JSP 1.1 is support for tag extensions (often referred to as customs tags). 66 . Well-designed tag extension libraries can enable application functionality to be invoked without the appearance of programming. Tag extensions look like HTML. So in this chapter.Tag Interface The javax. this proves to be very significant indeed. we’ll look at the basis of writing your own tags and then in the next chapter we’ll look at some more advanced examples.servlet.servlet. (or rather. So in this chapter we will cover:     Tag extension basics The anatomy of a tag extension How do deploy a tag library How to write custom tag extensions Let’s get started then with what tag extensions are all about.J2EE Servlets & JSP =========================================================================================================================== Chapter: 6 CUSTOM TAGS IN JSP Topics Discussed       Tag Extension 101 Anatomy of a Tag Extension Tag Handlers The javax.tagext.tagext.tagext.jsp.tagext.

it enforces separation of code and presentation. it requires. We will see later an example of a tag that can reverse its body content. A tag directly enclosing another tag is called the parent of the tag it encloses: in the example above. separated by a colon. This tag dispatches the current request to another page in the current web application. I could create a tag named <wrox:forward>. and suffix (in this case forward). The key concepts in tag extensions are:  Tag name: A JSP tag is uniquely identified by a combination of prefix (in this case jsp). decouples the call from the class that implements the functionality associated with the tag. Attributes: Tags may have attributes. which use the XML syntax for attributes.jsp” /> We can also to add additional parameters to the request before forwarding with an extend usage of <jsp:forward>.gif” </jsp:forward> /> Tax extensions allow a vast range of new functionality to be added to the JSP language and they can be invoked in a similarly intuitive way.1 Tag Extension 101 Consider the <jsp:forward> action provided by the JSP specification. It will be invoked like this (the body content is shown in bold): <examples:reverse> Able was I ere I saw Elba </examples:reverse>    67 .J2EE Servlets & JSP =========================================================================================================================== 6. The <jsp:forward> tag above has one attribute (page). A tag extension can access and manipulate its body content. Nesting: Note how the <jsp:param> subtag is used in the second example above. It can be invoked with the following syntax: <jsp:forward page=”next. excluding subtags. Body content: This is anything between the start and end elements in a JSP tag. For example. Tag extensions can detect nested tags at runtime and cooperate. Attributes may be required or optional.jsp” > <jsp:param name=”image” value=”house. the <jsp:forward> tag is the parent of the <jsp:param> tag. Not only can this be added simply into the web page. while the <jsp:param> attribute has two (name and value). and implement it to perform a custom action before forwarding. specify what attributes and subtags. and can be simply incorporated into a design tool. if any. which nests one or more <jsp:param> tags within the <jsp:forward> tag: <jsp:forward page=”next. Neither the <jsp:forward> not <jsp:param> tags require body content.

Generic tags application types. are a very old concept in dynamic page generation. Tags receive the attributes that control their behavior from the JSP pages using them. not the request to a particular JSP (as in the case of request bean property mappings) A well-designed tag extension may be used in many JSP pages. As an indication of their power. all the standard JSP actions provided via tags of form <jsp:XXX> could be implemented using tag extensions. The tag handler (the class implementing the tag itself) is a JavaBean. The behavior of tag handlers is configured by their XML attributes and their body content (which can be the result of evaluating JSP expressions at runtime). Why. A Tag Library Descriptor (TLD) file is an XML document that describes a tag library. and define scripting variables. This reusability is particularly interaction with the JSP engine libraries of tax extensions can be open source basis. Since their implementation and is well defined in the JSP 1. important. write output to the output writer. might we choose to use tax extensions rather than JSP bean? Are tag extensions not simply another way of allowing JSP pages to parcel out work to Java classes? Due to the richer interaction between the hosting JSP page and tax extensions. not tailored resources for a particular page or group of pages. 68 . tag extensions can achieve directly what beans can only achieve in conjunction with scriptlets. who may not be experienced with enterprise data) To introduce new scripting variables into the page To filter or transform tag content. although new to JSP. Typical uses of tag extensions are:  To conceal the complexity of access to a data source or enterprise object from the page (possibly. with properties matching the tag’s XML attributes. or even interpret it as another language To handle iteration without the need for scriptlets    Tag extensions can be used to deliver a range of functionality limited only by developers’ imaginations and sensible programming practice. which contains one or more tag extensions.1 specification. developed and distributed. Tag extensions may access the PageContext. Products such as Apple’s WebObjects and BroadVision have delivered rich functionality through custom tags for years. on a commercial or can be developed for particular industries or Tag extensions. Tax extensions differ from beans in that they are common building blocks.J2EE Servlets & JSP =========================================================================================================================== The functionality associated with a tag is implemented by one or more Java classes. although in a proprietary context. The JSP taglib directive must be used to import the tag library in each JSP that wishes to use any of them. the page author. redirect the response. This experience in the use of custom tags can be valuable to JSP developers. besides a clever syntax.

servlet. the tag handler. Of course. The Tag or BodyTag interfaces. The minimal requirement is a tag handler and a tag library descriptor. in the true Java spirit it delivers rich functionality without excessive complexity: The examples and most of the discussion in this chapter and the next assume that tag extensions will be used to generate HTML markup.tagext. Let’s look at each of these requirements in turn. the calls the class implementing the tag will receive when the JSP engine encounters the tag’s opening and closing tags. When a tag is encountered in a JSP.TagExtraInfo to provide information about scripting variables that are made available to JSPs through the use of tags. most importantly. the taglib directive must be used to import a tag library and associate the tags it contains with a prefix. it parses the tag library descriptor to find the required tag handler class. Tag or BodyTag. For performance reasons. TagExtraInfo subclasses may also perform custom validation of tag attributes. document containing information about one or more tag extensions.J2EE Servlets & JSP =========================================================================================================================== Tag extensions are a particularly welcome addition to the JSP developer’s armory because they are easy to implement.3 Tag Handlers When the JSP engine encounters a tag extension in a JSP at translation time.jsp.  More complex tags will require an additional class extending the abstract class javax.2 Anatomy of a Tag Extension Before we return to our simple example. Instead. tag extensions can be used to generate any content type supported by JSP: 6. and generates code to obtain. While this is currently their most likely use.jsp. as we have seen. This is a reflection of the elegance of the design if the tag extension mechanism. one of which must be implemented by any tag handler. the JSP engine will try to find a Tag instance that is not being used. define callbacks that the servlet resulting from the JSP engine’s code generation will make to the tag handler instance at runtime. JSP engines will not necessarily instantiate a new tag handler instance every time a tag is encountered in a JSP. and interact with. These interfaces define the lifecycle events relevant to a tag. Before tags can be used in a JSP. they may maintain a pool of tag instances. let’s cover some basic theory of tag extensions. 6. A number of components are required to implemented a tag extension. The API surrounding them is relatively simple. the classes implementing a tag may require any number of helper classes. and it is possible to use them to achieve results quickly.tagext package. which will need to be packaged with the tag for it to be a complete deployable unit. A tag library descriptor. is an XML. reusing them where possible.servlet. use it and release it 69 . initialize it.  A tag handler is a Java bean implementing one of two interfaces defined in the javax.

tag handler implementations don’t need to concern themselves with threat safety.Jsp. in the case of a tag invoked like this <mytags:test name=”John” age=”43” />.J2EE Servlets & JSP =========================================================================================================================== (but not destroy it). doStartTag() and doEndTag (). The container sets the tag handler’s parent property.      Lets look at the doStartTag() and doEndTag() methods: int doStartTag() throws JspException 70 . The programmer has no control over any pooling that may occur. but note one very important difference. If the type conversion fails. there is no different between an exception thrown by a tag handler and one thrown by an expression of scriptlet in the page.1 The javax. the String “43” will be converted to an int in this case. This is not equivalent to a finalizer. The container will attempt to convert each attribute to the type of the corresponding bean property: for example. For example. Tag handlers differ from page beans in that their lifecycle is entirely independent of that of the JSPs that use them.3. Tag handlers must support repeated use before destruction. This is a mapping from the XML attributes of the tag to the corresponding properties of the tag handler bean. and in the default state: Let’s look at the messages in more detail:  The container initializes the tag handler by setting the tag handler’s pageContext property. Before we look at the method contracts in more detail.tagext. sufficient for tags that don’t need to manipulate their body content. The JSP engine will not use an instance of a tag handler to handle a tag unless it is free. 6. Assume that the container already has a tag handler instance available. a sequence diagram helps to visualize the calls made to the tag handler by the compiled servlet. an exception will be thrown and must be handled by the calling JSP page.servlet.) Next. (From a JSP’s point of view. The repeated use model is similar to a servlet lifestyle. developers need to worry about threading issues less often than when developing sevlets. which the tag handler can use to access information available to the JSP currently using it. possibly in a number of JSPs. The implementation of the release() method must ensure that any state that may cause conflict in future uses it reset.) Any tag attributes defined by the developer will be set. and that any resources required during the tag’s execution are freed. The container calls the doEndTag () method. The container calls the release() method. (Parent may be set to null. the container will attempt to call the setName() and setAge() methods on the tag handler. making it available for further use. This is good news: as with JSP authoring in general.Tag Interface The Tag interface defines a simple interaction between the JSP engine and the tag handler. if the tag is not enclosed in another tag. the container calls the tag handler’s doStartTag () method. Its core methods are the calls implementing classes will receive when the JSP engine encounters the tag’s opening and closing tags.

as you can see. Its return value should be one of two constants defined in the Tag interface: EVAL_BODY_INCLUDE.jsp.tagext. to obtain context information: void setPageContext (PageContext pc) setPageContext ( ) is an initialization method. initialization. when the JSP engine encounters the opening of a tag at run time. as will most of methods in the tag handler API when an error condition is encountered. The second is an often overlooked task in this context. and reuse: Tag getParent() void setParent() The specification also requires methods to expose the parent property. int doEndTag () throws JspException doEndTag () is called when the JSP engine encounters the closing tag of an element at run time. Examples of this may be closing JDBC connections or open sockets that the handler requires for its function and to clear any state associated with it.BodyTag Interface BodyTag extends Tag. A legitimate use might be to terminate page output if it is established that the user has insufficient privileges to view the whole of the page. using tag handlers to terminate page evaluation is even worse than sprinkling random return statements in Java code. it is somehow more complex than that of the Tag interface: 71 . so an exception thrown in a tag will abort the rendering of the page. The SKIP_PAGE return value should be used only with very good reason.3. adding extra callbacks and other methods allowing the developer to work with the content of the tag. Tag implementations can query their parent at runtime. This can throw a JspException.J2EE Servlets & JSP =========================================================================================================================== Called after the tag has been initialized. which instructs the JSP engine to ignore the body. and may be confusing to the reader. Most JSP pages will use an error page. EVAL_PAGE will cause the JSP engine to evaluate the rest of the page. or null if there is no enclosing tag. There are also a number of methods that related to tag nesting. 6. SKIP_PAGE to terminate evaluation of the page. void release ( ) release ( ) is a call to the tag handler to release any resources. A sequence diagram displays the interaction between calling JSP and tag handler in the case of a body tag. Its return value can be EVAL_PAGE or SKIP-PAGE. how it will be handled will depend on the JSP page using the tag. A tag’s parent is the tag that directly encloses it in a JSP. making the PageContext of the JSP available to the tag. which instructs the JSP engine to evaluate both the tag’s body and any child tags it has.servlet.2 The javax. or SKIP_BODY.

BodyContent is a subclass of JspWriter that can be used to manipulate the body content of BodyTag implementations and store it for later retrieval. the BodyTag needs to write the contents of its BodyContent into its enclosing writer explicitly (see below). int doInitBody( ) throws JspException Called after the tag has been initialized and doStartTag ( ) has been called. and the possibility of repeated calls to the doAfterBody( ) method. which enables the BodyTag implementation to take control of the tag’s execution at runtime. After the BodyTag’s method have been called. in which case the body will be ignored.3. SKIP_BODY.servlet.BodyContent Class The BodyContent class is the key to BodyTag functionality. Before the BodyTag begins to evaluate its body content. EVAL_BODY_TAG directs the JSP engine to evaluate the tag’s body and any child tags again (resulting in at least one more call to this method).popBody( ). This can be used to conditionally loop through the tag content. 72 . int doAfterBody ( ) throws JspException doAfterBody ( ) is called each time the tag’s body has been processed. To generate output. The more significant methods of the BodyTag interface are listed below. To understand the way in which the BodyContent class works.jsp. The getBodyContent ( ) method of BodyTagSupport returns the BodyContent instance associated with a particular tag. This is the key difference between BodyTags and Tags: Tag implementations have no such (flexibility. consider how JspWriter objects are handled in JSPs using BodyTags: messages 5 and 10 from the sequence diagram above.J2EE Servlets & JSP =========================================================================================================================== The extra steps involve the preservation of the JSP’s JSPWriter (messages 5 and 10). or SKIP_BODY. and therefore cannot modify or suppress their body content. in which case the tag’s body content and any child tags will be evaluated. the generated JSP implementation class includes the following line: out = pageContext.3 The javax. pushBody ( ). What this means is that each BodyTag has a kind of play area.tagext. it includes a matching call: out = pageContext. The return values are EVAL_BODY_TAG and SKIP_BODY. 6. enabling it to manipulate its BodyContent without automatically affecting the JspWriter of the enclosing JSP page or tag. void setBodyContent (BodyContent bodyContent) Initialization method to set the class used to manipulate body content. causes processing of the body content to terminate. Watch out that you don’t try to return EVAL_BODY_INCLUDE from a BodyTag’s doInitBody ( ) or doStartTag ( ) methods. The JSP engine will throw a JspException if it detected this. Its return value should be EAVL_BODY_TAG.

The release ( ) method can also be omitted if it is not necessary to free resource or return the tag to its default state. this may be the writer of an enclosing tag. The methods that a developer will normally want to override are doStartTag ( ) and doEndTag ( ) for all tags. JspWriter getEnclosingWriter( ) Returns the enclosing JspWriter. } This ensures that if there is any body content held in the body tag. This is useful if we need to examine what has been added to the body content with each iteration of a loop. The most interesting methods in the BodyContent class are: void clearBody( ) Clears the body content.toString()). So developers can safely omit methods that they are not interested in. not abstract classes. as a String. it will be written to the enclosing JSP writer. String getString ( ) This returns the content already held in the body content. so they provide complete implementations of the corresponding interfaces.tagext package includes two convenience implementations of Tag and BodyTag: TagSupport and its subclass BodyTagSupport. Developers don’t usually concern themselves with handling the parent property and setPageContext ( ). The class diagram below shows the relationship between these classes and the Tag and BodyTag interfaces: TagSupport and BodyTagSupport are concrete. we have used the following lines of code in the doEndTag ( ) method of a number of BodyTag implementation in this chapter: BodyContent bodyContent = getBodyContent ( ). We normally use this method to get a JSP writer to which we can write the body content stored in a body tag when we have finished manipulating it.4 Convenlence Classes Some of the methods in Tag and BodyTag will be implemented the same way in most tags.servlet.J2EE Servlets & JSP =========================================================================================================================== although they can prevent it from being evaluated altogether by returning SKIP_BODY in their implementation of doStartTag( ). For example. So the javax. if (bodyContent ! = null) { bodyContent. Classes implementing tag extensions will normally be derived from one of these. or the writer of a JSP itself. Useful if we want to manipulate the body content before writing it out.getEnclosingWriter(). write(s)bout.3. which do nothing except return the appropriate values to cause the JSP engine to continue rendering the page. and doInitBody ( ) and doAfterBody ( ) for BodyTags specifically. 6. 73 .jsp.

and references to objects such as beans associated with the JSP. javax. It describes whether or not the variable should be declared or whether the tag will merely overwrite the value of an existing variable. Note that runtime attribute validation is entirely different. and the scope of the variable. Boolean isValid(TagData data) This is sometimes used to validate the attributes passed to a tag at translation time. necessary to obtain a tag’s BodyContent before manipulating it. This optional association is specified in the tag library descriptor. the isValid ( ) method of the appropriate TagExtraInfo subclass could be implemented to return false if the parameters supplied at translation time are invalid. Note. Custom tags should be thought 74 . These classes are standard implementations of the Tag and BodyTag interface. As you’ll recall. BodyTagSupport provides a getBodyContent( ) method. consider a tag with four attributes.J2EE Servlets & JSP =========================================================================================================================== TagSupport also makes an important convenience variable available to subclasses: pageContext (the saved PageContext which was set by the JSP engine when the tag was first used in a page). which contain information about the name of each scripting variable and its fully qualified class name. but if one of the optional attributes is specified the whole three must be present.TagExtraInfo Class Metadata classes extending the TagExtraInfo abstract class may be associated with tag handlers to provide extra information to a JSP engine.servlet.jsp. including the request and response object. and is the responsibility of the tag handler concerned. Three may be optional. 6. It returns an array of VariableInfo objects. Like me. As an example.jsp.tagext.servlet.3.PageContext is a convenient holder for information about the runtime of a JSP page. that it is poor style to modify request and response directly from a tag handler.5 Objects Available to Tag Handlers All tag handlers have access to more context information than do most beans. However. but the two methods you are most likely to override are: VariableInfo[ ] getVariableinfo (TagData td) This method is used to return information about scripting variable that the tag makes available to JSPs using it.5 The javax. you might find the names TagSupport and Body-TagSupport confusing. This is available through the PageContext object they are passed on initialization. It should be pointed out that this naming is inconsistent with Sun’s usual practice and Java convention. We will look at the implementation of a TagExtraction class in more detail later in this chapter. There is no way to specify this behavior in a tag library descriptor. This amount of access equals power. though.3. 6. The default implementation of isValid ( ) in TagExtraInfo always returns true. I think of them as TagImpl and BodyTagImpl.

In practice tags should not be concerned with the parameters passed to the JSP page.jsp.servlet.write("Hello world <br/>"). try { pageContext.io. It has no state and access no file or other resources. relying on doing so will greatly reduce its reusability.*.6 The Simple Example Revisited To catch our breath after all this theory. import javax.J2EE Servlets & JSP =========================================================================================================================== of as generic building blocks intended for use in a wide variety of contexts. import javax. let’s look again at the java implementation of the simple example we introduced earlier. public class HelloTag extends TagSupport { // This method will be called when the JSP engine encounters the start // of a tag implemented by this class public int doStartTag( ) throws JspTagException { // This return value means that the JSP engine should evaluate // the contents and any child tags of this tag return EVAL_BODY_INCLUDE. obtain a JspWriter.getName()+" and it's " + dateString + "<p/>"). } catch (IOException ex) { throw new JspTagException("Fatal error: hello tag could not write to JSP out").util. and generate output: package tagext. import java.write("My name is " + getClass().3. } // This return value means that the JSP engine should continue to 75 . so there is no need to override release( ). and so gets most of its functionality for free.getOut().getOut(). 6. We use doEndTag ( ) to access the PageContext.*. // Implementation of a tag to generate a single piece of HTML.IOException. toString ( ). import java.Date. We see that the tag handler extends TagSupport.tagext.jsp. } // This method will be called when the JSP engine encounters the end //of a tag implemented by this class public int doEndTag ( ) throws JspTagException { String dateString = new Date ( ).servlet. pageContext. Although a tag handler can access request parameters.

It’s defined in the DTD as: 76 . info?. This is defined by the author of the tag library. and should not start with a digit or underscore. the authoring tool may display it when the tag library is imported.1 specification. jspversion is the version of JSP specification the tag library depends on.servlet. but in fact it does exactly what its superclass TagSupport’s doStartTag() method does instruct the JSP engine to evaluate the tag’s content and any subtags. although such tools are yet to be widely available in the market. this isn’t in the same package as the other classes specific to tag handlers. The root elements are<taglib>. jspversion?. uri is an optional URI uniquely identifying this tag library.tld extension that describe one or more tag extensions. shortname. Think of it as the equivalent of a Javadoc comment relating to an entire class or package.) We could actually have omitted the doStartTag() method. 6.4 Tag Library Descriptors Tag Library Descriptors or TLDs are XML documents with a . info is an arbitrary text string describing the tag library. (Note that. and consistency will be achieved between all users of the tag library. It’s defined in the DTD by: <!ELEMENT taglib (tlibversion. confusingly. Many of the elements are intended to provide support for JSP authoring tools. hopefully developers using the library ill follow this suggestion.1 (the default).J2EE Servlets & JSP =========================================================================================================================== } // evaluate the rest of this page return EVAL_PAGE. The element is optional.     The <tag> element is the most important. TLDs must conform to the Document Type Definition (DTD) included in the JSP 1.jsp. shortname is a simple default name that could be used by a JSP authoring tool. the best value to use is the preferred prefix value: that is. a suggestion as to a prefix to use when importing the tag library. uri?. At the time of writing the value you should use is 1. Although there is no way of enforcing this. tag+) >  tlibversion is the version of the tag library implementation. The shortname should not contain whitespace. Any exception encountered while processing the tag must be wrapped as a JspException if it is so to be rethrown.JspTagException subclass of JspException. If it is used. } // class HelloTag Note that we need to check for IOException when generating output. it is good practice to use the javax. I include it for completeness. the value will normally be the URL of the definitive version of the tag library descriptor.

or whether it has a fixed value at translation time when the tag is used in a JSP. very often tag attributes will be set to the value of properties of JSP beans. This class must implement the javax. teiclass?. bodycontent is an optional attribute specifying the type of body content the tag should have. Not all tags require a TagExtraInfo class. the default is false.jsp. rtexprevalue?) >   name is the name of this attribute. and should therefore be passed unchanged. The DTD definition is: <!ELEMENT attribute (name. teiclass stands for TagExtraInfo class. Valid values are true and false. If rtexprvalue is true. The default (and more useful) to JSP.servlet. meaning that expression are forbidden .jsp. and false (the default. Three values are legal: tagdependent. signifying an optional attribute). Again. For example. empty is useful when a tag should not have any body content. which means that the tag’s body content will be evaluated at run time like any other JSP content. info?. attribute?) > name is the name that will identify this tag (after the tag library prefix0. JSP translation will fail. tagdependent signifies that the JSP engine should not attempt to evaluate the content.0” encoding=”ISO-8859-1” ?> <!DOCTYPE taglib 77 .J2EE Servlets & JSP ===========================================================================================================================   <!ELEMENT tag (name. If this value is used.   <attribute> sub-elements describe each attribute accepted (or required) by the tag.tagext. required specifies whether or not this attribute is mandatory. Setting attributes by the use of expression allows their behavior to be determined at runtime. tagclass is the fully qualified name of the tag handler class that implements this tag. tagclass. required?.getValue()%>’>  Allowing attributes to take expression values can be very useful.TagExtraInfo that will provide extra information about this tag at runtime to the JSP. The valid values are true/the attribute is required). and the tag is not empty.Tag interface. but accept that while it may not understand it. and defines the subclass of javax. and empty. The attribute may have a default value.tagext. as it will appear in JSPs using the tag. The simple example’s TLD was very straightforward. it means something to the tag handler. bodycontent?. This relies on the use of a JSP expression. <examples:mytag attrib”<%-myObject. only the bare minimum of elements is required: <?xml version=”1. JSP. rtexprvalue specifies whether the attribute value can be the result of a JSP expression. the following will be legal.servlet. As this tag takes no attributes and has no associated TagExtraInfo class.

When a tag requires no body content.1//EN” http://java. (of course it is good practice to write XML complaint HTML markup. and at present TLDs will usually be written by hand. tags in a library can be called as follows: <examples:someTag name=”Rod”> . The syntax for the taglib directive is shown below: <%@ prefix=”example” taglib %> uri=”http//www.1 becomes more widely supported tool support can be accepted. 6.5 Using Tag Extensions in JSP Pages Unlike the standard actions such as <jsp:forward>. Inc. the attributes of custom tag must be enclosed in double quotes. the first attempted access to any tag defined in the TLD will cause an exception at runtime if all the classes required to support the tag implementation cannot be loaded.//DTD JSP Tag Library 1. The prefix attribute tells the JSP engine what prefix will be given to tags from this library in the remainder of the JSP. avoiding time-wasting trivial errors.HelloTag</tagclass> <bodycontent>JSP</bodycontent> <info>Simple example</info> </tag> </taglib> Although the XML structure is not complex. custom tags must be explicitly imported into JSP pages that wish to use them.. Note that. The taglib directive will cause an exception at translation time if the tag library cannot be located.com/tags/tags. A JSP may import any number of tag libraries. unlike HTML attributes.dtd> <taglib> <tlibversion>1..1</jspversion> <shortname>examples></shortname> <tag> <name>hello></name> <tagclass>tagext.tagvendor. in accordance with the XML specification.sun. but browsers do not currently enforce it. as JSP 1.com/j2ee/dtds/web-jsptaglibrary_1_.) Tag prefixes use the same syntax as XML namespaces.tld” The uri attribute tells the JSP engine where to find the TLD for the tag library. Once the tag library has been imported into the page.J2EE Servlets & JSP =========================================================================================================================== PUBLIC “-//Sun Microsystems. it is best to use the XML shorthand to make this explicit: <examples:hello name=”Rod” /> 78 . This will synchronize TLDs and the relevant Java classes.0</tlibversion> <jspversion>1. </examples:someTag> The way in which custom tags are used in JSP is an example of Sun’s efforts to introduce XML conventions into JSP syntax.

xml file in a <taglib> element. This is the approach we’ve taken in this chapter.tld” prefix=”examples” %> The uri is simply a path on the host server. but consistency among JSP pages importing the same tag library is advisable. servlet. the tag library descriptor. There is no attempt to package a tag library or an application. the Java classes required to implement the tags. Choice of prefix is a matter for developers.xml file for our simple example looked like this: 79 .) 6. It is very attractive because it offers painless portability between servers and very easy deployment. In this case. Choosing a prefix unique to a company or organization is advisable: for example. In this approach. the tag library descriptor (although not the classes implementing the tag handler) is always publicly available: anyone could view it by simply typing in its URL. The prefixes jsp.. This server knows where to look in the current web applications WAR for a . which may be relative (as in this example) or absolute.J2EE Servlets & JSP =========================================================================================================================== Tag prefixes are defines in JSPs. in a Web Archive file (better known a WAR file). jspx.. It is best to adopt the value of the shortname element in the tag library..tld file matching this URI because the mapping from URI to file location is specified in the web. JSP developers must be familiar with all three. (This means that JSPs need to be modified slightly if they are to be deployed in a different way – surely an oversight in the JSP specification.. so there is no need to use the TLD extension. It’s perhaps unfortunate that Sun has not defined a unique naming system such as the Java package naming system for tag library prefixes. instead of using the potentially clashing short name tables. In this case. 6. as one might expect.2 WAR In a second approach to deployment. The complete web.6.1 No Packaging The first and simplest means of deployment is simply placing the tag library descriptor under the server’s document root. the taglib directive will look like this: <%@ taglib uri=”/hello” prefix=”examples” %> Note that we don’t specify the actual filename of the TLD. not. and the JSPs that use the tag library can be shipped together as a web application./hello. java. and sunw: are reserved. sun.. the taglib directive will look like this: <%# taglib uri=”. and the Java classes required to implement the tags in the server (or system) classpath.6. it might be advisable to use myCompany_tables. in tag libraries.6 Deploying the Packaging Tag Libraries There are three main ways of deploying and using tag libraries with a JSP engine. but can create problems at deployment time: the JSP engine or system’s classpath has to be hand edited to include the classes implementing the tag. This approach is easy to work with. 6. because each of them calls for slightly different syntax in the taglib directive. javax..

com/j2ee/dtds/web-app_2.    80 . <taglib>-location> specifies the path to the tag library descriptor relative to be web.dtd’> <web-app> <display-name>tagext</display-name> <description>Tag extensions examples</description> <session-config> <session-timeout>0</session-timeout> </session-config> <taglib> <taglib-uri>/hellovar</taglib-uri> <taglib-location>/WEB-INF/hello. Remember the important directories in the WAR.2 .xml file.sun.xml file.2//EN’’ http://java.//DTD Application 2.tld</taglib-location> </taglib> </web-app> Web The <taglib> element contains two subelements<taglib-uri> specifies the URI that should be used is JSP’s wishing to use the tag library.0” encoding=”UTF-8?> <!DOCTYPE web-app PUBLIC `-//Sun MicroSystem. WEB-INF/tlds: By convention (although not mandated in any specification) this contain the tag library description (but not tag handler classes) that will be made available to JSPs in the web. WEB-INF/classes: This contains Java classes required to implement tag libraries or otherwise support the functionality of the web application.xml file).  WEB-INF: This contains the web. in which the TLD URI-location mapping must be specified. but adhering to this convention makes it easier to comprehend the WAR’s structure. Note that this path need not be publicly available to users of the web server. WEB-INF/lib: This contains JAR files containing additional classes required to support the functionality of the web application. The TLDs could actually be placed anywhere in the WAR (so long as a mapping is included in the web.xml file.J2EE Servlets & JSP =========================================================================================================================== <?xml version=”1. the server will not publish anything that is in the WEB-INF directory. Inc.

A database can be defined as a collection of stored operational data used by the application systems of some particular enterprise. there are no duplicate pieces of data. A database is designed and built for a specific purpose. In a welldesigned database. a data storage place. A Database is like a data file. Related pieces of data are grouped together in a single table. the purpose of which is to record. the user or application has to update at the same time. keeping in mind the needs of the applications that are going to use it and the end users of those applications. Databases systems are more powerful than data files because data is more highly organized. presents it to the user in a useful format. a database does not present information directly to a user. Alike a data file.J2EE Servlets & JSP =========================================================================================================================== Chapter: 7 JDBC Topics Discussed           Introduction to Databases Database Design Two-Tier Database Design Three-Tier Database Design Overview of ODBC (Open Database Connectivity) Overview of JDBC API How does JDBC work? Security Model JDBC API Components The java. A database typically has two components: the files holding the physical database and the Database Management System (DMBS) software that application use 81 . and store data. The collection of data must be logically coherent with some inherent meaning. and the relationships between tables can be precisely defined.1 Introduction to Databases Data are raw facts from which information can be derived. more specifically a computer-based system. The user runs an application that accesses data from the database and after analyzing it. A database is a collection of interrelated data from which some information can be extracted. A database is a recordkeeping system of an organization.sql Package Literals Variables JDBC Drivers Type 1: The JDBC-ODBC Bridge Driver Type 2: The Native Library-to-Java Driver Type 3: The Network Protocol Driver Type 4: The Native Protocol Driver Executing SQL Commands Using JDBC drivers Using Type 1 Driver (JDBC ODBC Bridge Driver) Using Type 2 Driver (The Native Library-to-Java Driver) Using Type 4 Driver (The Native Protocol Driver) The ResultSetMetaData Interface 7.

An RODMS can be thought of a DBMS with add on facility of setting relations between databases. 7. It provides an environment wherein data can be stored and retired from databases easily and efficiently. It allows definition of data structures. and the database libraries were bundled together. contention between instances of the application because the monolithic approach did not allow multiple instances of the application to communicate with each other. There was often. the RDBMS applications were based on an integrated model where the user interface code.J2EE Servlets & JSP =========================================================================================================================== to access. process.F.1 The one-tier database design 7. The following figure depicts a monolithic. application code. and hence at one instance of time you can use information across tables. storage and retrieval operations and integrity constraints. In this model. The client software is connected to the database through a socket connection. Single Tier Database Design In the beginning of the RDBMS era. and output data. In this model the clients send requests to the database server through SQL (Structured Query Language). The application is considered as a front-end and the server as the back-end. one-tier database design: Application Storage Database Libraries Fig. The front-end applications are stored in the client side and the database is stored on the server. Codd at IBM in 1970.2 Database Design A Database Design can be categorized into three parts: • • • Single Tier Database Design Two-Tier Database Design Three-Tier Database Design Monolithic.1 Two-Tier Database Design The evolution of the two-tier design is due to the server technology. 7. The applications ran only on a local machine and did not work on local-area networks. A DBMS is a general-purpose software system that enables users to define and manipulate databases. The communication 82 . The server sends the results according to the request and the client is responsible for formatting the data. A Relational Database Management System (RDBMS) is a database based on the relational model invented by E. the application accesses data through a server. format.2.

The following figure depicts the three-tier database design: 83 . there is an intermediate server in addition to the client and the database server.7. The client communications with the intermediate server. The following figure depicts a two-tier database design.2 Three-Tier Database Design This design is not limited to only three tiers. In a multi-tier design.J2EE Servlets & JSP =========================================================================================================================== between the client and server takes place with the help of a vendor-provided library of functions. Application (Client) Client-side Libraries SQL Request Server Database Storage Fig.2. These functions are written in the C language. The intermediate layer is used to handle multiple client requests and manage the connection to one or more database servers.2 Two-Tier Database Design 7.

J2EE Servlets & JSP

===========================================================================================================================

Middleware Application (Client) Business Rules Client-side Libraries Datab ase Server

Client-side Libraries

Data Reply Change Notification
Storage

Fig. 7.3 Three-Tier Database Design Since, every organization maintains data pertaining to its business, employees, and clients in a database using some DBMS or ROBMS package, it is of vital importance that we have some mechanism to connect to the database using the programming languages at our disposal. Over the years we have had many approaches to establish connection with database but a few have stood the test of time. Let us go through a few of the more successful approaches for database connectivity. Note In two-tier and three-tier systems, an application is logically divided into three parts:

• •

GUL, Graphical User Interface: Consists of screens, Windows, buttons, list boxes and more. Business Logic: This is the part of the program that deals with interaction between various data elements, for example, calculation or credit limit based on the annual salary, etc.

84

J2EE Servlets & JSP

===========================================================================================================================

DBMS The database management system, that deals with the actual storage and retrieval of data.

7.3 Overview of ODBC (Open Database Connectivity) ODBC is a database interface used to interact with databases from a programming language through its functions. It is Microsoft’s implementation of the X/Open and SQL Access Group (SAG) Call Level interface (CLI) specification. The functions of ODBC include adding, modifying and deleting data and obtaining details about the databases, tables, views, and indexes. An ODMC application has five layers (shown in Figure 7.4): • Application Layer • ODBC Interface Layer • Driver Manager Layer • Driver Layer • Data Source Layer

Application
ODBC

Driver Manager Driver Data Source

Fig. 7.4 ODBC Architecture • Application Layer

The Application Layer provides GUI and Business logic, written in languages like Java, Visual Basic and C++. • ODBC Layer

The Application layer uses the ODBC functions defined in the ODBC interface to interact with the databases. • Driver Manager Layer

The Driver Manager Layer manages the loading of various drivers available in the system, directing calls to the right driver, and providing driver information to the application when required. The driver manager ensures that the right database management system gets all the program calls directed to it and that the data from the data source is routed to the application when an application is connected to more than one database. • Driver Layer

85

J2EE Servlets & JSP

===========================================================================================================================

This layer is the actual component, which knows about specific databases. The driver is assigned to a specific database like the Access Driver, SQL Server Driver, and Oracle Driver. It is the duty of Driver Layer to implement all the functionality provided by the ODBC interface like SQL statement calls, connection management calls, information about the database and so on. This indicates that the Driver has to emulate the ODBC interface functions not supported by the underlying DBMC for some databases. The other duties of this layer include sending queries to the databases, receiving the data back, and routing the data to the application. The Driver layer also handles the network communication for databases that are in the local networked system or on the internet. • Data Source Layer

In the content of ODMC, the Data Source can be a database management system, or the data store, which is usually a set of files on the hard disk. It can be the Microsoft Access database, the SQL Server database or the Oracle database. 7.4 Overview of JDBC API JDBC stands for Java Database Connectivity. It was developed by JavaSoft and is a part of the Java Enterprises API. JDBC is the first standardized API that allows the users to develop database front ends without continuously rewriting their code. JDBC provides the ability to create robust, platform-independent applications and Web-based applets, which can access any database through a DBMS-independent mechanism. The interaction between these applications and applets with SQL data sources is done through a set of relation database objects and methods defined in the JDBC API. 7.4.1 How does JDBC work? A set of API objects and methods, defined in JDBC, are used to interact with the underlying database. At the beginning of the process, a Java program open a connection to a database. Then, it creates a statement object, passes SQL statements to the underlying DBMS through the statement object, and retrieves the results and information about the result sets. The JDBC class files and the Java applets reside in the client. They can be downloaded from the network also. It is better to have the JDBC classes in the client to minimize the latency during execution. The DBMS and the data source are typically located in a remote server. The applet and the JDBC layers communicate in the client system, and interact with the database over the network.

7.4.2 Security Model Security is very important especially when databases are involved. As far as JDBC is concerned, it follows the standard security model in which applets can connect only to the server from where they are loaded. Remote applets cannot connect to local databases. Applications have no connection restrictions. The security check is automatic as far as pure Java drivers are concerned. The drivers must have security checks if they are developed through native methods.

86

Writing a JDBC driver consists of a creating a Java class that implements the Driver interface. Statement.e. The Driver Layer handles communication with a specific driver implementation. For example: jdbc:oracle:customer In the above example.e. the Driver is accessed through the DriverManager class. which keeps to our information. state information and more. The class bridges the Application Layer and the Drive Layer. which locates a server named dbserver in the eng domain and attempts to connect to a database server on the port 812 that contains a burgerports database using the default username and password. the mysql is the database driver type. Whenever a connection is made. The Application Layer allows the developer to make calls to the database via SQL and retrieve the results. the subname can contain the net URL //hostname:port/. The syntax of a JDBC URL is: jdbc:<subprotocol>:<subname> The <subprotocol> defines the type of driver and <subname> provides the network-encoded name. When each driver is loaded. Although you do not 87 . The Driver Layer must implement for interfaces and one class. The following section describes about the implementation of the JOBC API classes and interfaces. The interfaces like Connection. The topmost class in the class hierarchy of JDBC classes is the Driver/Manager. Connection.5 The java. The connection to the database is made by the Driver interface. from where the objects are coming or what type of driver the application will use. The developer has one more layer of abstraction. For example jdbc:msq1:. The Driver and Application layers allows the developer to create database applications without knowing details i.3 JDBC API Components The JDBC API has two levels of interface: the Application Layer and the Drive Layer.J2EE Servlets & JSP =========================================================================================================================== 7.4. Statement and ResultSet represent methods that allow the developer to create statements and retrieve results. the Driver/manager selects the driver on the JDBC URL. In most applications. The four interfaces are Driver. it is registered with the DriverManager. 7. • The java-sql.Driver Interface JDBC drivers implement the Driver interface.sql Package The implement of JDBC is made through the java. This package contains all the JDBC classes and methods that allow the developer to create database applications. The JDBC URL is a string that is used by the drivers and access databases.sql package.. and ResultSet. i. the database driver is an Oracle driver and the subname is a local database called customer. the DriverManager Class.eng:812/burgerports In the above example. For databases on the Internet or intranet.//dbserver.

• The DriverManager class (java.sql. which is invoked for the driver by the Driver/Manager to obtain a Connection object is the starting point of the JDBC Application. Actually. Properties into) throws SQLException Boolean acceptsURL(String throws SOLException url) Description This method first checks the sub-protocol name of the URL string passed for a match this driver. As the methods in this class are static and hence they have to be referred to through the class name. The Driver then attempts to make a connection to the database using the remaining part of the URL.DriverManager) This class controls the coding of driver specific classes. DriverManager. This object is used to create Statement objects that perform the queries. The method returns true only if the URL is valid. Properties info ) throws SQLException Connection getConnection(String url) throws SQLException Connection getConnection( String url. The drivers are registered with the Drive/Manager at the time of initialization of the DriverManager class or at the time of creating an instance of the driver. The parameter info is a reference to a Properties object.io. The JDBC drivers are actually managed by the utility class. The most important method is the connect( ) method. set up logging. this method will return an instance of the Connection class. static java. If the connection is successful. Table below lists the methods defined in this class.PrintStream reference to the PrintStream object passed to the method. not whether the connection can be made. The second parameter info contains the username and password. This method sets a private.J2EE Servlets & JSP =========================================================================================================================== have to worry about writing your own JDBC driver. This method first creates a Properties object (info).info) with the empty Properties object (info). It throws an SQLException only if the driver recognizes the URL subprotocol but cannot make the database connection. and set login timeouts for database access. This method returns a Connection object by calling the getConnection(url.Driver driver) throws SQLException void setLogStream( java. each driver name is a class filename and these class names of drivers 88 . String user.io. stores the user and password strings into it and then calls getConnection (url.Prin tStream out) Description This method returns a reference to a Connection object implemented from the Connection interface. register and deregister drivers. which identifies where the driver came from. Table below lists the methods defined in this class: Methods Connection getConnection( String url. info). This class provides methods that allow the user to obtain a connection through a driver. This method stores the instance of the Driver into a vector of drivers along with an instance of SecurityContext. It checks only the sub-protocol specified in the URL. String password) throws SQLException void registerDriver (Java. which contains the username and password.sql. Methods Connection connect(String url.

This property can be used to define a list of colonseparated driver class names. as follows: DriverManager. Once the user gets a Connection object form the driver. This method returns a PrepareStatement object that is configured with the sql string. load.Driver:oracle.forName (driver). The connection will support commit and rollback methods when the auto-commit mode is disabled. sql.J2EE Servlets & JSP =========================================================================================================================== are listed in a Java property named jdbc. This method is used to set a flag in the driver that enables commit (true)/rollback(false) or makes all transactions commit immediately. Table below lists the method defined in this class: Methods Statement createStatement() throws SQLException PrepareStatement prepareStatement ( String sql ) throws SQLException Description This method returns a Statement object.Driver The DriverManager uses the following call to locate. which represents a session with the database connection provided by the Driver. The SQLException might be thrown if the driver and the database do not implement precompiled statements. The functionalities of this class range from transaction processing to creating statements. jdbc.driver=imaginary. if the database(driver) handles precompiled statements. which is then used to issue queries. The application must create an instance of a driver class if the jdbc. The sql string is sent immediately through the driver when prepareCall() is complete or may wait until an execute method occurs. the driver may wait until the PreparedStatement is executed by an execute method. The driver class is created by implementing the interface Driver.sql. In both cases. such as. and link the named classes through the current CLASSPATH: Class. which is used to handle stored procedures. Otherwise. the user should set the auto-commit mode of false since JDBC connections are in autocommit mode by default. This method returns a CallableStatement object.drivers. This method is used to drop all changes made since the beginning of the current transaction. This method takes care of all changes made since the beginning of the current transaction. which are loaded when the DriverManager class is loaded. CallableStatement prepareCall(String sq ) throws SQLException void setAutoCommit( Boolea n commit-mode ) throws SQLException void commit() throws SQLException void rollback() throws SQLException 89 .drivers property is unspecified. the implementation of the Driver class must register itself with the DriverManager by calling the registerDriver() method. The Driver may then send the statement to the database. • The Connection interface One of the major interface in JDBC API is the connection interface.sql.registerDriver (this).Driver:weblogic.

column names. In the case of a PreparedStatement object. The Statement object is associated with various data needed to interact with a database. Statements can be SQL updates. datatypes and so on. which is passed to the underlying DBMS. as the name implies.Connection. This method can be used when a SQL statement returns single or multiple result sets or update counts. This method is used to execute a SQL query and return an integer that represents the affected rows. They are PreparedStatement and CallableStatement. But these are transparent to the JDBC application program. it is cleared. This method is used to return the current data as the result of a statement execution in the form of a ResultSet object. The important point to note is that once the result is read. and getMoreResults() are used. and Delete query or a stored procedure that returns a row status.J2EE Servlets & JSP =========================================================================================================================== DatabaseMetaData getMetaData() This method is used to return a DatabaseMetaData object which is associated with the information about the whole database. including access information about tables and procedures. The user can create many Statement objects from the Connection object. insertions. This method returns the status of an Update. In other words. The update count will be cleared once it is read. once read. The PrepareStatement() method takes a SQL string. Table below lists the methods defined in the Statement interface that allow the developer to make the job of writing queries to the database easier. the statement object sends the SQL queries to the database and retrieves results. buffer handles. and so on.sql. The method returns –1 if there is no update count or the data returned is a result set. Insert. Methods ResultSet executeQuery (String sql0 throws SQLException int executeUpdate( Strin g sql ) throws SQLException boolean execute(String sql ) throws SQLException Description This method is used to execute a SQL query and return a ResultSet object. getUpdateCount(). The method returns a null if there are no results to be read or if the result is an update count. To retrieve the data returned. the methods getResultSet().prepareStatement() method. including state information. This method can also be used to execute stored procedures that return Out and InOut parameters. This method can be used in situations where no results are expected except a row-count status. The method moves to the next result in a set of multiple results/update counts. • The Statement interface The Statement object is used to interact with the Database Management System in terms of SQL statements. The DBMS 90 . ResultSet getResultSet() throws SQLException int getUpdateCount() throws SQLException boolean getMoreResults() throws SQLException JDBC supports two more types of statement objects in addition to the statement object. the previous ResultSet will be closed. deletions or queries. This method is used to return true if the next result is a ResultSet object. the application program prepares a SQL statement using the java.

For a secure. Stored procedure centralizes the business logic in terms of manageability and also in terms of running the query. consistent. The parameter marker (question mark) must be used for the return value (if any) and output arguments because the parameter marker is bound to a program variable in the stored procedure.<parameter> . A Callable/Statement object is created by the prepareCall() method in the Connection object. This string. <?> …]} The OUT parameters should be registered using the registerOutParameter() method as shown in table below before the call to the executeQuery().]} where the question mark symbol(?) is the placeholder for the parameters/ The CallableStatement interface supports parameters. Tables below defines the setType methods and the getType methods. and then connect Java variables to the parameters. The methods of the PreparedStatement object such as executeQuery(). The prepareCall() method takes a string as the parameter. to data access should allow the use of stored procedures. called an escape clause. In the JDBC call. and manageable multi-tier client/server system. These parameters are of the OUT kind from a stored procedure or the IN kind to pass values into a stored procedure. and execute() methods are just calls to the underlying DBMS to perform the already-optimized SQL statement. input arguments can be either literals or parameters. setType Methods Method Java Type SQL Type 91 . and the execution plan that the JDBC driver stores internally in the Prepare/Statement object. executeUpdate(). For a dynamic parameterized statement. . But the results are important to those clients. with the escape clause string. The CallableStatement interface defines the getType methods and the PrepareStatement interface defines the setType methods.J2EE Servlets & JSP =========================================================================================================================== goes through the syntax run query plan optimization. The setType methods are used to set the values of the parameters marked in the SQL statements with question marks (?) whereas the getType methods are used to convert the SQL types returned from the database to Java types. JDBC allows the use of stored procedures. Methods void registerOutParameter (int parameterIndex. Java applets running on clients with limited resources cannot be expected to run huge queries. you create a CallableStatement object with the “?” symbol as a placeholder for parameter. . the escape clause string takes the from {[“=] call <stored procedure name> [<?>. The argument parameterIndex depicts the position of the question marks and SqlType defines the SQL datatypes that are returned as Out parameters. is of the form {[?=] call <stored procedure name> [<parameter>. executeUpdate(). by the CallableStatement interface. int sqlType) Description This method is used to tie the placeholders with actual parameters. or execute() methods.

io.sql. BigDecimal x) void setString(int index. int scale) String getString(int index) byte[] getBytes(int index) Date getDate(int index) Time getTime(int index) TimeStamp getTimeStamp(int index) boolean Java Type Boolean Byte short int int float double java.Date java.sql. VARCHAR.sql.sql.InputStream java.J2EE Servlets & JSP =========================================================================================================================== void setByte(int index. byte b) void setShort(int index.sql. int sqlType) Byte short int long float double java.InputStream byte array java. InputStream x.String jav. or VARBINARY DATE TIME TIMESTAMPA • The ResultSet interface (java. int length) void setUnicodeStream(int index.lang.ResultSet) 92 .Timestamp SQL Type BIT TINYBIT SMALLINT INTEGER BIGINT FLOAT DOUBLE NUMERIC CHAR.lang.io.Types has contains for each of the SQL types. short x) void setInt(int index.TimeStamp TINYINT SMALLINT INTEGER BIGINT FLOAT DOUBLE NUMERIC VARCHAR LONGVARCHAR VARBINARY LONGVARBINARY DATE TIME TIMESTAMP java. boolean b) getType Methods Method boolean getBoolean(int index) byte getByte(int index) short getShort(int index) int getInt(int index) long getLong(int index) float getFloat(int index) double getDouble(int index) BigDecimal getBigDecimal(int index.lang.Time java.BigDecimal java. Time t) void setTimestamp(int index. Timestamp ts) void setNull(int index. int I) void setFloat(int index.sql. int I) void setLong(int index. or LONGAVARCHAR BINARY. BIT void setBoolean(int index.InputStream x.Time java. int f) void setDouble(int index. int length) void setBytes(int index.sql. Date d) void setTime(int index.InputStream java.Date java. int length) void setDate(int Index. byte x[]) void setBinaryStream(int index.sql. InputStream x. String s) void setAsciiStream(int index. int d) void setBigDecimal9int index.BigDecimal string Byte array java.jo.

This class stores the results of the statements created.J2EE Servlets & JSP =========================================================================================================================== The data from tables are accessed through the methods defined in the ResultSet interface.1 and later. But. they can be selected either by name or the number of the column. and properties of the results. For that the ODBC driver must be configured on the client for bridge to work. This method is used to release the resources associated with the ResultSet.6 shows the driver interaction of the JDBCODBC Bridge. which demonstrates the usage of the methods. There are a variety of drivers available according to the type of database they are intending to support. The ResultSet object maintains a cursor indicating the position of the current row.1 Type 1: The JDBC-ODBC Bridge Driver The first type of JDBC driver is the JDBC-ODBC Bridge. you must be clear with the JDBC drives through which the JDBC application runs. This method is used to main an object this is associated with the description of the current result set. Also. Also. Initially the ResultSet row position is the first row of the result set.6 JDBC Drivers There are a number of drivers available from database vendors and third-party developers. Developers can use the JDBC-ODBC bridge driver instead of other JDBC drivers since applications will speak directly to JDBC interface classes. Now that you have been introduced to the various classes and interfaces of JDBC APL. This driver type is provided by Sun with the JDK1. the ODBC driver manager. Actually the data from tables are generated by executing Statement. 7. are cost effective and provide customer support. it is always wise to have the drivers that have the best features. Before explaining the examples. Method boolean next() throws SQLException ResultSetMetaData getMetaData() throws SQLException void close(0 throws SQLException Description This method sets the position of the ResultSet to the next row. The ResultSet values are indexed and hence they may be accessed in any order. The ResultSet column values are indexed and hence they may be accessed in any order. The description includes the number of columns. JavaSoft categorizes database drivers in four ways: 7. the type of each column. 7. Table below defines the methods of the ResultSet interface. developers should be aware of the requirements to run the applications when the JDBCODBC bridge is implemented and the clients must have a local copy of the ODBC driver.6.2 Type 2: The Native Library-to-Java Driver 93 .6. Also. Figure 7. they can be selected either by name or the number of the column. It is a driver that provides access to database through ODBC drivers. and client-side libraries since ODBC calls are made using binary C calls.

Application Space Java Application SQL Native Database Library Command Result Set Type 2 Jdbc Driver Proprietary Protocol Library Database Fig. It makes it possible to swap database without affecting the client. This type of driver translates JDBC calls into a database-independent network protocol that is sent to a middleware server. Sybase. These drivers were first available for Oracle. 7. The result is routed back through the middleware server and sent back to the client.6.3 Type 3: The Network Protocol Driver The JDBC-Network protocol drivers are a three-tier solution. This server then translates this DBMS-independent protocol into a DBMS-specific protocol. which is sent to a particular database. These drivers use C language libraries that provide vendor-specific functionality and tie these libraries to the JDBC. and other client-librarybased RDBMSs. 94 . Informix. Figure 7.6 shows the interaction of the Native Library-to-Java Drive. This type of solution makes it possible to implement a pure Java client. This is by far the most flexible JDBC solution.J2EE Servlets & JSP =========================================================================================================================== To translate JDBC to the native client library.6 The Native library-to-Java Driver 7. the Native Library-to-Java Driver uses native C language library calls.

The type 4 Driver has a very distinct advantage over all the other driver types.4 Type 4: The Native Protocol Driver The Type 4 drivers are pure Java drivers that communicate directly with the vendor’s database.8 95 . Figure 2. Application Java Application Space Type 4 JDBC Driver SQL Command Using Proprietary Protocol Result Using Proprietary Protocol Database Fig. It has no additional middleware layer.J2EE Servlets & JSP =========================================================================================================================== Java Application Application Space SQL Command Type 3 Jdbc Driver Result Set Middleware Space JDBC Driver Proprietary Protocol Database Fig.8 shows the communication of a Type 4 driver.7 The Network protocol Driver 7. This is done through converting JDBC commands directly into the database engine’s native protocol. 7.6. which improves performance tremendously. 7.

System.*. //To create a statement object to execute the SQL statement Stmt = Conn.sql.9 96 . while(rs.createStatement().executeQuery("select empno. StName = rs.7 Executing SQL Commands Using JDBC drivers 7.out.out. Add fields ENAME. empname from emp").J2EE Servlets & JSP =========================================================================================================================== The Native Protocol Driver 7. 7. create a table inside the Oracle database with the name emp. Fig. //Sends the SQL statement to the DBMS and executive rs = Stmt. //Processing the results System.println(StNo+"\t"+StName). HIREDATE and DEPTNO.getConnection("jdbc:odbc:empDB"). //Initialize and load the JDBC-ODBC driver. // To get a database connection Conn =DriverManager.getInt(1).7.getString(2). Now let us start making the programs • Program to retrieve the result from the Table The following program executes a SQL SELECT statement to list all the employee in the database.odbc.forName ("sun. } } } The output is as shown in Figure 7. Connection Conn. String StName.1 Using Type 1 Driver(JDBC ODBC Bridge Driver) Before you start writing the programs using Type 1 Drivers. class sqldemo1 { public static void main(String a[] ) throws Exception { int StNo.println("Empno "+" Name ").9. DESIG. ResultSet rs.jdbc.next()) { StNo = rs. Class. import java. EMPNO.JdbcOdbcDriver"). Statement Stmt.

User=<username>. When a ResultSet object is returned from a query. class OraSqlUpdate { public static void main(String a[] ) throws Exception { int StNo. when you use the jdbc:odbc driver.JdbcOdbcDriver”).forName (“sun. The next () method returns a boolean value is true if the next row is returned and false it the end of the table is reached. A normal ODBC databases JDBC URL locks like the following: jdbc:odbc:<ODBC DSN>. String StName. import java.jdbc. Step 2: The program calls the getConnection() method to get the Connection object. Hence. each how is processed until there are no more rows. the JDBC url should contain a data source name (DSN). you then invoked the executeQuery() method of the Statement interface. Step 3: With the help of the object created in step 2. //Initialize and load the JDBC-ODBC driver.PW=<password> That is.*. It must be initialized and loaded with the following method as described earlier: Class. This resulted in the query being processed by the database and a ResultSet object being returned. The pointer is referred to as a cursor. the following steps have been followed: Step 1: The program initializes and loads the JDBC-ODBC driver using the static method forName() of the class Class.sql. and password for the ODBC data source.odbc. user ID. In the next example the first three steps will be the same. 97 . ResultSet rs. The next () method of the ResultSet interface is used to move the cursor to the next row of the table. Step 4: With the help of the Statement object. the cursor initially points immediately before the first row of the table.J2EE Servlets & JSP =========================================================================================================================== Output of the program While creating the above program. Statement Stmt. Step 5: A ResultSet object maintains a pointer to a row within the tabular results. it invokes the method createStatement() to create the Statement object and prepares SQL treatment. • Program to Update the Table The following program is used to update the name and addr of the student whose number is 2. Connection Conn. Note: The odbc subprotocol name is reserved for ODBC style data sources. passing it the Select empno and empname From emp SOL statement as an argument.

} } The output is as shown in Figure 7. which updates the empno and empname of a particular employee.println("Number of records updated is "+n).forName ("sun. The executeUpdate() method of the Statement interface takes in the SQL Update statement as an argument and returns an integer value representing the number of rows updated.createStatement(). As discussed earlier. Fig. The following section describes the usage of PreparedStatement and CallableStatement interfaces in programs. 7. which we followed in the previous example. //Sends the SQL statement to the DBMS and executive int n= Stmt. • Programs to insert the row using PreparedStatement interface 98 . the UpdateName () method has been created. Here instead of executeQuery().odbc.jdbc. since the PreparedStatement parameters are considered as In (input) parameters and they have to filled in using the setType methods."scott". addr='China' where no=2"). the method executeUpdate() has been invoked. While creating the above program the first three steps."tiger").10 Output of the program In the code given above. whose name is passed as an argument. The only difference is in fourth and fifth step. //To create a statement object to execute the SQL statement Stmt = Conn. You have to use the setType methods defined in Table 1. the PrepareStatement interface provides an efficient mechanism for passing a precompiled SQL statement that uses parameters.out.J2EE Servlets & JSP =========================================================================================================================== Class. are the same.6 in the following programs.10.executeUpdate("Update stud set name='yanu'. // To get a database connection Conn =DriverManager.JdbcOdbcDriver").getConnection("jdbc:odbc:OraDsn". In the above code it returns 1. System.

jdbc.8.setInt (2.forName("sun. • Program to invoke a stored procedure using CallableStatement interface 99 .No number(10))").sql.executeUpdate(). which is used with parameterized SQL statements. System. p.JdbcOdbcDriver"). Further. Fig. p1. PreparedStatement p1 = c.setString (1. the executeUpdate() method of the PreparedStatement interface has been invoked to execute the SQL statement. public class preparedmo1 { public static void main(String a[]) throws Exception { Class. which is called an IN parameter.*. 7. after initializing and loading the Driver the prepareStatement() method is invoked using the object of the Connection interface.1000). } } The output is as shown in Figure 7.executeUpdate().out. "soma"). Connection c = DriverManager.8 Output of the program In the code given above. This method returns the object of the PreparedStatement interface. These methods are organized into the type of value to which a parameter is to be set. p. "tiger").println("value inserted"). The PreparedStatement provides several set methods for setting the values of IN PARAMETERS. "scott".getConnection("jdbc:odbc:OraDsn". which is passed as an argument to the prepareStatement() method.prepareStatement ("insert into Empl values(?. ?)"). p.odbc. These parameterized SQL statements replace a constant SQL statement with a question mark(?).prepareStatement("Create table Empl(Name varchar2(30).J2EE Servlets & JSP =========================================================================================================================== The following program inserts rows in the Students table where you can see the usage of the PreparedStatement parameters: import java. PreparedStatement p = c.

VARCHAR). BufferedReader b = new BufferedReader(new InputStreamReader(System. System. c1. this interface allows the developer to execute SQL stored procedures and pass IN and OUT parameters.in)).setInt(1. Step 2: Create a DSN(data source name) Step 3: Compile the program using javac Step 4: Run the program using java Step 5: In the command promptness pass the empno."tiger").odbc. 100 .jdbc.J2EE Servlets & JSP =========================================================================================================================== Now. class caloric { public static void main(String a[]) throws Exception { Class. int p1= Integer.out."scott". p1).parseInt(b.12. all of the execute and setType methods are available.println("The name selected for the given number is "+output). Connection con = DriverManager.execute(). c1.*.getString(2). end.forName("sun.readLine()). c1. CallableStatement c1 = con. nam out varchar2 ) is begin select name into nam from stud where no=num.sql. System.out. As discussed earlier. String output =c1. Types. } } To run the program given above follow the steps given below: Step 1: create or replace procedure selectpro (num in number.getConnection("jdbc:odbc:OraDsn".prepareCall ("{call selectpro (?.registerOutParameter(2.println("enter the no").JdbcOdbcDriver"). import java. You will get the corresponding deptno The output is as shown in Figure 7. import java.io. The following example will demonstrate the method of passing IN and OUT parameters to stored procedures and executing them. we will see the usage of the CallableStatement interface. ?)}"). Since the CallableStatement inherits the method from the Preparedstatement interface.*.

The stored SQL procedure is passed as an argument to the prepareCall() method.OracleDriver()). you have to specify the driver name. These files are present inside the folder Oracle\Ora8i\jbdc\lib. you must copy one of the two files called clsses81. while(rs. Connection con = DriverManager. the method prepareCall() of the Connection interface has been invoked to create the object of CallableStatement.getString(2)+" : "+rs. } }catch(Exception e) {e.next()) { System. The code given below demonstrates the usage of the Native Library-to-Java Driver: In this code we are creating a new table.println(rs.*.jdbc.jdbc. Statement st=con.getInt(1)+" : "+rs.out.zip and classes101. While creating the codes for Type 2 and Type 4 drivers.zip to the folder from where you are running the codes and set the classpath to that folder.driver. 7.printStackTrace(). ResultSet rs=st.2 Using Type 2 Driver (The Native Library-to-Java Driver) Before executing JDBC codes through Type 2 and Type 4.executeQuery("Select * from dept").sql.driver."scott".7.OracleDriver where the specification of both Type 2 and Type 4 drivers are available."tiger"). which is passed as an argument with the getConnection() method. import java. Secondly. class orasql { public static void main(String ar[]) { try { DriverManager. except the first two all the steps are same. Here you have to load and register the driver by specifying the classname oracle.createStatement().getString(3)).getConnection ("jdbc:oracle:oci8:@".registerDriver(new oracle. 7. It is parameterized using question marks in the same manner as that discussed for the PreparedStatement interface.12 Output of the program In the above program after initializing and loading the driver. inserting a record it and finally displaying the record. } } 101 .J2EE Servlets & JSP =========================================================================================================================== Fig.

//Sends the SQL statement to the DBMS and executive rs = Stmt. Statement Stmt. ename from emp"). while(rs.sq1 package contains two MetaData interfaces.createStatement().J2EE Servlets & JSP =========================================================================================================================== } 7.out. // To get a database connection Conn =DriverManager.getConnection("jdbc:odbc:thin:@dhs04:1521:dhs04db". keywords. database product name."scott". the column heading.registerDriver(new oracle.jdbc. String StName. and the name of the JDBC driver supported by the database.driver. system functions.8 The ResultSetMetaData Interface The java.println(StNo+"\t"+StName). The following table explains some of the methods of the ResultSetMetaData interface." tiger"). //Processing the results System. //Initialize and load the JDBC-ODBC driver. Connection Conn. StName = rs. //To create a statement object to execute the SQL statement Stmt = Conn. the DatabaseMetaData and the ResultSetMetaData interface. DriverManager. The following code displays all the name of the employees from the table emp.7. System. } } } 7. class sqldemo1 { public static void main(String a[] ) throws Exception { int StNo.*. and the properties of each column. ResultSet rs. The DatabaseMetaData interface is used to obtain information about a database such as a list of all tables in the database.out.OracleDriver()). The ResultSetMetaData interface is used to obtain information about the columns stored in a ResultSet object such as the datatype.getInt(1).sql. Method int getColumnCount ( ) String getColumnName column_number) String getColumnTypeName (int (int Description Returns the number of columns stored in a ResultSet object Returns the column name of the specified column Returns the database specific datatype 102 .getString(2).println("Empno "+" Name ").3 Using Type 4 Driver (The Native Protocol Driver) The code given below demonstrates the usage of Native Protocol Driver. import java.next()) { StNo = rs.executeQuery("select empno.

Example: import java. int colCount=rsmd.out.println ("Could not execute the query" +e).getConnection("jdbc:odbc:OraDsn". public class QueryApp { public static void main(String a [ ]) { ResultSet result.next()) { //Code to retrieves and display each record of the result set for (int i=1.addr from stud"). System. Connection con = DriverManager.println(rowdata).trim ( ) method is used to remove leading and trailing blanks in a string */ for (int i=1. i<=colCount. i++) { rowdata=rowdata+" : "+rsmd.trim(). result=stat. Statement stat=con.out. while (result. "tiger" ). } } } 103 .*.JdbcOdbcDriver"). rowdata=" ". ResultSetMetaData rsmd=result.getColumnCount ( ). } } catch (Exception e) { System. i++) { /* Retrieve the value present in the ith column of the current row */ rowdata=rowdata+" : "+result. //Code to retrieve and display the column headings /* The String.sql.out.createStatement().J2EE Servlets & JSP =========================================================================================================================== column_number) of the specified column.executeQuery("Select name.println("\n"). i<=colCount.out. try { Class. rowdata=" ".forName ("sun.odbc.getMetaData( ). String rowdata="".jdbc.out. System. } System.getString(i).getColumnName(i). } System. "scott".println("---------------------------------------------------").println (rowdata).trim(). You use the getMetaData ( ) method of the ResultSet class to obtain a reference to the ResultSetMetaData object of a particular result set.

J2EE Servlets & JSP =========================================================================================================================== Glossary 104 .

Application client module A software unit that consists of one or more classes and an application client deployment descriptor. Application client A first-tier client program that executes in its own Java Virtual Machine. The J2EE platform requires three types of authentication: basic. Atomic Refers to an operation that is never interrupted or left in an incomplete state under any circumstance. Application client container A container that supports application clients and provides a federated view of the J2EE platform APIs. 105 . A programming model that defines how to use and combine the features of the J2EE platform to create solutions for common application domains in the enterprise. JSP page definitions. APM Application Programming Model.Glossary ========================================================================================================================== Glossary Application Assembler A person that combines components and modules into larger deployable application units. Atomic Refers to an operation that is never interrupted or left in an incomplete state under any circumstance. form-based. and any required deployment descriptors. and mutual. Authentication The process by which an entity proves to another entity that it is acting on behalf of a specific identity. Application Component Provider A vendor that provides the Java classes that implement components' methods.

the tools located in the JDK(TM) 1. this logic is implemented by the methods of an enterprise bean. In the Enterprise JavaBeans model. 106 . Business method A method of an enterprise bean that implements the business logic or rules of an application. Bean-managed transaction When an enterprise bean defines the boundaries of the transaction. such as compute power and large memory capacity. Business logic The code that implements the functionality of an application. Classpath A classpath is an environmental variable which tells the Java(TM) virtual machine* and Java technology-based applications (for example. the client is a process that remotely accesses resources of a compute server. Client In the client/server model of communications. Callback methods Methods in a component called by the container to notify the component of important events in its life cycle.1. Bean-managed persistence When the transfer of data between an entity bean instance's variables and the underlying resource manager is managed by the entity bean. Bean-managed transaction When an enterprise bean defines the boundaries of the transaction.X\bin directory) where to find the class libraries.Glossary ========================================================================================================================== Basic authentication When a Web server authenticates an entity with a user name and password obtained using the Web client's built-in authentication mechanism. Bean A reusable software component. including user-defined class libraries. Beans can be combined to create an application.

Context attribute An object bound into the context associated with a servlet. Comment In a program. applets. The contract includes: life cycle management of the component. 107 . Web components..*/. a context interface that the instance uses to obtain various information and services from its container. The J2EE platform defines four types of components: enterprise beans. Each component names and accesses its environment configuration values using the java:comp/env JNDI context. Commit The point in a transaction when all updates to any resources involved in the transaction are made permanent. Components are configurable at deployment time. and a list of services that every container must provide for its components. Component contract The contract between a component and its container. explanatory text that is ignored by the compiler.. Component An application-level software unit supported by a container. and codebase specifies the URL of the directory containing the file. Container-managed persistence When transfer of data between an entity bean's variables and the underlying resource manager is managed by the enterprise bean's container.Glossary ========================================================================================================================== Codebase Works together with the code attribute in the <APPLET> tag to give a complete specification of where to find the main applet class file: code specifies the name of the file. In programs written in the Java(TM) programming language. Container-managed transaction When an EJB container defines the boundaries of a transaction. and application clients. An entity bean must use container-managed transactions. Component environment A set of requirements defined by the Application Component Provider required to be available to a J2EE component in its naming environment. such as a JDBC DataSource or a simple value such as a tax rate. The environment entries are declaratively specified in the component's deployment descriptor. These values can be objects a component is dependent on. comments are delimited using // or /*.

deployment. life cycle management.Glossary ========================================================================================================================== Conversational state The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. 108 . that is. Deprecation Refers to a class. EJB context An object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method. and may cease to exist in a future version. Deployment The process whereby software is installed into an operational environment. and other services. This contract specifies a runtime environment for enterprise beans that includes security. EJB Container Provider A vendor that supplies an EJB container. An EJB container is provided by an EJB or J2EE server. The EJB home object implements the enterprise bean's home interface. constructor. EJB home object An object that provides the life cycle operations (create. The client references an EJB home object to perform life cycle operations on an EJB object. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language. remove. find) for an enterprise bean. interface. The client uses JNDI to locate an EJB home object. method or field that is no longer recommended. the fields that would be stored by serializing the bean instance. The class for the EJB home object is generated by the container's deployment tools. Deployer A person who installs modules and J2EE applications into an operational environment. concurrency. EJB container A container that implements the EJB component contracts of the J2EE architecture. transaction. Deployment descriptor An XML file provided with each module and application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

a mainframe transaction processing system. An EJB server may host one or more EJB containers. a business objects in an ERP system.jar file. EJB Server Provider A vendor that supplies the EJB server. an EJB container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the participating resource managers. and a legacy database system. and a transaction program in a transaction processing system. The J2EE architecture assumes that an EJB container is hosted by an EJB server from the same vendor so does not specify the contract between these two entities. A client never references an enterprise bean instance directly. For example.jar file A JAR archive that contains an EJB module. The class of an EJB object is generated by the container's deployment tools. These applications provide an information infrastructure for an enterprise. Enterprise Bean Provider An application programmer who produces enterprise bean classes. These services are exposed to clients as local and/or remote interfaces. EJB object An object whose class implements the enterprise bean's remote interface. EJB server Software that provides services to an EJB container. remote and home interfaces. and deployment descriptor files. An EIS offers a well-defined set of services to its clients. Examples of EISs include: an ERP system.Glossary ========================================================================================================================== EJB . 109 . EIS resource An entity that provides EIS-specific functionality to its clients. and packages them in an EJB . Enterprise Information System (EIS) The applications that comprise an enterprise's existing system for handling company-wide information. a client always references an EJB object. Examples are: a record or set of records in a database system. EJB module A software unit that consists of one or more enterprise beans and an EJB deployment descriptor.

its primary key. and multi-user and secure. Enterprise Edition (J2EE platform) An environment for developing and deploying enterprise applications.ear file with a J2EE application deployment descriptor. used to fetch hypertext objects from remote hosts. based on TCP/IP. See also J2EE application Any deployable unit of J2EE functionality. J2EE server The runtime portion of a J2EE product.Glossary ========================================================================================================================== Enterprise JavaBeans(TM) (EJB) A component architecture for the development and deployment of objectoriented. J2EE applications are typically engineered to be distributed across multiple computing tiers. distributed. the entity bean. application programming interfaces (APIs). Applications written using the Enterprise JavaBeans architecture are scalable. 110 . HTTP HyperText Transfer Protocol. transactional. enterprise-level applications. An entity bean can manage its own persistence or it can delegate this function to its container. An entity bean is identified by a primary key. J2EE Product Provider A vendor that supplies a J2EE product. The J2EE platform consists of a set of services. Java(TM) 2 Platform. The Internet protocol. Standard Edition (J2SE platform) The core Java technology platform. A J2EE server provides Web and/or EJB containers. Webbased applications. and protocols that provide the functionality for developing multi-tiered. Entity bean An enterprise bean that represents persistent data maintained in a database. If the container in which an entity bean is hosted crashes. This can be a single module or a group of modules packaged into an . Java(TM) 2 Platform. J2EE product An implementation that conforms to the J2EE platform specification. and any remote references survive the crash.

The Java runtime environment consists of the Java virtual machine*. in which the methods of remote objects written in the Java programming language can be invoked from other Java virtual machines*. JavaBeans(TM) A portable. Java(TM) Remote Method Invocation (RMI) A distributed object model for Java(TM) program to Java program.Glossary ========================================================================================================================== Java(TM) 2 SDK. Java(TM) Runtime Environment (JRE) A subset of the Java Development Kit (JDK(TM)) for end-users and developers who want to redistribute the runtime environment alone. and supporting files. and server-side Java objects to return dynamic content to a client. Like all scripting languages. JavaServer Pages(TM) (JSP) An extensible Web technology that uses template data. custom elements. JavaScript(TM) A Web scripting language that is used in both browsers and Web servers. scripting languages. Enterprise Edition Sun's implementation of the J2EE platform. Typically the template data is HTML or XML elements. possibly on different hosts. platform-independent reusable component model. Java Database Connectivity (JDBC(TM)) An industry standard for database-independent connectivity between the Java(TM) platform and a wide range of databases. and so on. Java(TM) Message Service (JMS) An API for using enterprise-messaging systems such as IBM MQ Series. Java Naming and Directory Interface(TM) (JNDI) A set of APIs that assists with the interfacing to multiple naming and directory services. 111 . This implementation provides an operational definition of the J2EE platform. it is used primarily to tie other components together or to accept user input. and in many cases the client is a Web browser. The JDBC(TM) provides a calllevel API for SQL-based database access. TIBCO Rendezvous. the Java core classes.

an action. JSP application A stand-alone Web application written using the JavaServer Pages technology. images. applets. Actions follow the XML syntax for elements with a start tag. distributed A JSP container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts. JSP action. a body and an end tag. HTML files.Glossary ========================================================================================================================== JSP action A JSP element that can act on implicit objects and other server-side objects or can define new scripting variables. servlets. if the body is empty it can also use the empty tag syntax. custom An action described in a portable manner by a tag library descriptor and a collection of Java classes and imported into a JSP page by a taglib directive. converted to a String. An element can be a directive. JSP container. 112 . JSP declaration A JSP scripting element that declares methods. JSP element A portion of a JSP page that is recognized by a JSP translator. JSP container A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet. or a scripting element. JSP directive A JSP element that gives an instruction to the JSP container and is interpreted at translation time. variables. JSP action. The tag must use a prefix. standard An action that is defined in the JSP specification and is always available to a JSP file without being imported. including JSP files. and placed into the implicit out object. and JavaBeans components. or both in a JSP file. JSP expression A scripting element that contains a valid scripting language expression that is evaluated.

JSP tag library A collection of tags identifying custom actions described via a tag library descriptor and Java classes... platform-independent solution to speed and simplify the deployment and management of your Internet and Intranet Web sites. core JSP tags. easy-to-administer. Java Software division. scriptlet. because it is surrounded by angle brackets. and who’s content is written according to the scripting language used in the JSP page. JSP scriptlet A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. currently known as Sun Microsystems. Java technology-based server applications. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java". custom JSP tags. secure. 113 . and scripting language statements in order to display dynamic pages in a Web browser. Inc. JSP tag A piece of text between a left angle bracket and a right angle bracket that is used in a JSP file as part of a JSP element. extensible.jsp extension that a developer authors using standard HTML tags. as opposed to data. JavaSoft(TM) A former business unit of Sun Microsystems. JSP scripting element A JSP declaration. fullfeatured. A portable Java class library that has a unique URI and that defines custom tags that perform specialized tasks. Passivation The process of transferring an enterprise bean from memory to secondary storage. A JSP tag library can be imported into any JSP file and used with various scripting languages.Glossary ========================================================================================================================== JSP file A file named with a . The tag is distinguishable as markup. Java Web Server(TM) The easy-to-use. It provides immediate productivity for robust. JSP page A text-based document using fixed template data and JSP elements that describe how to process a request to create a response. whose tag syntax is defined by the JSP specification. or expression. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java". Inc.

Primary key An object that uniquely identifies an entity bean within a home. Servlet A Java program that extends the functionality of a Web server. and set and store attributes that other servlets in the context can use. The mapping is used to map requests to servlets. such as calculations or accessing a database. While a session bean may be transactional. and formats responses. All servlet containers must support HTTP as a protocol for requests and responses.jsp extension is implicitly mapped. Session bean objects can be either stateless or they can maintain conversational state across methods and transactions. it is not recoverable should a system crash occur. If the container handling the request is a JSP container.Glossary ========================================================================================================================== Persistence The protocol for transferring the state of an entity bean between its instance variables and an underlying database. obtain URL references to resources. Servlet container. Using the context. Servlet context An object that contains a servlet's view of the Web application within which the servlet is running. A session bean performs operations. but may also support additional request-response protocols such as HTTPS. generating dynamic content and interacting with Web clients using a request-response paradigm. then the EJB 114 . a URL containing a . a servlet can log events. decodes requests. Servlet container A container that provides the network services over which requests and responses are sent. If they do maintain state. Session bean An enterprise bean that is created by a client and that usually exists only for the duration of a single client/server session. distributed A servlet container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts. Servlet mapping Defines an association between a URL pattern and a servlet. Session An object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. for the client.

Thin Client A system that runs a very light operating system with no local system administration and executes applications delivered over the network. The URL consists of the Context Path + Servlet Path + PathInfo. and are able to modify their operation to track along with changes in a user's current situation. the path prefix starts with a / character but does not end with a / character. the session bean object itself must manage its own persistent data. what. where Context Path is the path prefix associated with a servlet context that this servlet is a part of. This includes the classic "who. A standard for writing a text reference to an arbitrary piece of data in the WWW.Glossary ========================================================================================================================== container manages this state if the object must be removed from memory. If this context is the default context rooted at the base of the web server's URL namespace. Servlet Path is the path section that directly corresponds to the mapping. An ISO/ANSI/ECMA standard that specifies a way to annotate text documents with information about types of sections of a document. Smart Web Services Smart Web Services extend the basic concept of web services by adding the dimension of user context. Otherwise. A URI is either a URL or a URN. However. A URI is an abstract superclass. Stateful session bean A session bean with a conversational state. host specifies the Internet name of the host on which to find it. and localinfo is a string (often a file name) passed to the protocol handler on the remote host. URL path The URL passed by a HTTP request to invoke a servlet. A compact string of characters for identifying an abstract or physical resource. Stateless session bean A session bean with no conversational state. the path prefix will be an empty string. This path starts with 115 . why" descriptors that come together to define a user's context at a any given moment. URL Uniform Resource Locator. A URL looks like "protocol://host/localinfo" where protocol specifies a protocol to use to fetch the object (like HTTP or FTP). SGML Standardized Generalized Markup Language. when. URLs and URNs are concrete entities that actually exist. All instances of a stateless session bean are identical. which activated this request. URI Uniform Resource Identifier. where.

A container that provides the same services as a JSP container and federated view of the J2EE platform APIs. deployment. This contract specifies a runtime environment for Web components that includes security. Web container A container that implements the Web component contracts of the J2EE architecture. distributable A Web application that uses J2EE technology written so that it can be deployed in a Web container distributed across multiple Java virtual machines running on the same host or different hosts. concurrency. transaction. Web application.Glossary ========================================================================================================================== a / character. XML Extensible Markup Language. J2EE deployment descriptors are expressed in XML. Web component A component that provides services in response to requests. and other services. The deployment descriptor for such an application uses the distributable element. 116 . A markup language that allows you to define the tags (markup) needed to identify the data and text in XML documents. PathInfo is the part of the request path that is not part of the Context Path or the Servlet Path. life cycle management. either a servlet or a JSP page. A Web container is provided by a Web or J2EE server.

Glossary ========================================================================================================================== Appendix 117 .

PaymentRequired 402 The parameter to this message gives a specification of charging schemes acceptable. Unauthorized 401 The parameter to this message gives a specification of authorization schemes which are acceptable. Authorization will not help. Service temporarily overloaded 502 The server cannot process the request due to a high load (whether HTTP servicing or other requests). As from the point of view of the client and the HTTP transaction the other service is hidden within the server. Bad request 400 The request had bad syntax or was inherently impossible to be satisfied. 118 . Not implemented 501 The server does not support the facility required. Gateway timeout 503 (TO BE DISCUSSED) This is equivalent to Internal Error 500. but has more diagnostic value.Appendix A ================================================================================================================================ Appendix A Common HTTP Status Codes OK 200 The request was fulfilled. this indicates that the response from the other service did not return within a time that the gateway was prepared to wait. The client should retry the request with a suitable Authorization header. this maybe treated identically to Internal error 500. The client may retry the request with a suitable ChargeTo header. but in the case of a server which is in turn accessing some other service. The implication is that this is a temporary condition which maybe alleviated at other times. Not found 404 The server has not found anything matching the URI given Internal Error 500 The server encountered an unexpected condition which prevented it from fulfilling the request. Forbidden 403 The request is for something forbidden.

The implicit objects re listed below request response pageContext session application out config page exception 119 .toLocaleString() %> --> Displays in the page source: <!-. These objects are parsed by the JSP engine and inserted into the generated servlet. JSP Syntax <%-. JSP Syntax <!-. you can escape it by typing --%\>. You can see the comment by viewing the page source from your Web browser.Date()). 2004 --> Q: What is a Hidden Comment? A: A comments that documents the JSP page but is not sent to the client. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.util. If you need to use --%> in your comment.comment [ <%= expression %> ] --> Example 1 <!-. either in the displayed JSP page or the HTML page source.comment --%> Q: What are implicit objects? List them? A: Certain objects that are available for the use in JSP documents without being declared first. The JSP engine handles an output comment as uninterpreted HTML text. The JSP engine ignores a hidden comment. A hidden comment is not sent to the client. and does not process any code within hidden comment tags. returning the comment in the HTML output sent to the client. You can use any characters in the body of the comment except the closing --%> combination.Appendix B ================================================================================================================================ Appendix B FAQ Q: What is a output comment? A: A comment that is sent to the client in the viewable page source.This is a comment sent to client on January 24.This is a comment sent to client on <%= (new java.

Appendix B
================================================================================================================================

Q: Difference between forward and sendRedirect? A: When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. Q: Explain the life-cycle methods in JSP? A: The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which intern extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two methods - spinet() and jspDestroy() that must be implemented by all JSP pages regardless of the clientserver protocol. However the JSP specification has provided the HttpJspPage interface specifically for the JSP pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance. Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface? A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root. The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must start with a "/" and are interpreted as relative to current context root. Q: Explain the directory structure of a web application. A: The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml 2. classes directory

120

Appendix B
================================================================================================================================

3. lib directory Q: Explain ServletContext. A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application. Q: What is preinitialization of a servlet? A: A container doesn’t initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet. Q: What is the difference between Difference between doGet() and doPost()? A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string. Q: What is the difference between HttpServlet and GenericServlet? A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

121

Appendix C
================================================================================================================================

Appendix C
MVC Architecture 1.What are Design Patterns? As you design and build different applications, you continually come across the same or very similar problem domains. This leads you to find a new solution for the similar problem each time. To save time and effort, it would be ideal if there was a repository which captured such common problem domains and proven solutions. In the simplest term, such a common solution is a design pattern. The repository or place of reference that contains these patterns is a design pattern catalog. A design pattern describes a proven solution, from experienced hands, for a recurring design problem. These solutions are very generic. They are described in well-defined Pattern Templates, with the most popular template defined by the Gang of Four. The pattern template usually includes a name that gives an idea as to what that pattern is about, followed by where the pattern is applicable, the motivation, the issues in implementation, and so on. Apart from describing the problem and illustrating the solution, the pattern also explains the implementation issues involved and consequences, if any, of using the pattern. Use of such patterns makes the design of an application transparent. These patterns have been used successfully by developers in their respective fields, and therefore, the pros and cons of the pattern (as well as implementation issues) are known beforehand. All design patterns are reusable and can be adapted to particular contexts. This gives you flexibility. The use of design patterns related to J2EE applications gives the added advantage of showing solutions in terms of J2EE platform technologies.

2.Design Patterns For Building Flexible and Maintainable J2EE Applications Multi-tiered J2EE applications consist of a number different views and components in the middle tier, possibly distributed. The following sections of this article suggest some design patterns that can help you keep typical J2EE applications extensible, flexible, and maintainable. Instead of discussing some abstract scenarios, this articles takes an imaginary sample application and tries to give you an understanding of these patterns in the context of this sample application. Once you know the sample application it is easier to extend the use of these patterns to other application scenarios. Take the case of an enterprise application for financial services over the web. Visitors to this site can browse through the list of services, create accounts, place orders for the products made available by the financial service, and so on. Also assume that this application allows existing customers to change their account details and profile, make use of services, and so on. Typically this kind of application has multiple views

122

If that were the case. In this scenario. solving this problem by mixing data access with views is problematic because • You must develop different versions of the same application to suit each type of client needs support • Since the code for views and that for data access/modification is intertwined. 3. and so on. use the services. The figure below depicts the MVC architecture. look at some recurring problems and see how you can use specific patterns to build a flexible and maintainable application.Model-View-Controller Problem Domain All would be well if you were building this enterprise application for a single type of client. The business logic represents the user's account. in addition to other types of traditional clients. you can separate the data access logic from the data presentation logic. The ModelView-Controller (MVC) architecture is the suggested solution. MVC has been used very effectively in GUI-type applications. the code for the data access/modification is duplicated everywhere. profile. You can also build a flexible and easily extensible controller that controls the whole flow of the application. ordering for services. take note that: • Regardless of the client type. we could simply mix the data access / data modifying logic with the logic for the various client views. But with the advent of the completely interconnected and wireless world. the catalog of services. access profiles. thereby making the application almost unmaintainable • The development life cycle is extended unnecessarily. • Modifying either a type of client or data accessing / modifying logic should not affect the other components of the application. By applying the MVC architecture to a J2EE application. the data being accessed and displayed comes from the same enterprise data source. You need a solution that lets you develop loosely-coupled applications. there are client devices ranging from PDAs to cell phones to a browser on a powerful desktop. 123 . Suggested Solution In finding a solution for this problem. With this sample application in mind. and to get other information. • All clients must be able to modify the data source.Appendix C ================================================================================================================================ or screens which users click through to search for lists of services. as separate entities in the form of Enterprise JavaBeans (EJB).

• The VIEW can access the data through the model and decide on how to present them to the client. 124 . The VIEW updates itself when the MODEL changes. • The various screens of the application forms the VIEW of the MVC architecture. and decide on the next screen to be displayed once the model completes the processing request It is very difficult to fully showcase the MVC architecture in the form of a small example code. The CONTROLLER also decides on the next view to be presented depending on the last client action and results of the corresponding MODEL action(s). The VIEW must ensure that the presentation changes as and when the MODEL changes. Applying the above logic to the sample financial application. you build the application as follows: • The business logic of the application is represented by EJBs that form the MODEL of MVC architecture. • The CONTROLLER of the application is a set of objects that receive the user actions. • The CONTROLLER can interact with the view and convert the client actions into actions that are understood and performed by the MODEL.Appendix C ================================================================================================================================ The MVC architecture can be mapped to multi-tiered enterprise J2EE applications as follows: • All enterprise data and the business logic to process the data can be represented in the MODEL. The MODEL responds to requests from CONTROLLER to access / modify the data it represents. convert them into requests understood by the model. The Java Pet Store Demo application from the J2EE BluePrints Program is a good example of a complete J2EE application that is based on the MVC architecture.

• MVC decouples presentation. user interaction. maintainability. 125 . and thereby. • By separating the presentation from model and overall application flow. This also makes it much easier to enable support for new types of clients.Appendix C ================================================================================================================================ Points to Note Here are some points to note: • MVC architecture is suitable for a highly interactive system that requires extensibility. this architecture enables division of developer responsibilities. produces faster time to market. and multiple user views. and system model. • Code duplication is minimized by using this architecture. • Presenting multiple views for multiple data sets is made easy because of the decoupling.

Kathy Sierra . Bert Bates Publication APress Wiley Publishing Inc. Weblogic Home Website EJB Tutorial 126 . John Crupi Richard MonsonHaefel.experts-exchange. Bill Burke.com www. containing the most current information on the J2EE Platform The complete J2EE API.html www.Reference ================================================================================================================================ References Book References: Title Professional Java Server Programming Expert One-on-One J2EE Design and Development Core J2EE Patterns: Best Practices and Design Strategies Enterprise JavaBeans Head First Servlets & JSP Author Subramanyam Allamaraju Rod Johnson Deepak Alur.sun.com/j2ee/docs.com http://java.3 Edition 2003 Second Edition Fourth Edtion 2004 Online References: URL http://java. Sun Press O’Reilly O’Reilly Edition J2EE 1. J2EE Interview questions. Sacha Labourey Bryan Basham.com http://bea.ejbtut.sun. Dan Malks.com Description The J2EE home website.

Reference ================================================================================================================================ Lab Works 127 .

forName("com. import java. Statement st=con.Reference ================================================================================================================================ Servlet & JSP Programs Servlet 1.getString(2). while(rs. public class servlet1 extends HttpServlet { public void doGet(HttpServletRequest req.Simple Servlet Program: import javax.getInt(1). Class.servlet. System.println("Driver has loaded"). out. name=rs.println("\t\t "+no+"\t\t "+name+"\t\t "+place).lang.createStatement(). 128 . import java.Driver").jdbc. System. String name.out.*.*.executeQuery("select * from emp1")."root".out.*.*. System.HttpServletResponse res) { try{ PrintWriter out=res. class db1 { public static void main(String args[]) throws Exception { int no.sql.next()) { no=rs.println("***WELCOME***").io.println("\t\t NO \t\t NAME \t\t PLACE")."admin").http. import javax.sql. ResultSet rs=st. JDBC: import java. } } } 2. System.getString(3).mysql.*.place.out.getConnection("jdbc:mysql://localhost:3306/prem ".*.out.servlet.getWriter().setContentType("text/html").println("Connection Established"). import javax. Connection con=DriverManager. place=rs. res.

} catch(Exception e){} } } } 129 . out.IOException { try { int no.place.getString(2).setContentType("text/html").http. name=rs.println(name).executeQuery("select * from emp1").println("<br>").mysql.io. out.*. out. out.forName("com.println("NO NAME PLACE<br>"). res. Connection con=DriverManager. out.next()) { no=rs. java.println(no). ResultSet rs=st.servlet. java.createStatement(). Statement st=con.*."root".sql. while(rs.getConnection("jdbc:mysql://localhost:330 6/prem". public class servlet3 extends HttpServlet { public void service(HttpServletRequest req.servlet.println(place).getString(3). HttpServletResponse res) throws ServletException. PrintWriter out=res.*.jdbc.getInt(1).JDBC & Servlets: import import import import javax. out. String name. place=rs.Reference ================================================================================================================================ } } catch(Exception e){} } 3.getWriter().*.Driver")."admin").println("CONTENTS IN THE TABLE<br>"). javax. Class.

String s2=req.*.Session: import javax.io.setContentType("text/html"). } catch(Exception e){} } } 5. String s1=req. res. Simple login page: login. import javax. out.servlet.println("Ur user name is : "+s1). import java. public class login extends HttpServlet { public void doGet(HttpServletRequest req. HttpServletResponse res) throws ServletException.java: import javax.http.getParameter("usname").servlet.*.getWriter(). import javax.*.Reference ================================================================================================================================ 4. public class sessioncount extends HttpServlet { public void service(HttpServletRequest req.http. import java.*. out.html: <HTML> <HEAD> <TITLE> USER LOGIN </TITLE> <BODY> <form action="login" method="get"> USERNAME <input type="text" name="usname"><br><br> PASSWORD <input type="password" name="psword"><br><br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> </BODY> </HTML> login.println("Welcome to Home Page <br>").*.IOException { 130 .servlet.io.*.servlet.getParameter("psword").HttpServletResponse res) { try { PrintWriter out=res.

import java. } catch (Exception e) {} } } 131 .setAttribute("counter". PrintWriter pw=res.http.io. HttpSession hs=req.setMaxAge(1000).getWriter().setMaxAge(1000). res."prem"). hs.setMaxAge(1000). c2.servlet.getAttribute("counter")).getWriter(). import javax. public class cookies extends HttpServlet { public void service(HttpServletRequest req.setAttribute("counter".setContentType("text/html").*.*.*. } else { int c=((Integer) hs. pw."pp"). new Integer(c)).getSession(true)."001").servlet. res. c3.IOException { try { res.addCookie(c1). new Integer(1)).Reference ================================================================================================================================ } } try { res.println("<h1> USER VIEWERS : " +hs. HttpServletResponse res) throws ServletException.getAttribute("counter")==null) { hs. Cookie c3=new Cookie("User id".println("<h2> Response sets all the cookies").intValue()+1.Cookies: import javax. PrintWriter pw=res. res.addCookie(c3). c1. } pw. Cookie c1=new Cookie("Emp no".setContentType("text/html"). if(hs.addCookie(c2). Cookie c2=new Cookie("Emp name". } catch(Exception e) {} 6.getAttribute("counter")).

Reference ================================================================================================================================ 7.getParameter("psword").*.servlet. public class servletcomm_srd extends HttpServlet { public void service(HttpServletRequest req.0.forward(req.servlet. PrintWriter p=res.*. Servlet Inter-Communication (Send Redirect): import import import import javax. IOException { res.*.getParameter("name"). import javax.*.getParameter("psword").setContentType("text/plain"). String psword=req.HttpServletResponse res) throws ServletException.res).equals("prem")==false) { rd=req. String psword=req.servlet. if(name.getRequestDispatcher("/invalid"). Servlet Inter-Communication (Request Dispatcher): import javax.getWriter(). java.forward(req.servlet.HttpServletResponse res) throws ServletException. PrintWriter p=res.getWriter(). String name=req. rd.getRequestDispatcher("/valid").*. java. rd.lang. IOException { res. } else { rd=req.io.sendRedirect("http://127.*.1:7001/Servlets/invalid").res). if(name.equals("prem")==false) { res.http. import java.*. } else 132 . public void service(HttpServletRequest req.0. public class servletcomm_rd extends HttpServlet { RequestDispatcher rd.setContentType("text/plain"). String name=req. javax.getParameter("name"). } } } 8.http.io.

util..0.1:7001/Servlets/valid").html"%> Current date is <%= new Date() %> </BODY> </HTML> 10. } %> <BODY> <h1><CENTER> METHOD DECLERATION </CENTER></H1> <p> The value of count is : <%=c %></p> <p> HELLO <%= disp("FRIENDS") %></p> </BODY> </HTML> 11.jsp: <HTML> <HEAD> <TITLE> USER LOGIN </TITLE> <BODY> <form action="login" method="get"> USERNAME <input type="text" name="usname"><br><br> PASSWORD <input type="password" name="psword"><br><br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> 133 . JSP Directive: <HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <%@ page import="java. JSP 9. Jsp Scripting: <HTML> <% int c=3.Reference ================================================================================================================================ { }) } res. Jsp & Servlets: login.0.Date" %> <%@ include file="included. public String disp(String s) { return "WELCOME " + s + ".!!".sendRedirect("http://127.

*.servlet.HttpServletResponse res) { try { PrintWriter out=res. out.servlet. out.getParameter("psword"). String s2=req.*.http.getParameter("usname").*.println("Ur user name is : "+s1). javax.servlet. java. import javax. } catch(Exception e){} } } 12. 134 . Jsp.getWriter().io.jsp.jsp: <HTML> <HEAD> <TITLE> USER LOGIN </TITLE> <BODY> <form action="login" method="get"> USERNAME <input type="text" name="name"><br><br> PASSWORD <input type="password" name="psword"><br><br> <input type="submit" name="submit"> <input type="reset" name="reset"> </form> </BODY> </HTML> loginservlet.println("Welcome to Home Page <br>").*.java: import import import import import javax.Reference ================================================================================================================================ </BODY> </HTML> login.*.*. import java.http. res.servlet.java: import javax.io. java.*. Servlets & JDBC: login. javax. public class login extends HttpServlet { public void doGet(HttpServletRequest req.setContentType("text/html").*. String s1=req.servlet.sql.

Driver"). hs. rd.getParameter("pass")."admin"). rd=req. String pw=req. PrintWriter p=res. res.name1). Statement st=con.res).getConnection("jdbc:mysql://localhost:3306/prem ".HttpServletResponse res) throws ServletException.next()) { name1=rs. String name1.equals(name1)) if(pw. rd. IOException { try { Class. int c=0. while(rs. c++. } } catch(Exception e) {} } } 135 . psword=rs. Connection con=DriverManager.forward(req.equals(psword)) { hs. ResultSet rs=st. String n=req.psword).setAttribute("pw". } } if(c==0) { rd=req. if(n. public void service(HttpServletRequest req.getParameter("name").forName("com.executeQuery("select * from login").getWriter().psword.mysql.getString(1).getRequestDispatcher("/valid.jsp").getString(2).getSession().res)."root".jsp").setContentType("text/plain").jdbc.forward(req.setAttribute("n".createStatement().getRequestDispatcher("/invalid.Reference ================================================================================================================================ public class loginservlet extends HttpServlet { RequestDispatcher rd. HttpSession hs=req.

println(" <h1><b><center> WELCOME !! </h1></b></center><br></br>").jsp: <html> <body> <%@page language="java" %> <% String name=(String) session.println("YOU ARE NOT A VALID USER").Reference ================================================================================================================================ valid.getAttribute("n"). out. 136 . %> </body> </html> invalid.println(" <h3><i> USER NAME IS : " + name+ "</h3></i>"). out.jsp: <html> <body> <%@page language="java" %> <% %> </body> </html> out.

Notes ================================================================================================================================ 137 .

Notes ================================================================================================================================ 138 .

Notes ================================================================================================================================ 139 .

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->