bt 0083 server side programming theory...

303
BT 0083 Server Side Programming Theory Contents Unit 1 Understanding Java Enterprise Edition Platform 1 Unit 2 Java Servlets An Introduction 18 Unit 3 The Servlet Request: Form Data 47 Unit 4 Exception Handling in Servlets 69 Unit 5 Servlet Session Tracking 85 Unit 6 Authentication in Servlets 107 Unit 7 Java Database Connectivity 130 Unit 8 Introduction to Java Server Pages (JSP) 156 Unit 9 JSP Tags 171 Unit 10 JSP 2.0 Expression Language I 186 Edition: Spring 2009 BKID B1088 30 th Sept. 2009

Upload: others

Post on 09-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

BT 0083 Server Side Programming – Theory

Contents

Unit 1

Understanding Java Enterprise Edition Platform 1

Unit 2

Java Servlets – An Introduction 18

Unit 3

The Servlet Request: Form Data 47

Unit 4

Exception Handling in Servlets 69

Unit 5

Servlet Session Tracking 85

Unit 6

Authentication in Servlets 107

Unit 7

Java Database Connectivity 130

Unit 8

Introduction to Java Server Pages (JSP) 156

Unit 9

JSP Tags 171

Unit 10

JSP 2.0 Expression Language – I 186

Edition: Spring 2009

BKID – B1088 30

th Sept. 2009

Page 2: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Unit 11

JSP 2.0 Expression Language – II 200

Unit 12

JSP Page Directives 222

Unit 13

JSP File Inclusion 244

Unit 14

THE MVC Architecture 269

Acknowledgements, References 290

and Suggested Readings

Page 3: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Director & Dean Directorate of Distance Education Sikkim Manipal University of Health, Medical & Technological Sciences (SMU DDE)

Board of Studies

Dr. U. B. Pavanaja (Chairman) Mr. Nirmal Kumar Nigam General Manager – Academics HoP – IT Manipal Universal Learning Pvt. Ltd. Sikkim Manipal University – DDE Bangalore. Manipal. Prof. Bhushan Patwardhan Dr. A. Kumaran Chief Academics Research Manager (Multilingual) Manipal Education Microsoft Research Labs India Bangalore. Bangalore. Dr. Harishchandra Hebbar Mr. Ravindranath P. S. Director Director (Quality) Manipal Centre for Info. Sciences, Bangalore. Yahoo India, Bangalore. Dr. N. V. Subba Reddy Dr. Ashok Kallarakkal HOD – CSE Vice President Manipal Institute of Technology, Manipal. IBM India, Bangalore. Dr. Ashok Hegde Mr. H. Hiriyannaiah Vice President Group Manager MindTree Consulting Ltd., Bangalore. EDS Mphasis, Bangalore. Dr. Ramprasad Varadachar Director, Computer Studies Dayanand Sagar College of Engg., Bangalore.

Content Preparation Team Content Writing Content Editing Mr. Anil Dudhe Mr. Nirmal Kumar Nigam Sr. Lecturer Asst. Professor & HoP – IT IIIT Pune. SMU DDE, Manipal. Mr. Purushotham U Asst. Professor – IT SMU DDE, Manipal.

Instructional Design Language Editing Mr. Kulwinder Pal Ms. Aparna Ramanan Asst. Professor – Education Asst. Professor – English SMU DDE, Manipal. SMU DDE, Manipal.

Edition: Spring 2009

This book is a distance education module comprising a collection of learning material for our students. All rights reserved. No part of this work may be reproduced in any form by any means without permission in writing from Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim. Printed and published on behalf of Sikkim Manipal University of Health, Medical and Technological Sciences, Gangtok, Sikkim by Mr. Rajkumar Mascreen, GM, Manipal Universal Learning Pvt. Ltd., Manipal – 576 104. Printed at Manipal Press Limited, Manipal.

Page 4: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses
Page 5: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

“Server Side Programming – Theory” is a 4 – credit subject in fourth

semester of BSc IT program.

This courseware is intended for programmers who are interested in

developing and deploying J2EE 1.4 applications on the Sun Java System

Application Server. Before proceeding with this courseware, you should

have a good knowledge of Java programming language.

The promise of web services is to enable a distributed environment in which

any number of applications, or application components, can interoperate

seamlessly among and between organizations in a platform-neutral,

language-neutral fashion.

This interoperation brings heterogeneity to the world of distributed

computing once and for all. This book defines the fundamentals of a web

service. It explores the core technologies that enable web services to

interoperate with one another. In addition, it describes the distributed

computing model that the core web service technologies enable and how it

fits into the bigger picture of integration and deployment within the J2EE

platform.

This subject discusses in detail, the client and server side programming with

respect to Servlets and JSP as a tool. It also discusses the Database

connectivity issues and deals with the JSP issues in detail.

The Self Learning Material (SLM) of this subject is divided into 14 units, the

overview of which is given below.

Unit 1: Understanding Java Enterprise Edition Platform

This unit discusses the concepts of Java 2 Enterprise Edition (J2EE), its

applications, and architecture. In addition, deals with the standard HTTP

protocol used for communication either on a network or on the Web, and the

usage of Web Servers in application development.

SUBJECT INTRODUCTION

Page 6: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Unit 2: Java Servlets – An Introduction

This unit starts with the introduction of various tools available for Server

Side programming like CGI, PHP, and so on. It also introduces the concept

of Servlets, a tool provided by Sun Microsystems to write Server Side

Programming in a client – server or Web based applications.

Unit 3: The Servlet Request: Form Data

This unit, which is an extension of the previous unit, discusses the creation

of user interfaces with the help of HTML and processing the input data by

the Web server.

Unit 4: Exception Handling in Servlets

This unit deals with the various ways of handling errors in the programs

written either on the client side or server side.

Unit 5: Servlet Session Tracking

This unit discusses the meaning and relevance of Sessions and their usage

with respect to Web applications and Server side programming. It also deals

with the Servlet API used in Session tracking and various techniques used

to track these sessions.

Unit 6: Authentication in Servlets

Internet has become an information hub, wherein you can find any kind of

information like personal details, social, sports, science & technology, and

so on. These might use important and highly secured information, so almost

every Website may need to maintain high security.

This unit is a walkthrough of Web Security techniques.

Unit 7: Java Database Connectivity

This unit deals with connectivity to various databases with Servlets and

processing of the data using a Servlet. It discusses various techniques to

connect to a database, data retrieval and manipulation and the required

objects (like APIs) to deal with.

Unit 8: Introduction to Java Server Pages (JSP)

The disadvantages of Servlets initiated JSP into picture. Java Server Pages

(JSP) is one of the major components of Java EE. It is an open source

specification developed by Sun Microsystems. This specification is based on

Page 7: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Servlet functionalities. In this unit these specifications are discussed in

detail.

Unit 9: JSP Tags

This unit deals with JSP tags where JSP Tag Libraries (TagLibs) are a

natural extension to the JSP tag syntax. It also describes how to write

simple custom tags, deploy your tags with the J2EE RI, use attributes to

extend JSP pages, write co-operating tags to support more complex

functionality, such as iteration and use the JSP Standard Tag Library

(JSPTL).

Unit 10: JSP 2.0 Expression Language – I

JSP 2.0 introduced a shorthand language for evaluating and outputting the

values of Java objects that are stored in standard locations. This expression

language (EL) is one of the two most important new features of JSP 2.0; the

other is the ability to define custom tags with JSP syntax instead of Java

syntax.

This unit discusses the Expression Language and its features.

Unit 11: JSP 2.0 Expression Language – II

This unit discusses the extensions of the EL covering the concept of Beans,

collections, implicit objects, and EL operators.

Unit 12: JSP Page Directives

A JSP page directive affects the overall structure of the Servlet that results

from the JSP page. This unit deals with these Page Directives.

Unit 13: JSP File Inclusion

This unit describes about JSP File inclusion techniques.

Unit 14: THE MVC Architecture

This unit describes how to combine Servlets and JSP pages with the help of

Model View Controller Architecture.

Page 8: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Objectives of studying this subject

After studying this subject, you should be able to:

define and describe the architecture of J2EE

describe and illustrate the usage of Servlets Technology

explain and illustrate database connectivity using Servlets and / or JSP

explain and illustrate the usage of Java Server Pages (JSP)

Technology

describe the Model View Control (MVC) Architecture and its usage in

Web applications

Page 9: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 269

Unit 14 Model View Controller Architecture

Structure:

14.1 Introduction

Objectives

14.2 Need for Model View Controller (MVC)

14.3 Implementing MVC with Request Dispatcher

14.4 Summarizing MVC Code

14.5 Interpreting Relative URLs in the Destination Page

14.6 MVC Applications

14.7 Forwarding Requests from JSP Pages

14.8 Including Pages

14.9 Summary

14.10 Terminal Questions

14.11 Answers

14.1 Introduction

In the previous unit you have learned about jsp:include action and include

directive. This unit describes how to combine Servlets and JSP pages.

Servlets are good at data processing: reading and checking data,

communicating with databases, invoking business logic, and so on. JSP

pages are good at presentation: building HTML to represent the results of

requests, to make best use of the strengths of each technology it is good to

combine Servlets and JSP pages.

Objectives:

After studying this unit, you should be able to:

explain the benefits of MVC

describe Request Dispatcher to implement MVC

explain Interpreting Relative URLs in the Destination Page

discuss on MVC Applications

explain how to forward requests from JSP pages

discuss on including pages instead of forwarding them

14.2 Need for Model View Controller (MVC)

Servlets are great when your application requires a lot of real programming

to accomplish its task. Servlets can manipulate HTTP status codes and

Page 10: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 270

headers, use cookies, track sessions, save information between requests,

compress pages, access databases, generate JPEG images on-the-fly, and

perform many other tasks flexibly and efficiently. But, generating HTML with

Servlets can be tedious and can yield a result that is hard to modify.

That’s where JSP comes in: as illustrated in Figure 14.1, JSP lets you

separate much of the presentation from the dynamic content. That way, you

can write the HTML in the normal manner, even using HTML-specific tools

and putting your Web content developers to work on your JSP documents.

JSP expressions, scriptlets, and declarations let you insert simple Java code

into the Servlet that results from the JSP page, and directives let you control

the overall layout of the page. For more complex requirements, you can

wrap Java code inside beans or even define your own JSP tags.

Simple application or small development

team.

Complex application

or large development

team.

Call Java Code Directly. Place all Java code in

JSP page. Appropriate only for very small amounts

of code.

Call Java Code Indirectly. Develop separate utility

classes. Insert into JSP page only the Java code

needed to invoke the utility classes.

Use Beans. Develop separate utility classes

structured as beans. Use jsp:useBean, jsp:get

roperty, and jsp:setProperty to invoke the code.

Use the MVC Architecture. Have a Servlet

respond to original request, look up data, and store

results in beans. Forward to a JSP page to present

results. JSP page uses beans.

Use the JSP Expression Language. Use

shorthand syntax to access and output object

properties. Usually used in conjunction with beans

and MVC.

Use Custom Tags. Develop tag handler classes.

Invoke the tag handlers with XML-like custom tags.

The assumption behind a JSP document is that it provides a single overall

presentation. What if you want to give totally different results depending on

the data that you receive? Scripting expressions, beans, and custom tags,

although extremely powerful and flexible, don’t overcome the limitation that

the JSP page defines a relatively fixed, top-level page appearance.

Page 11: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 271

Similarly, what if you need complex reasoning just to determine the type of

data that applies to the current situation? JSP is poor at this type of

business logic.

The solution is to use both Servlets and Java Server Pages. In this

approach, known as the Model View Controller (MVC) or Model 2

architecture, you let each technology concentrate on what it excels at. The

original request is handled by a Servlet. The Servlet invokes the business-

logic and data-access code and creates beans to represent the results

(that’s the model). Then, the Servlet decides which JSP page is appropriate

to present those particular results and forwards the request there (the JSP

page is the view). The Servlet decides what business logic code applies and

which JSP page should present the results (the Servlet is the controller).

MVC Frameworks

The key motivation behind the MVC approach is the desire to separate the

code that creates and manipulates the data from the code that presents the

data. The basic tools needed to implement this presentation-layer

separation are standard in the Servlet API and are the topic of this unit.

However, in very complex applications, a more elaborate MVC framework is

sometimes beneficial. The most popular of these frameworks is Apache

Struts. Although Struts is useful and widely used, you should not feel that

you must use Struts in order to apply the MVC approach. For simple and

moderately complex applications, implementing MVC from scratch with

Request Dispatcher is straightforward and flexible. Do not be intimidated: go

ahead and start with the basic approach.

In many situations, you will stick with the basic approach for the entire life of

your application. Even if you decide to use Struts or another MVC

framework later, you will recoup much of your investment because most of

your work will also apply to the elaborate frameworks.

Architecture or Approach?

The term “architecture” often connotes “overall system design.” Although

many systems are indeed designed with MVC at their core, it is not

necessary to redesign your overall system just to make use of the MVC

approach. It is quite common for applications to handle some requests with

Servlets, other requests with JSP pages, and still others with Servlets and

Page 12: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 272

JSP acting in conjunction as described in this unit. Do not feel that you have

to rework your entire system architecture just to use the MVC approach: go

ahead and start applying it in the parts of your application where it fits best.

Self Assessment Questions

1. The approach of Combining Servlets and Java Server Pages is known

as _________.

2 In MVC approach there is a separation between the code that creates

and manipulates the data from the code that presents the data

(True/False).

14.3 Implementing MVC with Request Dispatcher

The most important point about MVC is the idea of separating the business

logic and data access layers from the presentation layer. The syntax is quite

simple, and in fact you should be familiar with much of it already. Here is a

quick summary of the required steps; the following subsections supply

details.

Define Beans for Data Representation: Beans are just Java objects that

follow a few simple conventions. Your first step is defining beans to

represent the results that will be presented to the user.

Use Servlets for Request Handling: In most cases, the Servlet reads

request parameters.

Populate the Beans: The Servlet invokes business logic (application

specific code) or data-access code to obtain the results. Results are placed

in the beans that were defined in step 1.

Storing Beans in the Request, Session, or Servlet Context: The Servlet

calls set attribute on the request, session, or Servlet context objects to store

a reference to the beans that represent the results of the request.

Forward the Request to a JSP Page: The Servlet determines which JSP

page is appropriate to the situation and uses the forward method of Request

Dispatcher to transfer control to that page.

Extract the Data from the Beans: The JSP page accesses beans with jsp:

useBean and a scope matching the location of step 4. The page then uses

jsp: getProperty to output the bean properties. The JSP page does not

Page 13: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 273

create or modify the bean; it merely extracts and displays data that the

Servlet created.

Defining Beans to Represent the Data

Beans are Java objects that follow a few simple conventions. In this case,

since a Servlet or other Java routine (never a JSP page) will be creating the

beans, the requirement for an empty (zero-argument) constructor is waived.

So, your objects merely need to follow the normal recommended practices

of keeping the instance variables private and using accessory methods that

follow the get/set naming convention.

Since the JSP page will only access the beans, not create or modify them, a

common practice is to define value objects: objects that represent results

but have little or no additional functionality.

Writing Servlets to Handle Requests

Once the bean classes are defined, the next task is to write a Servlet to read

the request information. Since, with MVC, a Servlet responds to the initial

request, the normal approaches are used to read request parameters and

request headers, respectively.

Although Servlets use the normal techniques to read the request information

and generate the data, they do not use the normal techniques to output the

results. In fact, with the MVC approach the Servlets do not create any

output; the output is completely handled by the JSP pages. So, the Servlets

do not call response setContentType, response.getWriter, or out.println.

Populating the Beans

After you read the form parameters, you use them to determine the results

of the request. These results are determined in a completely application-

specific manner. You might call some business logic code, invoke an

Enterprise JavaBeans component, or query a database. No matter how you

come up with the data, you need to use that data to fill in the value object

beans that you defined in the first step.

Storing the Results

You have read the form information. You have created data specific to the

request. You have placed that data in beans. Now you need to store those

beans in a location that the JSP pages will be able to access.

Page 14: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 274

A Servlet can store data for JSP pages in three main places: in the

HttpServlet-Request, in the HttpSession, and in the ServletContext. These

storage locations correspond to the three non-default values of the scope

attribute of jsp:useBean: that is, request, session, and application.

Storing data that the JSP page will use only in this request.

First, the Servlets would create and store data as follows:

ValueObject value = new ValueObject(...);

request.setAttribute("key", value);

Next, the Servlets would forward the request to a JSP page that uses the

following to retrieve the data.

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="request" />

Note that request attributes have nothing to do with request parameters or

request headers. The request attributes are independent of the information

coming from the client; they are just application-specific entries in a hash

table that is attached to the request object. This table simply stores data in a

place that can be accessed by both the current Servlets and JSP page, but

not by any other resource or request.

Storing data that the JSP page will use in this request and in later

requests from the same client. First, the Servlets would create and

store data as follows:

ValueObject value = new ValueObject(...);

HttpSession session = request.getSession();

session.setAttribute("key", value);

Next, the Servlets would forward to a JSP page that uses the following

to retrieve the data:

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="session" />

Storing data that the JSP page will use in this request and in later

requests from any client. First, the Servlets would create and store

data as follows:

ValueObject value = new ValueObject(...);

getServletContext().setAttribute("key", value);

Page 15: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 275

Next, the Servlets would forward to a JSP page that uses the following

to retrieve the data:

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="application" />

The Servlets code is normally synchronized to prevent the data

changing between the Servlets and the JSP page.

Forwarding Requests to JSP Pages

You forward requests with the forward method of RequestDispatcher. You

obtain a RequestDispatcher by calling the getRequestDispatcher method of

ServletRequest, supplying a relative address. You are permitted to specify

addresses in the WEB-INF directory; clients are not allowed to directly

access files in WEB-INF, but the server is allowed to transfer control there.

Using locations in WEB-INF prevents clients from inadvertently accessing

JSP pages directly, without first going through the Servlets that create the

JSP data.

Note: If your JSP pages only make sense in the context of Servlets-

generated data, place the pages under the WEB-INF directory. That way,

Servlets can forward requests to the pages, but clients cannot access them

directly.

Once you have a Request Dispatcher, you use forward to transfer control to

the associated address. You supply the HttpServletRequest and

HttpServletResponse as arguments. Note that the forward method of

RequestDispatcher is quite different from the sendRedirect method of

HttpServletRequest. With forward, there is no extra response/request pair

as with sendRedirect. Thus, the URL displayed to the client does not

change when you use forward.

As an example, Listing 14.1 shows a portion of a Servlet that forwards the

request to one of three different JSP pages, depending on the value of the

operation request parameter.

Page 16: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 276

Listing 14.1: Request Forwarding Example

Forwarding to Static Resources

In most cases, you forward requests to JSP pages or other Servlets. In

some cases, however, you might want to send requests to static HTML

pages. In an e-commerce site, for example, requests indicating that the user

does not have a valid account name might be forwarded to an account

application page that uses HTML forms to HTML page, is perfectly legal and

requires no special syntax; just supply the address of the HTML page as the

argument to getRequestDispatcher.

However, since forwarded requests use the same request method as the

original request, POST requests cannot be forwarded to normal HTML

pages. The solution to this problem is to simply rename the HTML page to

have a .jsp extension. Renaming somefile.html to somefile.jsp does not

change its output for GET requests, but somefile.html cannot handle POST

requests, whereas somefile.jsp gives an identical response for both GET

and POST.

Redirecting Instead of Forwarding

The standard MVC approach is to use the forward method of

RequestDispatcher to transfer control from the Servlets to the JSP page.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String operation = request.getParameter("operation"); if (operation == null) { operation = "unknown"; } String address; if (operation.equals("order")) { address = "/WEB-INF/Order.jsp"; } else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp"; } else { address = "/WEB-INF/UnknownOperation.jsp"; } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); }

Page 17: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 277

However, when you are using session-based data sharing, it is sometimes

preferable to use response.sendRedirect.

Here is a summary of the behavior of forward.

Control is transferred entirely on the server. No network traffic is

involved.

The user does not see the address of the destination JSP page and

pages can be placed in WEB-INF to prevent the user from accessing

them without going through the Servlets that sets up the data. This is

beneficial if the JSP page makes sense only in the context of Servlet

generated data.

Here is a summary of sendRedirect.

Control is transferred by sending the client a 302 status code and a

Location response header. Transfer requires an additional network

round trip.

The user sees the address of the destination page and can bookmark it

and access it independently. This is beneficial if the JSP is designed to

use default values when data is missing. For example, this approach

would be used when redisplaying an incomplete HTML form or

summarizing the contents of a shopping cart. In both cases, previously

created data would be extracted from the user’s session, so the JSP

page makes sense even for requests that do not involve the Servlets.

Extracting Data from Beans

Once the request arrives at the JSP page, the JSP page uses jsp:useBean

and jsp:getProperty to extract the data.

The JSP page never creates the objects. The Servlet, not the JSP

page, should create all the data objects. So, to guarantee that the JSP

page will not create objects, you should use

<jsp:useBean ... type="package.Class" />

instead of

<jsp:useBean ... class="package.Class" />.

The JSP page should not modify the objects. So, you should use

jsp:getProperty but not jsp:setProperty.

Page 18: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 278

The scope you specify should match the storage location used by the

Servlet. For example, the following three forms would be used for request-,

session-, and application-based sharing, respectively.

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="request" />

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="session" />

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="application" />

Self Assessment Questions

3. In MVC there is a separation between the business logic and data

access layers from the _________ layer.

4. The standard MVC approach is to use the forward method of ________

to transfer control from the Servlets to the JSP page.

14.4 Summarizing MVC Code

This section summarizes the code that would be used for request-based,

session-based, and application-based MVC approaches.

Request-Based Data Sharing

With request-based sharing, the Servlet stores the beans in the HttpServlet-

Request, where they are accessible only to the destination JSP page.

Servlet

ValueObject value = new ValueObject(...);

request.setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="request" />

<jsp:getProperty name="key" property="someProperty" />

Page 19: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 279

Session-Based Data Sharing

With session-based sharing, the Servlet stores the beans in the

HttpSession, where they are accessible to the same client in the destination

JSP page or in other pages.

Servlet

ValueObject value = new ValueObject(...);

HttpSession session = request.getSession();

session.setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="session" />

<jsp:getProperty name="key" property="someProperty" />

Application-Based Data Sharing

With application-based sharing, the Servlet stores the beans in the Servlet-

Context, where they are accessible to any Servlet or JSP page in the Web

application. To guarantee that the JSP page extracts the same data that the

Servlet inserted, you should synchronize your code as below.

Servlet

synchronized(this) {

ValueObject value = new ValueObject(...);

getServletContext().setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

}

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="application" />

<jsp:getProperty name="key" property="someProperty" />

Page 20: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 280

14.5 Interpreting Relative URLs in the Destination Page

Although a Servlets can forward the request to an arbitrary location on the

same server, the process is quite different from that of using the

sendRedirect method of HttpServletResponse. First, sendRedirect requires

the client to reconnect to the new resource, whereas the forward method of

RequestDispatcher is handled completely on the server. Second,

sendRedirect does not automatically preserve all of the request data;

forward does. Third, sendRedirect results in a different final URL, whereas

with forward, the URL of the original Servlets is maintained.

This final point means that if the destination page uses relative URLs for

images or style sheets, it needs to make them relative to the Servlets URL

or the server root, not to the destination page’s actual location.

For example, consider the following style sheet entry:

<LINK REL=STYLESHEET

HREF="my-styles.css"

TYPE="text/css">

If the JSP page containing this entry is accessed by means of a forwarded

request, my-styles.css will be interpreted relative to the URL of the

originating Servlets, not relative to the JSP page itself, almost certainly

resulting in an error. The simplest solution to this problem is to give the full

server path to the style sheet file, as follows.

<LINK REL=STYLESHEET

HREF="/path/my-styles.css"

TYPE="text/css">

The same approach is required for addresses used in <IMG SRC=...>

and <A HREF=...>.

Self Assessment Questions

5. The sendRedirect method results in a different final URL, whereas with

forward method, the URL of the original Servlets is maintained

(True/False).

6. To guarantee that the JSP page extracts the same data that the Servlet

inserted, Synchronization code should be used. (True/False).

Page 21: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 281

14.6 MVC Applications

In this section, we apply the MVC approach to an application that displays

bank account balances. The controller Servlet (Listing 14.2) reads a

customer ID and passes that to some data-access code that returns a Bank

Customer value bean (Listing 14.3).

Listing 14.2: ShowBalance.java

Listing 14.3 BankCustomer.java

package coreservlets;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/** Servlet that reads a customer ID and displays

* information on the account balance of the customer

* who has that ID.

*/

public class ShowBalance extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

BankCustomer customer =

BankCustomer.getCustomer(request.getParameter("id"));

String address;

if (customer == null) {

address = "/WEB-INF/bank-account/UnknownCustomer.jsp";

} else if (customer.getBalance() < 0) {

address = "/WEB-INF/bank-account/NegativeBalance.jsp";

request.setAttribute("badCustomer", customer);

} else if (customer.getBalance() < 10000) {

address = "/WEB-INF/bank-account/NormalBalance.jsp";

request.setAttribute("regularCustomer", customer);

} else {

address = "/WEB-INF/bank-account/HighBalance.jsp";

request.setAttribute("eliteCustomer", customer);

}

RequestDispatcher dispatcher =

request.getRequestDispatcher(address);

dispatcher.forward(request, response);

}

}

Page 22: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 282

Listing 14.3: BankCustomer.jsp

The Servlets then stores the bean in the HttpServletRequest object where it

will be accessible from destination JSP pages but nowhere else. If the

account balance of the resulting customer is negative, the Servlets forwards

to a page designed for delinquent customers (Listing 14.4, Figure 14.2).

package coreservlets; import java.util.*; /** Bean to represent a bank customer. */ public class BankCustomer { private String id, firstName, lastName; private double balance; public BankCustomer(String id, String firstName, String lastName, double balance) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.balance = balance; } public String getId() { return(id); } public String getFirstName() { return(firstName); } public String getLastName() { return(lastName); } public double getBalance() { return(balance); } public double getBalanceNoSign() { return(Math.abs(balance)); } public void setBalance(double balance) { this.balance = balance; } // Makes a small table of banking customers. private static HashMap customers; static { customers = new HashMap(); customers.put("id001", new BankCustomer("id001", "John", "Hacker",-3456.78)); customers.put("id002",new BankCustomer("id002","Jane","Hacker",1234.56)); customers.put("id003", new BankCustomer("id003","Juan","Hacker",987654.32)); } /** Finds the customer with the given ID. * Returns null if there is no match. */ public static BankCustomer getCustomer(String id) { return((BankCustomer)customers.get(id)); } }

Page 23: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 283

Listing 14.4: NegativeBalance.jsp

Fig. 14.2: The Show Customer Servlet with an ID corresponding to a

customer with a negative balance.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>You Owe Us Money!</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> We Know Where You Live!</TABLE> <P> <IMG SRC="/bank-support/Club.gif" ALIGN="LEFT"> <jsp:useBean id="badCustomer" type="coreservlets.BankCustomer" scope="request" /> Watch out, <jsp:getProperty name="badCustomer" property="firstName" />, we know where you live. <P> Pay us the $<jsp:getProperty name="badCustomer" property="balanceNoSign" /> you owe us before it is too late! </BODY></HTML>

Page 24: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 284

If the customer has a positive balance of less than $10,000, the Servlets

transfers to the standard balancedisplay page (Listing 14.5, Figure 14.3).

Listing 14.5: NormalBalance.jsp

Fig. 14.3: The ShowCustomer Servlet with an ID corresponding to a customer

with a normal balance.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Your Balance</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Your Balance</TABLE> <P> <IMG SRC="/bank-support/Money.gif" ALIGN="RIGHT"> <jsp:useBean id="regularCustomer" type="coreservlets.BankCustomer" scope="request" />

<UL> <LI>First name: <jsp:getProperty name="regularCustomer" property="firstName" /> <LI>Last name: <jsp:getProperty name="regularCustomer" property="lastName" /> <LI>ID: <jsp:getProperty name="regularCustomer" property="id" /> <LI>Balance: $<jsp:getProperty name="regularCustomer" property="balance" /> </UL></BODY></HTML>

Page 25: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 285

if the customer has a balance of $10,000 or more, the Servlets forwards the

request to a page reserved for elite customers (Listing 14.6, Figure 14.4).

Listing 14.6: HighBalance.jsp

Fig. 14.4: The ShowCustomer Servlet with an ID corresponding to a customer

with a high balance.

<HTML> <HEAD> <TITLE>Your Balance</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Your Balance</TABLE> <P> <CENTER><IMG SRC="/bank-support/Sailing.gif"></CENTER> <BR CLEAR="ALL"> <jsp:useBean id="eliteCustomer" type="coreservlets.BankCustomer" scope="request" />

It is an honor to serve you, <jsp:getProperty name="eliteCustomer" property="firstName" /> <jsp:getProperty name="eliteCustomer" property="lastName" />!

<P> Since you are one of our most valued customers, we would like to offer you the opportunity to spend a mere fraction of your $<jsp:getProperty name="eliteCustomer" property="balance" />

on a boat worthy of your status. Please visit our boat store for more information. </BODY></HTML>

Page 26: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 286

Finally, if the customer ID is unrecognized, an error page is displayed

(Listing 14.7, Figure 14.5).

Listing 14.7: UnknownCustomer.jsp

Fig. 14.5: The ShowCustomer Servlet with an unknown customer ID.

14.7 Forwarding Requests from JSP Pages

The most common request-forwarding scenario is one in which the request

first goes to a Servlet and the Servlet forwards the request to a JSP page.

The reason a Servlet usually handles the original request is that checking

request parameters and setting up beans requires a lot of programming, and

it is more convenient to do this programming in a Servlet than in a JSP

document. The reason that the destination page is usually a JSP document

is that JSP simplifies the process of creating the HTML content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Unknown Customer</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Unknown Customer</TABLE> <P> Unrecognized customer ID. </BODY></HTML>

Page 27: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 287

However, just because this is the usual approach doesn’t mean that it is the

only way of doing things. It is certainly possible for the destination page to

be a Servlet. Similarly, it is quite possible for a JSP page to forward

requests elsewhere. For example, a request might go to a JSP page that

normally presents results of a certain type and that forwards the request

elsewhere only when it receives unexpected values.

Sending requests to Servlets instead of JSP pages requires no changes

whatsoever in the use of the RequestDispatcher. However, there is special

syntactic support for forwarding requests from JSP pages. In JSP, the

jsp:forward action is simpler and easier to use than wrapping

RequestDispatcher code in a scriptlet.

This action takes the following form:

<jsp:forward page="Relative URL" />

The page attribute is allowed to contain JSP expressions so that the

destination can be computed at request time. For example, the following

code sends about half the visitors to http://host/examples/page1.jsp and the

others to http://host/examples/page2.jsp.

<% String destination;

if (Math.random() > 0.5) {

destination = "/examples/page1.jsp";

} else {

destination = "/examples/page2.jsp";

}

%>

<jsp:forward page="<%= destination %>" />

The jsp:forward action, like jsp:include, can make use of jsp:param elements

to supply extra request parameters to the destination page.

Self Assessment Question

7. Sending requests to Servlets instead of JSP pages requires changes in

the use of the RequestDispatcher. (True/False).

Page 28: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 288

14.9 Summary

Need for MVC

As you move from simple applications to complex applications there is a

need to use both Servlets and Java Server Pages. This approach is known

as the Model View Controller (MVC) or Model 2 architecture

Implementing MVC with Request Dispatcher

The most important point about MVC is the idea of separating the business

logic and data access layers from the presentation layer.

Summarizing MVC Code

This section summarizes the code that would be used for request-based,

session-based, and application-based MVC approaches

Interpreting Relative URLs in the Destination Page

Servlets can forward the request to an arbitrary location on the same server,

the process is described in three steps. First, sendRedirect requires the

client to reconnect to the new resource, whereas the forward method of

Request Dispatcher is handled completely on the server. Second,

sendRedirect does not automatically preserve all of the request data;

forward does. Third, sendRedirect results in a different final URL.

Forwarding Requests from JSP Pages

The most common request-forwarding scenario is one in which the request

first goes to a Servlet and the Servlet forwards the request to a JSP page. A

Servlet usually handles the original request is that checking request

parameters and setting up beans requires a lot of programming, and it is

more convenient to do this programming in a Servlet than in a JSP

document.

14.10 Terminal Questions

1. What is Model 2 architecture?

2. What is the necessity to write Servlets to Handle Requests?

3. Describe Interpreting Relative URLs in the Destination Page.

4. Explain the concept of Forwarding Requests from JSP Pages.

Page 29: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 289

14.11 Answers

Self Assessment Questions

1. Model View Controller (MVC) or Model 2 architecture,

2. True

3. Presentation

4. RequestDispatcher

5. True

6. True

7. False

Terminal Questions

1. As you move from simple applications to complex applications there is a

need to use both Servlets and Java Server Pages. This approach is

known as the Model View Controller (MVC) or Model 2 architecture

(Refer Section 14.1).

2. Since, with MVC, a Servlet responds to the initial request, the normal

approaches are used to read request parameters and request headers,

respectively. Servlets use the normal techniques to read the request

information and generate the data, they do not use the normal

techniques to output the results. (Refer Section 14.3).

3. Servlets can forward the request to an arbitrary location on the same

server, the process is described in three steps. First, sendRedirect

requires the client to reconnect to the new resource, whereas the

forward method of RequestDispatcher is handled completely on the

server. Second, sendRedirect does not automatically preserve all of the

request data; forward does. Third, sendRedirect results in a different

final URL.

4. The most common request-forwarding scenario is one in which the

request first goes to a Servlet and the Servlet forwards the request to a

JSP page. The reason a Servlet usually handles the original request is

that checking request parameters and setting up beans requires a lot of

programming, and it is more convenient to do this programming in a

Servlet than in a JSP document. The reason that the destination page is

usually a JSP document is that JSP simplifies the process of creating

the HTML content. (Refer Section 14.7).

Page 30: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 290

Acknowledgements, References and Suggested Readings:

1) Armstrong, E., Ball, J. et al. The J2EE™ 1.4 Tutorial.

2) Bergsten, H. (2000). Java Server Pages, First Edition. O'Reilly.

3) Farley, J. Java Distributed Computing. O'Reilly.

4) Harold, E. and Means, W.S. XML in a Nutshell. O'Reilly.

5) Hunter, J. and Crawford, W. (1998). Java Servlet Programming, First

edition. O'Reilly.

6) McLaughlin, B. Java and XML. O'Reilly.

7) Neimeyer, P. and Knudsen, J. Learning Java (formerly Exploring Java).

O'Reilly.

Web Sites:

1) Go through Sun Java™ System Application Server Platform Edition 8

Developer’s Guide at http://docs.sun.com/db/doc/817-6087 for

information about developer features of the Application Server.

2) Go through Sun Java™ System Application Server Platform Edition 8

Administration Guide at http://docs.sun.com/db/doc/817-6088 for

information about administering the Application Server.

3) Oracle, JDeveloper http://www.oracle.com/java/

A development environment for Java-based database applications with

support for JSP-based user interfaces.

4) VisualAge for Java (IBM), http://www-4.ibm.com/software/ad/vajava/

An IDE with support for servlet and JSP debugging as well as a wizard

for generation of template code. Available for Windows and Linux.

5) Tomcat (Apache Software Foundation), http://jakarta.apache.org

Tomcat is the official reference implementation for the Servlet and JSP

specifications, developed as an open source product in the Apache

Jakarta project.

Page 31: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 18

Unit 2 Java Servlets – An Introduction

Structure:

2.1 Introduction

Objectives

2.2 Server Side Tools

Common Gateway Interface (CGI)

Hypertext Processor (PHP)

ColdFusion

Cold Fusion Markup Language (CFML)

PerlEx

Server-Side JavaScript (SSJS)

Active Server Pages (ASP)

2.3 Java Servletsu

2.4 The Servlet Interface

2.5 The Servlet Life Cycle

2.6 The GenericServlet Class

2.7 The HttpServlet Class

2.8 Structure of Web Applications

2.9 Servlet Contexts and Configurations

2.10 Installing Tomcat Web Server

2.11 Summary

2.12 Terminal Questions

2.13 Answers

2.1 Introduction

In the last unit, you have studied the concept of J2EE platform, its

applications, communication protocols, and Web Servers. This unit starts

with the introduction of various tools available for Server Side programming

like CGI, PHP, and so on. This unit also explains the concept of Servlets, a

tool provided by Sun Microsystems to write Server Side Programming in a

client – server or Web based applications.

Before you study this unit, you should be familiar with the concepts of Client

– Server and Web Architectures.

Page 32: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 19

Objectives:

After studying this unit, you should be able to:

describe various tools for Server Side programming

define CGI, Servlets, and Servlet API’s

describe Servlet Interfaces and Servlet Life Cycle

describe Generic and HTTP Servlets

explain Web Application Structure

describe Servlet Configuration and Context

illustrate the process of installing the Tomcat Web Server

2.2 Server Side Tools

This section will cover the scripting-languages which can run server side.

Scripting languages are interpreted, rather than compiled. They are easier

to write but slow in execution.

2.2.1 Common Gateway Interface (CGI)

Fig. 2.1: CGI Request Handling

CGI was the core of web servers for many years. CGI was originally

designed to be a standard method for a Web server to communicate with

external applications. CGI is a scripting interface, which can be written

almost in any language like Perl, C, C++, UNIX shell scripts etc. With this

CGI, many other scripting written in plethora of languages from PERL to

Python, and from TCL/TK to REBOL, generates dynamic contents in web

pages. The major issue with CGI is that, “it can handle the request, but in

separate process by separate instance of CGI program or CGI script”. So

you have the overhead of creating a new process for every new request. In

CGI requests are handled by creating a pool of processes. If one process

finishes handling a request, it is kept and used to manage the next incoming

Page 33: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 20

request rather than starting a new process for each request. CGI

implementations improve efficiency by pooling resources for requests.

Web Server (CGI)

Fig. 2.2: CGI Process Creation

Yet there are many problems with CGI. Most notable is the difficulty in

sharing resources such as common data or server-side object between

requests. Solving these problems involves using creative fixes that work

with the specific CGI and are custom-made for individual projects. For

complex and large web applications, a better solution, preferably one that

addresses the problems of CGI, was required.

CGI Features

Not secured.

High overhead in process creation.

Doesn't support state persistence across invocations.

Has limited functionality.

CGI processes have high overheads as compared with threads.

Because processes are heavyweight tasks that require their own

separate address spaces.

Creating and terminating processes utilizes more server time.

Context switching from one process to another is also costly.

Inter-process communication is expensive and limited.

Process #1

Process #3

Process #3

Client Request

Client Request

Client Request

CGI Process Pool

Page 34: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 21

CGI processes do not have specialized support for:

Client functionality - cookies, sessions etc.

Concurrency control for persistent state updates at server.

2.2.2 Hypertext Processor (PHP)

PHP (Hypertext Processor) is an HTML-embedded, Server - Side, cross-

platform scripting language used to create dynamic web pages. It is an

Open Source software designed to handle web-based applications and

processing. It can be run on many servers such as Apache, IIS etc. It

includes support for many Web servers, HTTP sessions, output buffering,

more secure ways of handling user input and several new language

constructs.

Advantages

It has large community support.

It can be installed on nearly all webhosts.

It is platform independent.

It is an Open Source.

Disadvantages

Requires strong learning curve for inexperienced developers.

Security risks for new developers due to the power given to PHP.

2.2.3 ColdFusion

ColdFusion was launched in 1995 by Allaire Corporation, and was the first

Web application server available for Windows NT. According to

documentation, the ColdFusion product consists of four components:

1. ColdFusion Server

2. ColdFusion Markup Language (CFML)

3. ColdFusion Studio

4. ColdFusion Administrator

2.2.4 Cold Fusion Markup Language (CFML)

CFML is a scripting language designed specifically for web development. It

is a tag-based scripting language. This makes it easier for developers to

learn. CFML is implemented in ColdFusion 5. It includes more than 75 tags

and over 240 built-in functions. CFML code is written directly into pages on

the Web server, along with any HTML, which may be required on that page.

It uses a .cfm or. cfml as a file extension. It is not an open source.

Page 35: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 22

Advantages

Simple to learn and use

Provides fast application development

Cross-platform support

Provides good scalability

Well documented

Extensive, simple and effective features.

Disadvantages

Extending its features can increase complexity.

Costs more than competing platforms. A freeware version is available,

but with limited features.

2.2.5 PerlEx

PerlEx is a plug-in for NT Web servers developed by ActiveState. It

improves the performance of CGI scripts written in Perl that run on Windows

NT Web servers. Performance improves because:

1. PerlEx compiles Perl scripts once and then stores them in memory. This

feature eliminates recompilation every time.

2. It enables persistent database connections so that a new connection is

not required for each user request. This feature significantly reduces

both server load and response time.

3. It creates multiple interpreters, which can execute scripts

simultaneously, thus increasing Web server performance.

2.2.6 Server - Side JavaScript (SSJS)

This server side scripting is given by iPlanet/Netscape. SSJS allows

embedded code in HTML pages to generate dynamic web content. With this

we can create precompiled web pages which will improve the performance

of the code. But this is limited to iPlanet/Netscape servers only.

2.2.7 Active Server Pages (ASP)

ASP is a "framework" development environment, inside which you can

invoke ASP properties and methods using the ASP-enabled language of

your choice. Currently the 2 primary languages that support ASP are Jscript

and VBScript by Microsoft.

With ASP, a HTML page on the Web server can contain snippets of

embedded code. ASP is optimized for generating small portions of dynamic

Page 36: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 23

content, using COM components to do the heavy lifting. But to run ASP

pages for performing advanced tasks on non-Windows platform requires

Windows COM library. ASP is designed to run on Microsoft's Internet

Information Services (IIS) Web server, though it can run in other

environments as well.

Advantages

It is easy to learn for new users.

Ease of extension via COM objects.

It comes free with most Windows operating systems.

It is browser independent.

No extra software costs are required.

Disadvantages

Strongest in a Windows environment, weaker on Unix or other platforms.

Recovering from a bad ASP selection decision can be expensive and

time consuming.

ASP ties us to Microsoft and NT on the server-side.

Data safety – basic requests for physical and technological data safety

(hacking, cracking and loss of data),

Not a full program development environment, so debugging a script may

not be straight forward.

Many server side tools are available for developing dynamic Web content.

Other solutions can be Servlets, Java Server Pages (JSP), which are Java-

based alternatives to ASP, invented and standardized by Sun.

Self Assessment Questions

1. CGI supports Multi-threading. (True / False)

2. –––––––– and ––––––– scripting languages are given by Microsoft.

2.3 Java Servlets

Definition: “It is a Web component managed by a Web container, which

generates dynamic content in Web pages.”

A Servlet is a Java application that runs in a Web server or an application

server and provides server-side processing such as accessing a database.

Servlets are protocol and platform independent server side components,

written in Java, which dynamically extend Java-enabled Web Servers. A

Page 37: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 24

Servlet, in simple terms, is a Java program running under a Web server

taking a 'request' object as an input and responding back by a 'response'

object. A Java Servlet is an application, which runs in a Servlet container

using a framework for servicing data requests.

The javax.servlet and javax.servlet.http packages provide interfaces and

classes for writing Servlets. All Servlets must implement the Servlet

interface, which defines the life-cycle methods.

When implementing a generic service, you can use or extend the

GenericServlet class provided with the Java Servlet API. The HttpServlet

class provides methods, such as doGet and doPost, for handling HTTP-

specific services.

2.3.2 Comparison with CGI

Servlets were designed to solve the problems of CGI and to create robust

server-side environments for Web developers. Like CGI, Servlets also take

requests from client, process those requests and give appropriate

responses. Servlets support multi - threading that share resources among

various requests. So there is a need for creating a new process for every

request.

Fig. 2.3: Resource Sharing among requests

Web Server

Client Request

Servlet #1

Servlet #3

Servlet #1

Client Request

Process

Client Request

Page 38: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 25

Servlets provide many such advantages compared to CGI.

Advantages of Servlets over CGI

Servlets

Support Multi – threading

Easy context switching between invocations

Faster to run when loaded

Share open DB connection using Connection Pooling with successive

invocations

Store state information in static variables

Share access to state data each time the Servlet is run

Control concurrent access to shared state

CGI programs

Have to renew database connections each time they're run.

Lack common address space to share states.

Disadvantages of Servlets over CGI processes

Slower only when being initially loaded

Cruder model of concurrency (thread Vs process scheduling)

less robust – share common address space in JVM process

more complex to write, handle and configure

Because Servlets are Java classes, you do not end up with huge mess

of Java, HTML and JavaScript.

The Servlet engine does not always automatically reload Servlets.

Self Assessment Questions

3. –––––––– and –––––––– are the two core packages of Servlet.

4. Resource sharing can be done with CGI. (True / False)

2.3.3 Servlet API

The Java Servlet API is a class library for Servlets. The entire Servlet API is

contained in two packages:

1. javax.servlet and

2. javax.servlet.http.

Page 39: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 26

The javax.servlet Package

The javax.servlet package deals with generic Servlets. Classes and

interfaces from this package are protocol independent and define the

contracts between a Servlet class and the Servlet container. This Package

contains the following interfaces and classes:

a) The javax.servlet Interfaces

Servlet interface is at the heart of every Servlet. It is at the top in the

hierarchy of Servlet. It must be implemented by all the Servlets. The Servlet

interface defines the lifecycle methods of the basic Servlet: init() –

initialization, service() – service, and destroy() – destruction. The interface

also includes the getServletConfig() method, which the Servlet can use to

access the ServletConfig object. The Servlet container uses a ServletConfig

object to pass initialization information to the Servlet.

Other interfaces will be discussed where they are required in the future

explanation.

b) The javax.servlet Exception Classes

There are two exceptions contained in the javax.servlet package:

a) ServletException

b) UnavailableException

ServletException is a general exception which might be thrown to indicate a

problem with the user's request, processing the request, or sending the

response. The UnavailableException should be thrown when a filter or

Servlet is temporarily or permanently unavailable.

The javax.servlet.http

The javax.servlet.http deals with specialized HTTP Servlets. It defines

HTTP-specific subclasses of the generic Servlet elements, including session

management objects that track multiple requests and responses between

the Web server and a client.

2.4 The Servlet Interface

The Servlet interface defines the methods that are required for a Java class

to become a Servlet. All Servlets must implement the Servlet interface,

although most will extend from a class that has already implemented

Servlet.

Page 40: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 27

To implement this interface, you can write a generic Servlet that extends

javax.servlet.GenericServlet or an HTTP Servlet that extends

javax.servlet.http.HttpServlet.

Fig. 2.4: Relation Servlets Classes and Interfaces

Servlet interface contains life cycle methods of Servlet. Servlet interface

contains abstract method service() must be implemented in GenericServlet.

Because it is implemented in GenericServlet, if you are creating HttpServlet

(internally extends GenericServlet), there is no need to override the

service() method. HttpServlet can override other methods of HTTP which

can doGet(), doPost(), doHead() etc.

2.5 Servlet Life Cycle

The lifecycle of a Servlet begins when it is loaded into Server memory and

ends when the Servlet is terminated or reloaded. The Servlet interface

defines the following three lifecycle methods, called by the Servlet container:

a) public void init(ServletConfig config) throws ServletException

b) public abstract void service (ServletRequest req, ServletResponse

res) throws ServletException, IOException

c) public void destroy()

Page 41: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 28

Fig. 2.5: Servlet Life Cycle

Loading and instantiating a Servlet

When we start up a Servlet container, it searches for a set of configuration

files, i.e. web.xml called as Deployment Descriptors (DD) that describes all

the web applications. Deployment Descriptor is one per web application that

includes an entry for each of the Servlets it uses. First of all the Servlet

container creates an instance of the given Servlet class using the method

Class.forName(className).newInstance() and then loads the Servlet in the

memory.

The init () method – Servlet Initialization

After instantiation of Servlet, many times, a Servlet needs to perform some

kind of initialization before handling the request, Servlet calls init() method. It

is responsible for performing initialization required by the Servlet, which can

include setting up resources that the Servlet will require to process requests,

such as database connections. The init() will be called only once per

Servlet.

Instantiation

Load

init()

Service()

destroy()

Called with each request

Unloaded from memory

Loaded into memory

Page 42: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 29

Syntax:

public void init(ServletConfig config) throws ServletException

The container passes the object of ServletConfig interface, which contains

all the initialization parameters, declared in deployment descriptor. This is

quite important in order to ensure the reusability of a Servlet. For example, if

you are going to make a database connection in the Servlet instead of hard-

coding the username/password and the database URL in the Servlet, you

can use the init() method that allows you to specify them in the deployment

descriptor. These values can be changed as needed without affecting the

Servlet code.

web.xml having initialized parameter

<init-param>

<param-name>driver</param-name>

<param-value>org.gjt.mm.mysql.Driver</param-value>

</init -param>

<init -param>

<param-name>user</param-name>

<param-value>root</param-value>

</init -param>

<init -param>

<param-name>password</param-name>

<param-value>root</param-value>

</ init -param>

Example 2.1 Servlet getting initialized parameter for database

connection.

protected Connection con;

public void init(ServletConfig config){

try {

// Make sure the Driver class for MySQL is loaded

Class.forName(config.getInitParameter(driver));

// Try to connect to a database via JDBC

conn = DriverManager.getConnection("jdbc:mysql://localhost/Customer",

config.getInitParameter(user), config.getInitParameter(password));

}catch (Exception e) {

Page 43: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 30

// use the Servlet logging API to store error if any

getServletContext().log( "Error in JDBC connection: ", e);

}

}

You can receive the values declared in DD using getInitParameter () or

getInitParameterNames () of ServletConfig interface.

The service() method:

Each incoming service request to the Servlet is handled by service()

method. It accepts two parameters:

ServletRequest: The incoming request stream encapsulated in a

ServletRequest object, and

ServletResponse: The outgoing response stream encapsulated in a

ServletResponse object.

It is the heart of any Servlet. It may be called simultaneously by the

container in different threads to process many different requests. This

method is the only method that a Servlet is actually required to implement.

Syntax:

public void service(ServletRequest request, ServletResponse response)

throws java.io.IOException

The destroy () method

The Servlet engine stops a Servlet by invoking the Servlet's destroy()

method. The purpose of the destroy() method is to make sure that any

finalization of data, releasing of resources, closing of database connections,

open files, and network connections and so on, is to be carried out before

the Servlet instance is lost.

Example 2.2

public void destroy(){

try { // Close the connection if it is not null

if (con != null) { con.close();

}

}

catch (SQLException e) { // use the Servlet logging API to store error if

any

Page 44: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 31

getServletContext().log("Error in closing JDBC connection: ", e);

}

}

Self Assessment Questions

5. Which are the Servlet life cycle methods. (Select any three)

a. GetServlet() b. init () c. service() d. destroy()

6. Initialization parameters are mentioned in ––––––––- file.

2.6 The Generic Servlet Class

The GenericServlet is an abstract class and implements Servlet and

ServletConfig interfaces. It is used to develop protocol-independent

Servlets. Protocol could be HTTP, FTP etc.

Syntax

public abstract class GenericServlet implements Servlet, ServletConfig

It provides simple versions of the life-cycle methods init() and destroy, and

of the methods in the ServletConfig interface. It also provides a log method,

from the ServletContext interface. The Servlet writer must override only the

service method, which is abstract. Though not required, the Servlet

implementer should also override the getServletInfo method, and will want

to specialize the init and destroy methods if expensive Servlet-wide

resources are to be managed.

Fig. 2.5: Generic Servlet handling Generic Request

Server

Service()

method

Servlet Response Servlet Request

Page 45: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 32

Methods of Generic Server Class

public String getInitParameter(String)

o Returns a string containing the value of the named initialization

parameter, or null if the requested parameter does not exist.

public Enumeration getInitParameterNames()

o Returns the names of the initialization parameters for this Servlet as

an enumeration of Strings, or an empty enumeration if there are no

initialization parameters.

public ServletConfig getServletConfig()

o Returns a ServletConfig object containing any startup configuration

information for this Servlet.

public ServletContext getServletContext()

o Returns a ServletContext object, which contains information about

the network service in which the Servlet is running.

public String getServletInfo()

o Returns a string that contains information about the Servlet, such as

its author, version, and copyright.

public void init()

o This method is provided as a convenience so that Servlet writers do

not have to worry about storing the ServletConfig object.

public void init(ServletConfig)

o Initializes the Servlet and logs the initialization.

public void log(Exception, String)

o Logs the message with the cause of the exception. (Deprecated)

public void log(String)

o Writes the class name of the Servlet and the given message to the

Servlet log file.

public void log(String, Throwable)

o Logs the message with the root cause.

public abstract void service(ServletRequest, ServletResponse)

o Each incoming service request to the Servlet is handled by service ()

method.

Page 46: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 33

Example 2.3 GenericServlet

import java.io.*;

import javax.Servlet.*;

public FirstServlet implements Servlet {

private ServletConfig config;

public void init ()

{ //Write code for initialization here

}

public void service (ServletRequest req, ServletResponse res) throws

ServletException, IOException {

res.setContentType( "text/html" ); // setting MIME type

PrintWriter out = res.getWriter();

// output stream for writing data on the client side

out.println (<html>" );

out.println( "<head>" );

out.println( "<title>FIRST SERVLET</title>" );

out.println( "</head>" );

out.println( "<body>" );

out.println( "<h1>Welcome in the world of Servlet</h1>" );

out.println( "</body>" );

out.println( "</html>" );

out.close();

}

public void destroy()

{ // write cleanup task here

}

}

Self Assessment Questions

7. Generic class implements ––––––– and ––––––– interface.

8. GenericServlet can handle only HTTP protocol. (True / False)

2.7 The HttpServlet Class

HttpServlet is a protocol dependent, can handle only Http specific requests.

The HttpServlet object's implementation of the service() method, which is

Page 47: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 34

called during each service request, calls one of the seven different helper

methods. HTTP request can be GET, POST, HEAD, DELETE, PUT, TRACE

OPTION, TRACE.

An HTTP Servlet overrides doGet(), doPost(), doHead() most often instead

of service() of Servlet interface. The service() is already implemented in

GenericServlet. HttpServlet extends GenericServlet.

Fig. 2.6: HTTP Servlet handling HTTP Request

HttpServletRequest

To compile Servlet we need to download Servlet API that contain all Servlet

specific interfaces and classes. If you are user of Tomcat 6.0 web server,

you can get it from...\lib folder file name servlet-api.jar of Tomcat installed

directory. In this book we are going to see Tomcat web server for Servlet

deployment and execution.

Class HttpServlet hierarchy

java.lang.Object

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

Subclass of HTTP Servlet

doGet()

doPost()

doHead()

etc.

service()

HTTP Response

HTTP Request Server

Page 48: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 35

Table 2.1 HttpServlet Class Methods

HTTP Methods HttpServlet Methods

GET doGet()

POST doPost()

HEAD doHead()

DELETE doDelete()

PUT doPut()

TRACE doTrace()

OPTION doOption()

doGet () method

GET simply retrieves the data identified by the URL. In doGet () method the

data will append to the URL as a query string. A query (request) string for

doGet () looks like the following:

http://www.mniop.org/search?name=Rama&city=Pune

This method is preferred to use when we want to send the small amount of

data. GET is limited to about 256 characters (usually a browser limitation)

and creates ugly URL. It may vary depending on the browser. It is little

faster when compared to doPost(). It is not recommended when you are

sending some sensitive information like password, will be displayed as a

query string in the address bar of browser.

Syntax:

public void doGet (HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException

doPost () method

POST is used to transfer a block of data to the server in the entity body of

the request. It bundles the data in packet and then sends the packet of data

to the server. In this method we do not have any size limitation. All data

passed to server will be hidden; user cannot see this information in the

browser. This method will be executed when POST method is mentioned in

HTML form tag.

<Form action=”someaction” method = “POST”>

Page 49: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 36

action can be any Servlet or jsp request.

Syntax:

public void doPost (HttpServletRequest req, HttpServletResponse res)

throws IOException, ServletException

doGet () method can be called in doPost (), but reverse might affect

sometime.

Example 2.4 HttpServlet

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response)

throws IOException, ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head>");

out.println("<title>Hello Servlet!</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Welcome in the world of Servlet !</h1>");

out.println("</body>");

out.println("</html>");

}

}

In this example, import indicates including Servlet APIs and HttpServlet

specific APIs. When you are creating HTTP specific Servlet, class must

extend HttpServlet.

Self Assessment Questions

9. Default method HTTP is –––––––––– .

10. Data added in URL after ? is called as ––––––––––.

Page 50: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 37

2.8 Structure of Web Applications

A Web application is a collection of Servlets, Java-Server Pages (JSPs),

HTML documents, images, templates, and other web resources that are set

up in such a way as to be portably deployed across any Servlet-enabled

web server. Each and every Servlet needs to be deployed before it is

available for a client to use. Each web application strictly follows directory

structure, which is as follows:

webapps

WEB-INF

web.xml // Its a File

classes FirstServlet.class

lib

servlet-api.jar

Figure 2.7 Web Directory Structure for Tomcat

The above structure shows that each web application has a unique context

path. It contains all web components. For Tomcat Web server, “webapps”

is the root directory (context path), which contains special subdirectory

called as “WEB-INF”. This directory contains all private components for

web application. Components can be Servlet classes, library files,

deployment descriptor i.e. web.xml file and other private files.

Webapps might contain some public files that can be accessed by client.

These files can be static HTML pages, JSP pages or images.

If you are creating Web applications without any editor, we need to create

this structure manually under webapps folder of Tomcat directory.

If you are creating web application using any editor like, Net beans, Eclipse

etc., the structure will be created automatically.

The classes folder contains all Servlet (Java) classes. Lib folder contains all

required library files like driver files for database. These can be jar files.

Page 51: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 38

The deployment descriptor i.e. web.xml is an xml file used to deploy

Servlet. This contains xml tags.

Example 2.5 web.xml

<web-app>

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>First</servlet-name>

<url-pattern>/Welcome</url-pattern>

</servlet-mapping>

</web-app>

In the above example, <servlet> tag contains <servlet-name> and <servlet-

class> where we can mention the name of Servlet and actual Servlet class

that should be executed when client sends a request from browser.

And <servlet-mapping> tag contains <servlet-name> and <url-pattern>

where <servlet-name> should match with the <servlet-name> given in

<servlet> tag. <url-pattern> indicates the name with which the Servlet class

is executed in the URL address bar of the browser during the request.

The URL path can be anything as defined by the Servlet specification:

1. An exact pattern to match. The pattern must start with a /, but can

contain anything afterwards. This type of pattern is used for a one-to-

one mapping of a request to a specific Servlet.

2. An extension match, *.extension. In this case all URLs ending with the

given extension are forwarded to the specified Servlet, for example, by

Tomcat to map all requests to .jsp to a Servlet that knows how to

process Java Server Pages.

3. A path mapping. Path mappings must start with a / and end with a /*. In

between anything can appear. Path mappings are usually used for

forwarding all requests that fall in a certain directory to a specific Servlet.

4. Default Servlet, /. A default Servlet mapping is used to define a Servlet

for forwarding requests when no path information is given.

Page 52: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 39

For example, the default Servlet was used when you sent the first request to

http://localhost:8080/Welcome

To simplify deployment, these files can be bundled into a single archive file

and deployed to another server merely by placing the archive file into a

specific directory. These archive files have the extension .war, which stands

for “web application archive”.

WAR files are actually JAR files (created using the jar utility) saved with an

alternate extension. Using the JAR format allows WAR files to be stored in

compressed form and have their contents digitally signed. The .war file

extension was chosen over .jar to let people and tools know to treat them

differently.

Self Assessment Questions

11. For every Web Application ––––––– web.xml (s) is/are used.

12. .jar stands for ––––––– .

2.9 Servlet Config and Servlet Contexts

The javax.servlet.ServletContext interface provides a set of methods that

the Servlet can use to communicate with the Web server.

The ServletContext object is contained within the javax.servlet.ServletConfig

object, which is provided to the servlet when it is first initialized.

Using the ServletContext object, a servlet can perform the following

functions:

Set and store attributes that other servlets in the context can access.

Log events.

Obtain URL references to resources.

Get values assigned to initialization parameters. These are parameters

associated with a servlet, not an individual request.

Get the MIME type of files.

Obtain information about the servlet container, such as its name and

version.

A servlet context is associated with a Web application and shared by all the

servlets within that application.

Page 53: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 40

Servlet Config

The ServletConfig object is a parameter that can be passed into the init

method of the Servlet used to provide initial configuration information for

Servlets. Configuration information for a Servlet may consist of a string or a

set of string values included in the <init-param> tag of web.xml declaration.

The major benefit of this functionality is that it allows a Servlet to have initial

parameters outside of the compiled code and changed without needing to

recompile the Servlet.

You can get the ServletConfig object from the request object through the

getServletConfig method. This object is created by the container and

implements the javax.servlet.ServletConfig interface. ServletConfig defines

attribute for an individual Servlet.

This interface provides following methods for accessing initial parameter.

a) getInitParameter (String name)

The getInitParameter () returns a String object that contains the value of the

named initialization parameter or null if the parameter does not exist. The

return value is always a single String. It is upto the Servlet to interpret the

value.

b) getInitParameterNames ()

The getInitParameterNames () method returns the names of the Servlet's

initialization parameters as an Enumeration of String objects or an empty

Enumeration if the Servlet has no initialization parameters. It's most often

used for debugging.

Example 2.6 Showing to initialize Servlet-Config object in web.xml

<web-app>

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>FirstServlet</servlet-class>

<init-param>

<param-name>driver</param-name>

<param-value>org.gjt.mm.mysql.Driver</param-

value>

</init-param>

</servlet>

Page 54: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 41

<servlet-mapping>

<servlet-name>First</servlet-name>

<url-pattern>/Welcome</url-pattern>

</servlet-mapping>

</web-app>

<init-param> tag must be written in <servlet> tag only. It is accessible in the

specified Servlet here HelloWorld class can accesses value of “driver”

initialized parameter.

Servlet-Context

A Servlet context is rooted at a known path within a web container. For

example, if we have a stores application, it could exist under the context

/WebData. Therefore if the application contained an HTML file called

First.html if would be accessible at http://localhost:8080/WebData/First.html.

All requests that begin with the /WebData request path, known as the

context path, are routed to the web application associated with the Servlet

context.

The ServletContext represents the web application's view on the container

that it is deployed within. The ServletContext can be thought of as a

sandbox for a web application. The primary use of the ServletContext is to

share attributes between all of the Servlet in an application, and for loading

resources for use within the application.

Through the ServletContext interface, a Servlet can also access raw input

streams to Web Application resources, virtual directory translation, a

common mechanism for logging information, and an application scope for

binding objects.

Example 2.7 Showing to initialize Servlet-Context object in web.xml

<web-app>

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>FirstServlet</servlet-class>

<init-param>

<param-name>driver</param-name>

<param-value>org.gjt.mm.mysql.Driver</param-

value>

Page 55: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 42

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>First</servlet-name>

<url-pattern>/Welcome</url-pattern>

</servlet-mapping>

<context-param>

<param-name>email</param-name>

<param-value>[email protected]</param-value>

</context-param>

</web-app>

Self Assessment Questions

13. ––––––– is used per application and ––––––– is used for a application.

14. In which method of Servlet life cycle we pass ServletConfig as a

parameter.

a. init() b. service() c. destroy() d. non of them

2.10 Installing Tomcat Web Server

Jakarta Tomcat, is an Open Source web container that provides an

environment for developing and testing Web applications. Tomcat is

provided by the Apache Software Foundation that executes Java Servlet

and renders Web pages, which include Java Server Page coding. Apache

has provided Tomcat in both binary and source versions. Tomcat can be

used as either a standalone product with its own internal Web server or

together with other Web servers, including Apache, Netscape Enterprise

Server, Microsoft Internet Information Server (IIS), and Microsoft Personal

Web Server. It's not a high-performance Servlet engine, but it is a complete

implementation of the Servlet API. Tomcat is one of the several open source

collaborations that are collectively known as Jakarta.

This section is a guide to installing and configuring Apache Tomcat 6 for use

as a standalone Web server (for development) that supports Servlets 2.5

and JSP 2.1.

Page 56: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 43

To install and configure Tomcat, you will have to take the following

steps:

1. JDK 1.6 from Sun site at http://java.sun.com/javase/downloads/

index.jsp

2. Install JDK to …\Program Files\Java\jdk1.6.0

3. Download Tomcat 5 from http://tomcat.apache.org/download-60.cgi

4. Install Tomcat on …\Program Files\Apache Software Foundation\Tomcat

6.0.

Page 57: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 44

5. Set the port number to 8080 (default), or you can change to other. Set

the name as admin (default) or you can change as desired and give

password as desired. The password column can even be left blank.

6. Set the environment variables as follows: Either Right-click My

Comp

OR

Select properties or select Start Control Panel System

Advanced Environment Variable. Then,

1. Set Path: In Users variable topside of the dialog box, create a new

variable named PATH, and in the variable value field give the path of

JDK installation as

…\Program Files\Java\jdk1.6.0\bin;.;

2. Set Class path: In the same dialog box, create a new variable named

CLASSPATH, and in the variable value field give the path of servlet-

api.jar file as …\Tomcat 6.0\lib \servlet-api.jar. This is for servlet API.

3. Set CATALINA_HOME: In the same dialog box create new variable

named CATALINA_HOME, and in the variable value field give the

location of Tomcat installation as …\Program Files\Apache Software

Foundation\Tomcat 6.0.

4. Set JAVA_HOME: In the same dialog box create new variable named

JAVA_HOME, and in the variable value field give the location of JDK

installation excluding bin as C:\Program Files\Java\jdk1.6.0.

Page 58: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 45

How to run Servlet application on Tomcat

5. Take the example 2.4 save it in …Tomcat 6.0\webapps\WEB-

INF\classes.

6. Take the example 2.5 save it in … Tomcat 6.0\webapps\WEB-

INF\web.xml

7. Go to …\Program Files\Tomcat 6.0\bin directory and start tomcat by

double clicking on the startup batch file.

8. Open a new instance of any browser and type the following URL in the

Address bar:

http://localhost:8080/Welcome

2.11 Summary

Server Side Tools: This topic described various kinds of Server Side

programming Tools like, CGI, ASP, PHP, ColdFusion etc., their

advantages and disadvantages. It also highlighted the how Servlets are

better than CGI.

Java Servlet: This topic explained about Java Servlets, various Servlet

API's. It also made a comparison between Servlets and CGI.

The Servlet Life Cycle: This topic has described the meaning and

stages involved in the life cycle of a Servlet. It also described the

working of Servlets.

Generic Servlet Class: This topic has explained the concept of

Generic Servlets in detail.

The HttpServlet Class: This topic has explained the APIs of

HttpServlet, their implementation and working.

Structure of Web Applications: In this topic, the basic structure and

components of a Web application have been described.

Servlet Contexts and Servlet Config: A detailed discussion of the

concepts of Servlet Context and Servlet Config has been dealt with.

2.12 Terminal Questions

1. What is Servlet? What are the features of 2.5 API? Explain.

2. What is Servlet Life Cycle? Explain in detail.

3. Differentiate ServletContext and ServletConfig.

Page 59: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 2

Sikkim Manipal University Page No.: 46

2.13 Answers

Self Assessment Questions

1. false

2. Jscript & VBScript

3. javax.servlet and javax.servlet.http

4. false

5. b,c,d

6. web.xml

7. ServletContext and ServletConfig

8. false

9. GET

10. Query String

11. one

12. Java Archive

13. ServletConfig and ServletContext

14. init()

Terminal Questions

1. It is a web component managed by web container, which generates

dynamic contents in web page. (Refer section 2.1 and 2.3)

2. - newInstance(): Creates an object to the class. Creates the Servlet

object.

- init(): We pass the configuration parameters to the init()method. This

object is responsible for getting the necessary configuration details from

the configuration file or the deployment descriptors i.e. web.xml and is

responsible for initializing the Servlet.

- service(): The actual tasks are performed. We do the real coding in

this method.

- destroy(): Kills the Servlet object. (Refer section 2.4)

3. ServletConfig is for an individual Servlet and ServletContext shares

attributes among all Servlets in an application.

ServletConfig is passed as a parameter in init() method of Servlet and

ServletContext is rooted at a known path within a Web container.

(Refer section 2.8)

Page 60: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 47

Unit 3 The Servlet Request: Form Data

Structure:

3.1 Introduction

Objectives

3.2 Setting Header Information

3.3 Retrieving Header Information

3.4 Handling Form Elements

3.5 Servlet Redirection

sendRedirect method

The Request Dispatcher interface

3.6 Summary

3.7 Terminal Questions

3.8 Answers

3.1 Introduction

In the previous unit, the basics of Servlets have been discussed. The basics

of running the Servlet applications, the protocols used for communication,

and the structure of Web applications have also been dealt with.

This unit is an extension of the previous unit, which discusses the creation

of user interfaces with the help of HTML.

After building Web application, you need to deploy application server in

which your application runs. Then the user can request for the application. A

request is a line of text specifying what resource a client would like to

retrieve. Servlets have provided a number of methods to retrieve such

information about the requests and responses. In this unit, you will be

learning all such methods of retrieving information.

You will also be learning Servlet redirection. Redirection is generally used

when:

A document moves to the new location.

For load balancing (distributing the load to several different machines)

For simple randomization (choosing a destination at random) etc.

Page 61: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 48

To understand the subject discussed in this topic, we need to understand

the HTML tags, Client – Server communication, Event – Driven

programming, and Server processing.

Objectives:

After studying this unit, you should be able to:

describe the usage of HTTP Headers in information processing

explain the usage of HTML elements in usage of forms

describe the process of getting and setting request parameters.

iIlustrate the concept of Servlet redirection methods

3.2 Setting Header Information

The HttpServletResponse provides a number of methods to assist Servlets

in setting HTTP response headers. This interface allows a Servlet's service

method to manipulate HTTP – protocol specified header information and

return data to its client. When a client sends a request either by Get or Post

method, the Servlet sends a number of header information like accept,

accept language, encoding, content length, host, user agents, cookies, etc.

Table 3.1 shows some methods for adding such header information in the

response.

Table 3.1: HttpServletResponse Methods

Method Description

addCookie(Cookie) Adds the specified cookie to the response.

encodeRedirectURL(String) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.

sendError(int) Sends an error response to the client using the specified status code and a default message.

sendRedirect(String) Sends a temporary redirect response to the client using the specified redirect location URL.

Page 62: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 49

setDateHeader(String, long) Adds a field to the response header with the given name and date-valued field.

setHeader(String, String) Adds a field to the response header with the given name and value.

setIntHeader(String, int) Adds a field to the response header with the given name and integer value.

setStatus(int) Sets the status code for this response.

Example 3.1

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Clock extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/plain");

PrintWriter out = res.getWriter();

res.setHeader("Refresh", "1");

out.println(new Date().toString());

}

}

3.3 Retrieving Header Information

In header request, Servlet sends extra information about its response. This

information can be retrieved using ServletRequest Interface. Following are

various methods of ServletRequest Interface.

Page 63: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 50

Table 3.2: ServletRequest methods

Method Description

getAttribute(String) Returns the value of the named attribute of the request, or null if the attribute does not exist.

getAttributeNames() Returns an enumeration of attribute names contained in this request.

getContentLength() Returns the size of the request entity data, or –1 if not known.

getContentType() Returns the Internet Media Type of the

request entity data, or null if not known.

getReader() Returns a buffered reader for reading text

in the request body.

getRealPath(String) Returns the IP address of the agent that

sent the request.

getRemoteHost() Returns the fully qualified host name of

the agent that sent the request.

getScheme() Returns the scheme of the URL used in

this request, for example "http", "https", or

"ftp".

getServerName() Returns the host name of the server that

received the request.

getServerPort() Returns the port number on which this

request was received.

Many such methods are available in ServletRequest Interface.

Methods of HttpServletRequest

Table 3.3: HttpServletRequest methods

Method Description

getAuthType() Gets the authentication scheme of this request.

getCookies() Gets the array of cookies found in this request.

getDateHeader(String) Gets the value of the requested date header field of this request.

Page 64: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 51

getHeader(String) Gets the value of the requested header field of this request.

getHeaderNames() Gets the header names for this request.

getMethod() Gets the HTTP method (for example, GET, POST, PUT) with which this request was made.

getPathInfo() Gets any optional extra path information following the servlet path of this request's URI, but immediately preceding its query string.

getPathTranslated() Gets any optional extra path information following the servlet path of this request's URI, but immediately preceding its query string, and translates it to a real path.

getQueryString() Gets any query string that is part of the HTTP request URI.

getRemoteUser() Gets the name of the user making this request.

getServletPath() Gets the part of this request's URI that refers to the servlet being invoked.

getSession() Gets the current valid session associated with this request, if create is false or, if necessary, creates a new session for the request.

These are the few methods of HttpServletRequest Interface.

Example 3.2

import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class headerDemo extends HttpServlet {

public void doGet(HttpServletRequest req,HttpServletResponse res) throws

ServletException, IOException {

res.setContentType("text/html");

Page 65: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 52

PrintWriter out = res.getWriter();

out.println("<html>");

out.println("<body>");

out.println("<table border=1>");

out.println("<tr><th>Name</th><th>Value</th></tr>");

Enumeration enames= req.getHeaderNames();

while(enames.hasMoreElements()) {

String name= (String)enames.nextElement();

String value=req.getHeader(name);

out.println("<tr><td>"+name+"</td>");

out.println("<td>"+value+"</td></tr>");

}

out.println("</table>");

out.close();

}

}

Output:

Self Assessment Questions

1. Which method sets the value of the named header as a String?

A. setHeader

B. setDateHeader

C. setStatus

D. none of the above

Page 66: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 53

2. The most common status code numbers are defined as mnemonic

constants (True/False).

3. ___________ request indicates that client wants to see only the headers

of the response, to determine the cookies, content length, user agent

etc.

A. PUT

B. GET

C. TRACE

D. HEAD

4. To retrieve all header names from request, which of the following will be

used?

A. getParameter()

B. getParameterNames()

C. getHeaderNames()

D. getAttributeNames()

3.4 Handling Form Elements

HTML forms are used to create good GUI for user interaction. Here you can

create Textbox, checkboxes, radio buttons, combo box, and various kinds of

GUIs on the forms. After creating forms and GUI, the important step is to

consider is the methods to retrieve inform of these forms in servlet.

This data can be retrieved either by GET or POST method. In GET method

data will be appended in URL, while POST data will be send with the

request. POST data is visible and not added in URL.

while reading information from server always we use GET method. But

when we sending any information on server, POST method is the best

solution.

It is very easy to retrieve data from form using Servlet API. One of the nice

features of Java servlets is that all of this form parsing is handled

automatically which was not available in CGI.

HttpServletRequest interface has provided for retrieving information.

Following some methods.

Page 67: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 54

Table 3.3: HttpServletRequest Methods

Method Description

String getParameter(jString name) Returns the value of a request

parameter as a String, or null if

the parameter does not exist.

Enumeration getParameterNames() Returns Enumeration of String

objects containing the names of

the parameters contained in this

request.

String[]

getParameterValues(String name)

Returns an array of String objects

containing all the values the given

request parameter has, or null if

the parameter does not exist.

String getQueryString() Returns the query string that is

contained in the request URL

after the path

Example 3.3

1. Save this file in GetParaDemo.html

<html>

<body>

<form action="/SIS/GetParaDemo" method=POST>

<table border="1">

<tr>

<td>Enter First name :</td>

<td> <input type="input" name="fname"/></td>

</tr>

<tr>

<td>Enter Last name : </td>

<td><input type="input" name="lname"/></td>

</tr>

<tr>

<td>Enter Cell No: </td>

<td><input type="input" name="cell"/></td>

</tr>

Page 68: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 55

<tr>

<td>

<input type="submit" name="btn" value="Submit"/> </td></tr>

</form>

</body>

</html>

2. Save this file in GetParaDemo.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class GetParaDemo extends HttpServlet

{

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException,IOException

{

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String firstName,lastName;

String cell;

firstName= req.getParameter("fname");

lastName= req.getParameter("lname");

cell= req.getParameter("cell");

out.println("<html>");

out.println("<head> Getting Parameter Demo </head><br>");

out.println("<body>");

out.println("Wel-come Mr."+firstName+" "+lastName + "<br>");

out.println("Your cell No :"+cell);

out.println("<body>");

out.println("</html>");

}

}

Page 69: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 56

User Input:

Output:

Getting Parameter Demo

Wel-come Mr.Anil Dudhe

Your cell No :9922558490

Using getParameterNames() :

The getParameterNames method returns an enumeration of the string

objects. Each of these strings is the name of a parameter and can be used

as an argument to getParameter or getParameterValues.

Example 3.4

Enumeration enames = req.getParameterNames();

while(enames.hasMoreElements())

{

String name = (String) enames.nextElement();

String value = req.getParameter(name);

out.println("Name : "+ name+"<br>");

out.println("Value : "+ value+"<br>");

}

Using various GUI like textbox, radio button and List box

1. Save this file in GUIDemo.html

<html>

<body>

<form action="/SIS/Registration" method ="GET">

<center><h1>Registration Form</h1>

<table border =1 align="center">

<tr>

<td>First Name</td>

<td><input type = "text" name ="fname"></td>

Page 70: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 57

</tr>

<tr>

<td>Middle Name</td>

<td><input type = "text" name ="mname"></td>

</tr>

<tr>

<td>Last Name</td>

<td><input type = "text" name ="lname"></td>

</tr>

<tr>

<td>Education</td>

<td> <select name="education">

<option> MBA</option>

<option> ME</option>

<option> MCA</option>

<option> MSc</option>

<option> Other</option>

</td>

</tr>

<tr>

<td>Gender</td>

<td>Male <input type = "Radio" name ="gender" value = "Male">

Female <input type = "Radio" name ="gender" value =

"Female"></td>

</tr>

<td><input type="submit" name="btnsub" value="Submit"> </td>

<td><input type="reset" name="btnreset" value="Cancel"> </td>

</tr>

</table>

</form>

</body>

</html>

Page 71: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 58

2. Save this page in GUIDemo.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

import java.util.*;

public class GUIDemo extends HttpServlet

{

public void doPost(HttpServletRequest req, HttpServletResponse

res) throws ServletException,IOException

{

res.setContentType("text/html");

PrintWriter out = res.getWriter();

Enumeration enames = req.getParameterNames();

out.println("<html> <body> <table border=1>");

out.println("<tr><th>Name</td><th>Value</th></tr>");

while(enames.hasMoreElements())

{

String name = (String) enames.nextElement();

String value = req.getParameter(name);

out.println("<tr><td>"+name+"</td><td>"+value+"</td></tr>");

}

out.println("</table></body></html>");

}

}

User Input form

Output: Registration Form

Page 72: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 59

Self Assessment Questions

5. To retrieve all requested parameters, which following will be used?

A. getParameter()

B. getParameterNames()

C. getHeaderNames()

D. getAttributeNames()

6. Data appended in URL after question marks is called as –––––––––.

A. URL Data

B. QueryString

C. Name/value pair

D. None of the above

3.5 Servlet Redirections

When building a new Web application or adding some new pages in the

existed Web application, it is always required to forward the processing of a

request to another servlet, or to include the output of another servlet in the

response. This can be achieved by various methods of servlet redirection.

Following are the methods of Servlet Redirections

1. sendRedirect method

2. RequestDispatcher interface

3.5.1 sendRedirect Method

This method redirects response back to the client's browser with status

code. The container decides whether it can handle the request; otherwise

the browser will normally interpret this response by initiating a new request

to the redirect URL given in the response. This method works in browser

only.

Example 3.5

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class RedirectDemo extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

IOException,ServletException {

res.setContentType("text/html");

ServletContext context = this.getServletContext();

Page 73: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 60

PrintWriter out = res.getWriter();

String uName = req.getParameter("name");

String password = req.getParameter("pwd");

if(uName.equals("yash"))

res.sendRedirect("/MyApplication/Success.jsp");

else

out.println("<h1>Wrong username/password</h1>");

out.close();

}

}

Because the browser issues a completely new request any objects stored

as request attributes before the redirect occurs will be lost.

3.5.2 RequestDispatcher Interface

The RequestDispatcher allows the dynamic inclusion of web components

either by including in the current component or by forwarding to another web

component. It takes request from the client and sends them to other

resources available on the server. Resources could be any Servlet, HTMl,

JSP or other. A RequestDispatcher has two primary methods:

A. Include: This is for including the response of another program in the

current request.

B. Forward: This is forwarding the request of the current program to

another one.

General example where we can use RequestDispatcher: include a standard

menu in all pages.

An object implementing the RequestDispatcher interface may be obtained

via the following methods:

a) ServletContext.getRequestDispatcher(String path)

b) ServletRequest.getRequestDispatcher(String path)

c) ServletContext.getNamedDispatcher(String name)

a) RequestDispatcher with ServletContext:

A RequestDispatcher object can be obtained by calling the

getRequestDispatcher method of the ServletContext object. An instance of

Page 74: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 61

ServletContext can be obtained by calling the getServletContext method of

the HttpServlet class. Following are the steps of getting instance of

RequestDispatcher.

1. Get a servlet context instance from the servlet instance:

ServletContext sc = this.getServletContext();

2. Get a request dispatcher from the servlet context instance, specifying

the page-relative or application-relative path of the target JSP page as

input to the getRequestDispatcher() method:

RequestDispatcher rd =sc.getRequestDispatcher

("/DemoRedirection");

3. Invoke the include() or forward() method of the request dispatcher,

specifying the HTTP request and response objects as arguments.

rd.include(request, response);

OR

rd.forward(request, response);

public void forward (ServletRequest request, ServletResponse response)

throws ServletException, java.io.IOException

public void include(ServletRequest request, ServletResponse

response)

throws ServletException, java.io.IOException

ServletContext methods require an absolute URL, must begin with „/‟ is

interpreted

Example 3.6 Including resources in the same request.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class RedirectDemo extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

IOException, ServletException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

ServletContext context = this.getServletContext();

Page 75: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 62

ServletContext sc = getServletContext();

RequestDispatcher rd;

rd= sc.getRequestDispatcher("/Menu.html");

rd.include(req, res);

rd = sc.getRequestDispatcher("/LoginForm.html");

rd.include(req, res);

out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

doGet(req,res);

}}

b) .RequestDispatcher with ServletContext

The ServletRequest.getRequestDispatcher method allows relative paths

that are relative to the path of the current request (not relative to the root of

the ServletContext). It is provided in the ServletRequest interface. The

behavior of this method is similar to the method of the same name in the

ServletContext.

If you create RequestDispatcher as follows:

ServletContext sc = getServletContext();

RequestDispatcher rd;

rd= sc.getRequestDispatcher("Menu.html");

rd.include(req, res);

At runtime it will produce an error, which on my Tomcat

setup was as follows:

java.lang.IllegalArgumentException: Path Menu.html

does not start with a "/" character

RedirectDemo.doGet(RedirectDemo.java:16)

javax.servlet.http.HttpServlet.service(HttpServlet.java:6

17)

javax.servlet.http.HttpServlet.service(HttpServlet.java:7

17)

Page 76: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 63

Example 3.7

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Regi extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

IOException,ServletException{

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String uName = req.getParameter("name");

String password = req.getParameter("pwd");

ServletContext context = getServletContext();

RequestDispatcher rd = req.getRequestDispatcher("form");

If(uName.equals("Yash"))

rd.forward(req,res);

else

res.sendRedirect("Error.html");

out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws

IOException,ServletException

{

doGet(req,res);

}

}

Page 77: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 64

For the above examples following is the deployment descriptor in web.xml.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>Redirect</servlet-name>

<servlet-class>RedirectDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Redirect</servlet-name>

<url-pattern>/DemoRedirect</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>Regi</servlet-name>

<servlet-class>Regi</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Regi</servlet-name>

<url-pattern>/Regi</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>form</servlet-name>

<servlet-class>form</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>form</servlet-name>

<url-pattern>/form</url-pattern>

</servlet-mapping>

</web-app>

Page 78: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 65

Using setAttribute and getAttribute methods

Included or forwarded objects do not share Java variables with the

originating resource, but they do share attributes. Thus, if you include the

following code

request.setAttribute("username", uName);

Within the doGet method, it will be possible to retrieve the value of that

attribute with a call to request.getAttribute(“username”);

Example 3.8 Setting attributes in context

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Regi extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws

IOException,ServletException {

res.setContentType("text/html");

ServletContext context = getServletContext();

PrintWriter out = res.getWriter();

String uName = req.getParameter("name");

context.setAttribute("Myattribute",uName); // Setting Attribute

RequestDispatcher rd = req.getRequestDispatcher("form");

if(uName.equals("Yash"))

rd.forward(req,res);

else

res.sendRedirect("Error.html");

out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws

IOException,ServletException {

doGet(req,res);

}

}

Page 79: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 66

Example 3.9 Getting attribute from context

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class form extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

res.setContentType("text/html");

ServletContext context = this.getServletContext();

PrintWriter out = res.getWriter();

String name = (String)context.getAttribute("Myattribute"); //getting

attribute out.println("<h1> User Name : </h1>" + name);

out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

doGet(req,res);

}

}

c) .ServletContext.getNamedDispatcher(String name)

The ServletContext.getNamedDispatcher method takes a String argument

indicating the NAME of a servlet known to the ServletContext. If a servlet is

found, it is wrapped with a RequestDispatcher object and the object is

returned. If no servlet is associated with the given name, the method must

return null.

Self Assessment Questions

7. What will be displayed in the browser when the following program using

GET request is sent to FirstServlet assuming that the buffer is large

enough to hold all the data before sending the data to the client?

(Select 1 correct option)

Page 80: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 67

In the doGet() of FirstServlet:

PrintWriter out = response.getWriter();

out.println("<html><body>Page 1");

RequestDispatcher rd =

request.getRequestDispatcher("SecondServlet");

rd.forward(request, response);

In the doGet() of SecondServlet:

PrintWriter out = response.getWriter();

out.println("<br>Page 2</body></html>");

A. Only Page1

B. Only Page2

C. Page1 and Page2

D. IllegalStateException at Runtime.

8. ––––––– is a client side redirection.

A. sendRedirect

B. RequestDispatcher

C. SetHeader

D. All of the above

9. HttpServlet can share its objects among requests. (True/False).

3.6 Summary

This unit has covered the following topics:

1. Setting Header Information: In this topic, we discussed about setting of

the header information in a query sent to the server.

2. Retrieving Header Information: This topic dealt with the process of

retrieving header information from the Requests and responses.

3. Handling form elements: This topic illustrated designing HTML forms

and the various components used in this process.

4. Redirection: This topic explained the process of request redirection for

a given URL.

Page 81: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 3

Sikkim Manipal University Page No.: 68

3.7 Terminal Questions

1. What are the various methods of HttpServletResponse interface?

2. What are the differences between sendRedirect and Request

Dispatcher?

3.8 Answers

Self Assessment Questions

1. A

2. SC_OK

3. D

4. C

5. B

6. B

7. B

8. A

9. True

Terminal Questions

1. The HttpServletResponse provides a number of methods to assist

servlets in setting HTTP response headers. This interface allows a

servlet's service method to manipulate HTTP-protocol specified header

information and return data to its client. (Refer section 3.2)

2. a. sendRedirect is a client side redirection and RequestDispatcher is

server side redirection.

b. sendRedirect uses absolute path and RequestDispatcher uses

relative path.

c. sendRedirect is a method of HttpServletRequest and

RequestDispatcher can be implemented by HttpServletRequest as

well as ServletContext by these interfaces. (Refer section 3.5)

Page 82: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 69

Unit 4 Exception Handling in Servlets

Structure:

4.1 Introduction

Objectives

4.2 Throwable Class

4.3 Exception Classes

4.4 Exception Handling Keywords

4.5 Exception Handling Methods

Using the web.xml file

Using a RequestDispatcher

Using sendError() method of HttpServletResponse

Using the Web Application Log

4.6 Summary

4.7 Terminal Questions

4.8 Answers

4.1 Introduction

In the previous units, we discussed about writing code to run Servlets,

designing and running HTML forms, and small bits of coding. In this unit, we

are going to read about the various ways in which errors are handled in the

programs written either on the client side or server side.

Exception handling is an elementary part of any Web application

development. Exceptions provide a more natural and elegant way to handle

errors. Exceptions allow you to separate error-handling code from normal

code, which makes for cleaner, more readable applications. When an

exception occurs, it causes the flow of program execution to be transferred

to a pre-designated "catcher" block of code. The exception carries with it

an object that contains information about the situation that caused the

exception.

The Java compiler requires that a method either declare the exceptions it

can generate or catch and deal with them itself. This promotes error

information to the same level of importance as argument and return typing.

Page 83: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 70

As a Java programmer, you know precisely what exceptional conditions you

must deal with, and you have help from the compiler in writing correct

software that doesn't leave them unhandled.

Within Java, when an exception is thrown and not caught within the method

that threw it, it filters upward. Specifically, it propagates back to the caller of

the method until either it is caught, or it is thrown back out of main. This

assumes that main declares itself as throwing some (or all) exception types.

In general, you should take care to catch all servlet-generated exceptions in

the servlet and take appropriate action to inform the client what has

happened. If you don’t, instead of the expected page, the user is likely to

see a Java exception stack trace on the screen.

Although you may find the information useful during development, an

exception stack trace sent to the client will leave most users bewildered and

worried.

When a fatal exception occurs, there is often nothing to do but tell the client

that a serious error has occurred. The following catch block simply returns a

HTTP 503 Service Unavailable error to the client, along with a suitable error

message:

catch (RemoteException ex)

{

res.sendError(res. SC_SERVICE_UNAVAILABLE, “Internal

communication error”);

}

In other situations, it might be appropriate to redirect the user to another

URL that has a form that the user can use to report the error:

catch (RemoteException ex)

{

res. sendRedirect(“/Servlets/ReportErrorPage”);

}

A Servlet can throw a number of exceptions that will be handled by the

server. During initialization or while handling requests, the servlet instance

can throw an UnavailableException or a ServletException. If this happens,

the action taken by the server is implementation specific, but it is likely to

Page 84: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 71

return a 503 Service Unavailable response to the client. In this case, you

can still use the error-page tag in the web.xml file to send the client an

appropriate message when the server handles the exception.

These are some of the major questions we will answer in this unit first from

a generic way and then as applicable to Servlet applications.

Objectives:

After studying this unit, you should be able to:

describe and explain the importance of Exception Handling

explain the exception handling from servlet specification perspective.

compare Throwable Class and Exception Class

describe various techniques of Exception Handling.

4.2 Throwable class

The java.lang.Throwable class is the super class of all errors and exceptions

in the Java language. When an error occurs within a running program, an

appropriate instance of this class is created and said to be thrown. Throwing

an exception is like throwing a beeping; flashing red ball to indicate there is

a problem that can't be handled where it occurred. Somewhere, this ball will

be caught and the problem will be dealt with.

We need to catch that exception and handle it or let the JVM handle the

problem, which generally results in terminating the current program. In some

cases Java enforces the code to try and handle exceptions, and in others

the exceptions are left to freely pass to a JVM.

The Throwable class contains:

detail stack of execution.

a message string that gives more information about the error.

also contain a cause: another Throwable that caused this Throwable to

get thrown.

There are three main subclasses of the Throwable class which are:

1) Error

2) Exception

3) Runtime Exception

Page 85: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 72

Fig. 4.1: Throwable Class Hierarchy Diagram

Exceptions

Definition: “Servlet exceptions are abnormal conditions that can occur while

executing a piece of code in a Servlet”.

In Java, exceptions are objects. When you throw an exception, you throw an

object. You can't throw just any object as an exception, however, only those

objects whose classes descend from Throwable class can be thrown as

exceptions. Throwable serves as the base class for an entire family of

classes, declared in java.lang, that your program can instantiate and throw.

Exceptions can occur at:

1. Run - time, for example when a servlet is processing the form data.

2. Compile - time.

Exceptions need to be handled properly; otherwise the application may not

work.

Some of the common run time exceptions or unchecked exceptions,

encountered in a servlet are the HTTP Servlet errors like Internal server

errors 500, 404 etc.., the data handling errors like NumberFormatError,

NullPointerException, DivideByZeroException etc.

Compile - time exceptions or checked exceptions need to be handled before

deploying Web applications. Some common compile - time exceptions are

ClassNotFoundException, NoSuchMethodException etc.

Throwable

Error Exception

RuntimeException

Page 86: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 73

Self Assessment Questions

1. Run-time exception can be created by extending –––––––– class.

2. Exception class is the top in Exception Hierarchy (True/False)

3. Exception occurs either at compilation time or at run time (True/False)

4.3 Exception Classes

Exceptions generated from runtime are called unchecked exceptions. These

kinds of exceptions are not possible for the compiler to determine that your

code will handle the exception. Exception classes that descend from

RuntimeException and Error classes are Unchecked Exceptions or

Runtime Exceptions. Examples for RuntimeException are illegal cast

operation, inappropriate use of a null pointer, referencing an out of bounds

array element.

Error exception classes signal critical problems that typically cannot be

handled by your application. Examples are out of memory error, stack

overflow, failure of the Java VM.

The Figure 4.2 below shows the hierarchy of the Throwable class, and lists

a few of the classes sub-classed from the Error and Exception classes.

There are many more classes than those listed here, but the figure

demonstrates the general idea.

Fig. 4.2: Throwable Class Hierarchy Diagram

Page 87: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 74

4.4 Exception Handling Keywords

The following are the Five keywords used in exception handling:

try: Identifies a block of statements within which an exception might be

thrown.

catch: Must be associated with a try statement and identifies a block of

statements that can handle a particular type of exception. The

statements are executed if an exception of a particular type occurs

within the try block.

finally: must be associated with a try statement and identifies a block of

statements that are executed regardless of whether or not an error

occurs within the try block

throw: You can throw your own exceptions with throw statement. All

methods use the throw statement to throw an exception. The throw

statement requires a single argument: a Throwable object.

throws: Instead of try…catch block, if you want to catch exception in

any method you can use throws clause with that method.

Self Assessment Questions

4. Which statements are correct?

a) HttpServlet.init() throws ServletException

b) HttpServlet.service() throws ServletException and IOException

c) HttpServlet.destroy() throws ServletException

d) HttpServlet.doHead() throws ServletException

5. Statements written in ––––––––– are executed even there is an

exception which is not caught.

a) throws

b) throw

c) try

d) finally

4.5 Exception Handling Methods

In a Java Servlet, an exception is represented by an instance of the class -

javax.servlet.ServletException.

There are many ways of handling exceptions in a Servlet, which are:

1. Using the web.xml file

Page 88: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 75

2. Using a RequestDispatcher

3. Using sendError() method of HttpServletResponse.

4. Using the Web Application Log

4.5.1 Using the web.xml file

Handling errors can be defined declaratively using the sub tag of <error-

page> in web.xml file. There are two ways in this declaration.

A. <error-code> tag of <error-page>

If the servlet chooses to handle the error codes, <error-code> tag

that is within <error-page> tag is used to identify the value.

Following is a code snippet that demonstrates handling of Forbidden error

403 in a servlet. Whenever this exception is encountered, the JSP, Servlet

or HTML mapped in <location> tag is displayed.

The file Service.html can be a simple HTML page that displays a

customized message for the exception.

The web.xml mapping for handling error-code:

Declaration in web.xml

<web-app>

.......

<error-page>

<error-code>403</error-code>

<location>/Service.html</location>

</error-page>

........

</web-app>

Servlet code showing the use of 403

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class form extends HttpServlet {

Page 89: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 76

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String uName = req.getParameter("name");

String password = req.getParameter("pw");

if(uName.equals("Raj") && password.equals("Pune"))

res.sendRedirect("/Sample/Menu.html");

out.close();

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

doGet(req,res);

}

}

If you are not an authorized user, the statement will be executed showing

the output as in Figure 4.3:

Fig. 4.3: Output if, there is error.

Service.html file

<html>

<body>

Internal Server Error 500

Page 90: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 77

<br><br>

Possibilities :

Check variable/parameter

</body>

</html>

B. <exception-type> tag of <error-page>

If, however, the page chooses to handle an exception, <exception-type> tag

that is within <error-page> tag is used.

In <exception-type> we specify the type of exception. Following snippet

code shows how to use exception type.

Servlet Code ExceptionServlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class ExceptionServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws IOException,ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

ServletContext sc = getServletContext();

int n1= Integer.parseInt(request.getParameter("fnum"));

int n2 = Integer.parseInt(request.getParameter("snum"));

int result =0;

result = n1 / n2 ; // might throw exception

out.println("<h1> Dividion Result </h1>"+ result);

out.close();

}

}

Page 91: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 78

Error tag in web.xml

<error-page>

<exception-type>java.lang.ArithmeticException</exception-type>

<location>/Error.html</location>

</error-page>

Error.html file

<html>

<body>

<h1> Check possibilities</h1>

<li> Arithmetic type of exception </li>

<li> Number Format type of exception </li></body>

</body>

</html>

Fig. 4.4: User Input Screen

Fig. 4.5: User Output

Page 92: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 79

4.5.2 Using a RequestDispatcher

A RequestDispatcher can be used to receive the requests from the client

and forward the same to any resource such as a servlet, HTML file, or JSP

file on the server. This mechanism can be made use to forward the request

to a different resource whenever an exception is encountered.

Example:

Servlet Code ExceptionServlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class ExceptionServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws

IOException,ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

ServletContext sc = getServletContext();

int n1= Integer.parseInt(request.getParameter("fnum"));

int n2 = Integer.parseInt(request.getParameter("snum"));

int result =0;

try {

result = n1 / n2 ; // might throw exception

} catch(ArithmeticException a)

{

RequestDispatcher rd =

request.getRequestDispatcher("/Arithmetic.html");

rd.forward(request,response);

}

out.println("<h1> Dividion Result </h1>"+ result);

out.close();

}

}

Page 93: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 80

4.5.3 Using sendError() method of HttpServletResponse

When sendError method is called, the servlet container sends an error page

to the browser. This method uses Mnemonic Constant with respect to the

status code as mentioned in the table 4.1. The string message that can be

set in sendError() is ignored if the error code has a mapping file configured

in web.xml. Otherwise it will be displayed in the browser.

In the following example, the error 404 indicated by SC_NOT_FOUND is

mapped to the file 404Error.html in the file web.xml

Example:

response.sendError (response. SC_NOT_FOUND, ”Resource Not

Found”);

Table 4.1: HTTP Status Codes

Mnemonic Constant Code Default

Message Meaning

SC_OK 200 OK This is the default status code which indicates successful request

SC_NO_CONTENT 204 No Content This code returns body without content and used to avoid the "Document contains no data" error message.

SC_MOVED_ PERMANENTLY

301 Moved Permanently

This code is used when the requested resource has permanently moved to a new location. Most browsers automatically access the new location.

Page 94: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 81

SC_MOVED_TEMPORARILY

302 Moved Temporarily

The requested resource has temporarily moved to another location, but future references should still use the original URL to access the resource. The new location is given by the Location header.

SC_UNAUTHORIZED 401 Unauthorized The request lacked proper authorization. Used in conjunction with the WWW-Authenticate and Authorization headers.

SC_NOT_FOUND 404 Not Found The requested resource was not found or is not available.

SC_INTERNAL_SERVER_ERROR

500 Internal Server Error

An unexpected error occurred inside the server that prevented it from fulfilling the request.

SC_NOT_IMPLEMENTED

501 Not Implemented

The server does not support the functionality needed to fulfill the request.

SC_SERVICE_UNAVAILABLE

503 Service Unavailable

The service (server) is temporarily unavailable but should be restored in the future. If the server knows when it will be available again, a Retry-After header may also be supplied.

The status codes fall into five general categories:

100-199 Informational.

200-299 Successful.

300-399 Redirection.

400-499 Incomplete.

500-599 Server Error.

4.5.4 Using the Web Application Log

Servlets can also write their actions and their errors to a log file using the

log() method.

Syntax:

public void ServletContext.log(String msg)

public void ServletContext.log(Exception e, String msg)

Page 95: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 82

The first method writes the given message to a servlet log. Generally, this is

an event log file. The second method writes the given message and

exception's stack trace to a servlet log.

Example:

try {

int a = Integer.parseInt(req.getParameter(“Num1”);

int b = Integer.parseInt(req.getParameter(“Num2”);

} catch (NumberFormatException e)

{

log("Incorrect Number : " + e.getMessage());

res.sendError(res.SC._INTERNAL_SERVER_ERROR);

}

Self Assessment Questions

6. Which of the following statement is correct?

a) The response from the server to a HEAD request consists of status

line, content type and the document.

b) The response from the server to a GET request does not contain a

document.

c) The setStatus method defined in the HttpServletRequest class takes

an int as an argument and sets the status of Http response

d) The HttpServletResponse defines constants like SC_NOT_FOUND

that may be used as a parameter to setStatus method.

7. The sendError method defined in the HttpServlet class is equivalent to

invoking the setStatus method with the following parameter. Select the

correct answer.

a) SC_OK

b) SC_MOVED_TEMPORARILY

c) SC_NOT_FOUND

d) SC_INTERNAL_SERVER_ERROR

e) ESC_BAD_REQUEST

8. Which of the following statements are correct about the status of the

Http response. Select the one correct answer.

a) A status of 200 to 299 signifies that the request was successful.

b) Statuses of 300 to 399 are informational messages.

c) A status of 400 to 499 indicates an error in the server.

d) A status of 500 to 599 indicates an error in the client.

Page 96: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 83

4.6 Summary

1. Throwable class

Throwable class is at the top in the hierarchy of Exception.

2. Exception Handling keywords

try, catch, finally, throw and throws.

3. Type of Exceptions.

Checked exceptions must be caught or forwarded. This can be done in a

try ... catch statement or by defining the exception in the method

definition.

Un-checked exception, check for exception while execution. Program

will compile succefully.

4. try…catch…finally dependency

– If no matching catch block is found in the exception chain, the

thread containing the thrown exception is terminated.

– The finally block after a try ... catch statement is executed

regardless whether an exception is caught or not.

– Returning within a finally block breaks the exception chain to the

invoker even for uncaught exceptions.

5. Exception Handling Methods

Various techniques of exception handling- using web.xml,

RequestDispatcher, sendError, application log etc.

4.7 Terminal Questions

1. What are the ways of handling exception? Explain any one in details.

2. Explain Exception Handling using RequestDispatcher.

3. What is an Exception? Explain the keywords used for exception

handling?

4.8 Answers

Self Assessment Questions

1. RuntimeException

2. false

3. true

4. a, b

5. d

Page 97: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 4

Sikkim Manipal University Page No.: 84

Terminal Questions

1. There are various ways of exception handling. They are as follows:

a. Using the web.xml.

b. Using a RequestDispatcher

c. Using sendError() method of HttpServletResponse.

d. Using the Web Application Log

(Refer section 4.5)

2. A RequestDispatcher can be used to receive the requests from the client

and forward the same to any resource such as a Servlet, HTML file, or

JSP file on the server. (Refer section 4.5)

3. Servlet exceptions are abnormal conditions that can occur while

executing a piece of code in a Servlet.

The following five keywords are used for exception handling:

1. try

2. catch

3. throw

4. throws

5. finally

Page 98: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 85

Unit 5 Servlet Session Tracking

Structure:

5.1 Introduction

Objectives

5.2 Sessions – An Introduction

5.3 Servlet API

Session Creation

Putting and getting data from HttpSession

5.4 Session Tracking Techniques

Using Cookies

URL Rewriting

Hidden Form Fields

5.5 Summary

5.6 Terminal Questions

5.7 Answers

5.1 Introduction

The previous unit covered the topic of Exception Handling in server – side

programming. In this unit we are going to discuss the meaning and

relevance of Sessions and their usage with respect to Web applications and

Server side programming. It further discusses about the Servlet API used in

Session tracking and various techniques used to track these sessions.

As you know most of the website uses only HTTP protocol, which does not

maintain the state of user/client. So it very difficult for the server to

recognize which client is using what part of the application.

Example(s):

A shopping cart application

Booking online tickets for a movie.

Online Examinations

Accessing your email account.

In many such examples you are required to keep track of client sessions.

In real life you may see a number of Web sites where you need not track the

user, for example:

Page 99: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 86

Search Engines (google.com, ask.com, khoj.com, etc) where user can

search any kind of information but not required to keep his/her

information.

Websites of News Paper(s), Sports, Food & Nutrition, etc where users

are not required to register.

For keeping track of the user, Java Servlet technology provides an API

for managing sessions and allows several mechanisms for

implementing sessions.

This unit requires an understanding of the basic communication occurring

between the client (for example, a browser interface) and the Web Server

(for example, Apache Tomcat). In order to get an idea of the topic of

Sessions being discussed here, we need to have a complete understanding

of Units 2 and 3 of this SLM. For further information and skill enhancement,

you can visit the Sun‟s official Web Site http://java.sun.com.

Objectives:

After studying this unit, you should be able to:

define Sessions and their applications

describe the usage of Servlet API in Session creation

explain session tracking techniques

5.2 Sessions – An Introduction

Definition:

The following are various definitions of Sessions:

1. Session tracking is a technique that Servlets use to preserve state about

a series of requests from the same user, which originates from the same

browser across some period of time.

2. A session is an uninterrupted series of request-response interactions

between a client and a server (from SCWCD Exam Tool Kit Second

Edition)

The ability of a protocol to remember the user and his/her requests is called

its State.

In a Web environment there are two types of protocols:

1. Stateless:

Example: HTTP protocol.

Page 100: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 87

In a stateless protocol, the container handles every HTTP request as an

individual request. So there is no way of remembering when a series of

requests are coming from a user. This indicates that the container does

not maintain any state information of the user.

2. Stateful:

For example, File Transfer Protocol (FTP) is a stateful protocol. You

don‟t require creating a new connection for every request. These kinds

of protocols maintain states or remember user's credentials throughout

the session.

A session maintains a "virtual connection" between a Web browser and a

Servlet, instead of storing state information in cookies, hidden fields, or URL

rewriting. Sessions continue for a limited period of time if application is ideal

and are associated with a single user.

A session is temporary, and its existence ends when one of the following

occurs:

Browser does not accept cookies.

When a user closes the browser.

When request is ideal and crosses the session time.

When a Servlet calls its invalidate() method.

The following are the techniques for session tracking:

1. Cookies

2. URL Rewriting

3. Hidden Form Fields

Before talking about session tracking techniques, let us first understand the

Servlet API used for sessions.

5.3 Servlet API

Generally you keep two things in session,

1. User data and

2. Session state.

As per Java Servlet Specification, every servlet can access a server-side

session by using its interface, HttpSession. The HttpSession interface

provides various methods for managing sessions between the server and

the client; some of them are shown in Table 5.1 below:

Page 101: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 88

Table 5.1: HttpSession Interface Methods

SNo Method Purpose

1 void setAttribute(String, Object)

This method is used to set objects in session.

2 Object getAttribute(String) These methods are used to return back or to read objects from session. 3 Enumeration

getAttributeNames()

4 void removeAttribute() This method is used to remove objects from session.

5 String getId() This method returns unique session id generated by server.

6 long getCreationTime() This method returns a long value indicating the date and time this session was created.

7 long getLastAccessedTime()

Returns a long value indicating the last time user accessed any resource on this server.

8 int getMaxInactiveInterval()

This method returns the maximum inactive interval (ideal) in seconds for this session respectively

9 void setMaxInactiveInterval (int interval)

This method sets the maximum inactive interval in seconds for this session respectively

10 boolean isNew() This method returns a boolean value indicating if the session is new, meaning that the user has visited for the first time

11 void invalidate() This method invalidates a session. You can use this method on a 'logout' page-allowing user to end his session.

5.3.1 Session Creation

Session object closely depends on HttpSession interface. You can create

session for current user using following statement.

Page 102: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 89

HttpSession session = request.getSession(true);

getSession(boolean) method of javax.servlet.http.HttpServletRequest will

return the current session and assign to the reference of HttpSession i.e.

„session‟. The boolean parameter to this method specifies whether a new

session should be created if one does not already exist or obtain an existing

one. The default parameter value is true.

5.3.2 Putting and getting data from HttpSession

After creating session user can add, retrieve or remove data in the session.

To do these operations you can use setAttribute(), getAttribute(),

getAttributeName(), or removeAttribute() methods.

For example

// Adding data in session

session.setAttribute ("LoginID", request.getParameter("LID"));

// Retrieving session data

session.getAttribute(“LoginID”);

Returns one object data at a time.

// Return the list of objects

Enumeration enames = session.getAttributeNames();

while(enames.hasMoreElements())

{

String n = (String)enames.nextElement();

String v = (String) session.getAttribute(n);

…..

…...

// Code here for manipulation.

}

Complete Example

1. Store following code in StudentInformation.html

<html>

<body>

Page 103: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 90

<form action="/Aug2008/SessionDemo" method="Get">

<h2> Student Information</h2>

<table border="1">

<tr> <th> Enter name </th><td>

<input type = "text" name = ”name"></td></tr>

<tr><th>Enter Cell No</th><td><input type = "text" name = "cell"></td></tr>

<tr><th>Enter City </th><td><input type = "text" name = "city"></td></tr>

<tr><td colspan = "2" align="center">

<input type = "submit" name = "sub" value="Submit">

<input type = "reset" name = "reset" value="Reset"></td></tr>

</table>

</form>

</body>

</html>

2. Store following code in SessionDemo.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class SessionDemo extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws IOException,ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);

//Retrieving parameters from StudentsInformation.html

String Name = request.getParameter("name");

String Cell = request.getParameter("cell");

String City = request.getParameter("city");

//Setting attributes in session

session.setAttribute("Name",Name);

session.setAttribute("Cell",Cell);

session.setAttribute("City",City);

if(session.isNew())

Page 104: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 91

out.println("<h1> You are new user.... Login first</h1>");

else {

RequestDispatcher rd = request.getRequestDispatcher("/DisplayServlet");

rd.forward(request,response);

} out.close();

}

}

3. Store following code in DisplayServlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class DisplayServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws

IOException,ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

HttpSession session = request.getSession(true);

//Retrieving session data

String name = (String)session.getAttribute("Name");

String cell =(String) session.getAttribute("Cell");

String city = (String) session.getAttribute("City");

// You may write following code for retrieving data

/*

Enumeration enames = session.getAttributeNames();

while(enames.hasMoreElements())

{

String n = (String)enames.nextElement();

String v = (String) session.getAttribute(n);

out.println(n + "<br>");

out.println(v + "<br>");

} */

Page 105: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 92

out.println("Your name is : "+ name +"<br>");

out.println("Your cell no is : "+ cell +"<br>");

out.println("Your city name is :"+ city +"<br><br><br>");

out.println("<h1>Session information ....<h1> <br><br>");

out.println("<h4> Session Id </h4>" + session.getId());

out.println("<h4> Session Creation Time </h4>" + new

Date(session.getCreationTime()));

out.println("<h4> Last accessed time </h4>" + new Date(

session.getLastAccessedTime()));

out.close();

}

}

Entering Student‟s information:

Output after entering student‟s information in the session:

Page 106: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 93

Self Assessment Questions

1. The –––––– and –––––– methods are used to read objects of session.

2. If false is passed as parameter in getSession() , then also it will create

new session. (True / False)

3. Browser doesn‟t accept cookies. (True / False)

4. Both FTP and HTTP are stateful protocol. (True / False)

5. Which method would be called when the session becomes invalid?

(Select 1 correct option)

a) sessionInvalidated() of HttpSessionListener

b) sessionDestroyed() of HttpSessionListener

c) valueUnbound() of HttpSessionAttributeListener

d) valueUnbound() of HttpSessionBindingListener

e) valueUnbound() of HttpSessionListener

6. URL Rewriting must be used for sharing state information between client

and server. When the specified URL is encoded, what is included in the

URL that gets written out in the servlet's response output stream?

a) user ID

b) session ID

c) IP address

d) domain name

e) machine name

5.4 Session Tracking Techniques

There are various techniques of session tracking, they are as follows:

1. Using Cookies

2. Using URL-Rewriting

3. Using Hidden Form Fields

5.4.1 Using Cookies

Definition: Cookies are pieces of data that web server adds in the client

browser and later in the web server for tracking.

Cookies are useful for identifying clients as they return to the server.

Whenever the client requests a page, it sends along with the request any

cookies that it was previously asked to associate with that request. Each

cookie has a name and a value. In Cookies enabled browser each server

domain allows to add up to 20 cookies of upto 4k per cookie.

Page 107: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 94

Cookie Creation

To create cookie, first you need to create an instance of Cookie class using

its constructor.

Cookie object-name = new Cookie (String name, String value);

This constructor allows the user to pass cookie data in name/value pair.

After that to add this cookie in the browser you need to call addCookie

(object-name) method of HttpServletResponse.

You can also do the following actions with Cookies:

Adding comments

Setting life of cookie

Setting version

Setting secure channel (i.e. HTTPS or SSL)

Set the domain

For example:

HttpSession session = request.getSession(true); //Creating session

String id = session.getId(); // getting session ID

// Cookie creation and passing session ID

Cookie cookies = new Cookie (“SessionID”, id);

response.addCookie(cookies); // adding cookie in the browser

getId()

This method gives session id, which is unique for every instance of the

browser.

setMaxAge() method

This method specifies the maximum age of cookie.

Setting and Getting Cookie Attributes

Before adding the cookie in the response, you can set or get attributes of

the cookie using following methods:

getComment/setComment

Gets/sets a comment associated with this cookie.

Page 108: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 95

getDomain/setDomain

Usually, cookies are returned only to the hostname, which sent them.

Gets/sets specifies the domain to which cookie applies. You can use this

method to inform the browser to return them to other hosts within the same

domain. The domain must begin with a dot and must contain at least two

dots. A domain matches only one entry beyond the initial dot. For example,

"abc.net" is valid and matches www.abc.net and upload.abc.net but not

www.upload.abc.net.

getMaxAge/setMaxAge

These allows user to set/get maximum time cookies remain in the browser.

If you don't set the cookie will remain only for the current session i.e. till

browser is running.

Syntax:

Cookies.setMaxAge(age);

– If age is positive in seconds specifies life of cookie.

– If age is negative, delete when browser exits

– If age is zero, delete cookie immediately

getName/setName

This method allows specifying names to cookies and getting the same for

tracking the user for next time.

getPath/setPath

This method allows specifying path for cookies. If you don‟t specify, by

default it will send to current requested page and all pages belonging in that

directory where request page is saved.

getSecure/setSecure

This method allows to set/get secured channel like SSL. If you don‟t specify

anything, its value is false by default.

getValue/setValue

This method allows to set or get values of cookies which are set using

setName.

For example:

import java.io.*;

import javax.servlet.http.*;

import javax.servlet.*;

Page 109: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 96

public class CookieDemo extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws IOException,ServletException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String name=null;

String value=null;

Cookie[] cookies = req.getCookies(); //Reading cookies

if(cookies !=null)

for (int i = 0; i < cookies.length; i++)

{

out.println("Cookies from Computer Cookie...");

name = cookies[i].getName();

value = cookies[i].getValue();

out.println(" " + name + " : " + value);

}

else

{

HttpSession sessionid = req.getSession(true);

String si =sessionid.getId();

Cookie c = new Cookie("SESSIONID", si); // creating cookies

c.setMaxAge(30);

res.addCookie(c);

name = c.getName();

value = c.getValue();

out.println("New Cookie generated..");

out.println(" " + name + " : " + value);

}

}

}

How to disable Cookies?

You may disable "cookies" in your browser. Considering the browser and

the operating system used, the process may change.

Page 110: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 97

If you surf with Mozilla: Cookies are located in the menu bar. Click on

block, see or removes cookie(s).

Advantages of Cookies

1. Cookies are stored on the client computer & can be read by the server

after a request for a page is posted. Therefore, no server resource is

involved in maintaining the cookie.

2. The cookies are the best way to customize your navigation on Internet.

3. The best example of cookies is their usage by advertising companies.

They can download a cookie onto your computer to keep track of your

Page 111: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 98

surfing habits and can then tell you about the products that will be in

relevance to your taste.

4. Cookies are non-executable, so they will not spread viruses.

5. Cookies are light weighted, because they are simple text files storing

key-value pairs and consume less memory space.

Disadvantages of Cookies

1. Cookies have a limited size i.e. upto 4 KB(4096 B), So you can‟t store

large amount of data in cookie.

2. Some sites or some malicious hackers can misuse cookies.

3. Because cookies are stored as plain text on to a computer that means

that they can be edited and read by anyone unless and until the site

thinks of your privacy and encrypts the data.

4. Cookies can be stolen via some cross site scripting; the Hacker exploits

a vulnerable Web application and simply applies a JavaScript code to

use your details for his own malicious purposes.

5. If you delete cookies from your hard drive, it will be difficult for servers to

trace your surfing or spending habits.

Self Assessment Questions

7. The ______ allows specifying name to the cookies and getting the same

for tracking the user for next time.

8. Cookies are _______, so they will not spread viruses.

5.4.2 URL Rewriting

URL Rewriting is a method in which the requested URL is modified to

include a session ID. This is another popular session tracking method used

by many developers. URL Rewriting can be one of the best and quickest

ways to improve the usability and maintainability of your site when user

disables cookies from the browser. This method works only with GET

request.

Important point about URL rewriting is that it works if cookies are

unavailable and the response has the URL encoded.

There are 2 methods in the HttpServletResponse for URL rewriting:

1) encodeURL(String url)

The encodeURL() method of the HttpServletResponse interface returns

a URL by including the session ID in it. If the encoding is not required,

Page 112: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 99

the URL is returned unchanged. If cookies are supported by the

browser, the encodeURL() method returns the input URL unchanged

since the session ID will be persisted as a cookie.

2) encodeRedirectURL(String url)

The encodeRedirectURL() method of the HttpServletResponse

interface, returns a URL by including a session ID in it for use in the

sendRedirect() method. If the encoding is not required, the URL is

returned unchanged. If browser supports cookies, the

encodeRedirectURL() method returns the input URL unchanged, since

the session ID will be persisted as a cookie. This method is different

from the encodeURL as this method redirects the request to a different

URL in the same session.

For Example:

1. Save this URLRewritingDemo.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class URLRewritingDemo extends HttpServlet {

//Process the HTTP Get request

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>URL Rewriting Example</title></head>");

out.println("<body>");

HttpSession session = request.getSession(true);

// Encode a URL with the session id.

String url = response.encodeRedirectURL(

http://localhost:8080/June07/validUser?sid= + session.getId());

// Redirect the client to the new URL

Page 113: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 100

response.sendRedirect(url);

out.println("</body></html>");

out.close();

}

}

2. Save this in ValidUser.java

import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class validUser extends HttpServlet {

public void doGet(HttpServletRequest req,HttpServletResponse res) throws

ServletException, IOException

{

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String id = req.getParameter("sid");

out.println("<h3> Welcome in Session Tracking </h3>");

out.println("<h4> Your Session Id is </h4>"+id);

out.close();

}

}

Page 114: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 101

Output

Advantages of URL Re-writing

1. URL Rewriting masks the dynamic URLs with static URLs.

2. Usability.

3. Security: It will make the site more secure as malicious user will not be

able to get to know the structure of the application.

4. Search Engine Visibility.

5. You can avoid Query String and use URL Re-writing to pass on data

among various page calls.

6. It works even if cookies are disabled.

Disadvantages of URL Re-writing

1. Dynamic URLs are hard to read and remember.

2. Dynamic URLs expose the underlying technology, hence are relatively

more prone to attack by hackers.

Session id is appended as

session data in URL

Page 115: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 102

3. Dynamic URLs provide lower level of abstraction and maintainability.

4. Another disadvantage is that some browsers specify a limit on the length

of a URL.

5. URL rewriting acquires more resources.

5.4.3 Hidden Form Fields

This is the simplest and most easy way to implement session tracking. The

hidden fields rely upon a feature of HTML to provide session information.

These are added to an HTML form that is not displayed in the client's

browser. They are sent back to the server when the form that contains them

is submitted.

For example:

<FORM ACTION="/June-07/HiddenFormFieldDemo" METHOD="POST">

...

<INPUT TYPE=hidden NAME="visitor" VALUE="Yash">

<INPUT TYPE=hidden NAME="passno" VALUE="Y-125">

...

</FORM>

In this method you need to pass values, so it is same as defining constants.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class HiddenFormFieldDemo extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse

response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>Hidden Form Field Example</title></head>");

out.println("<body>");

// Create the Form with Hidden Fields

out.println("<FORM ACTION=" +"\"/Sample/HiddenFormFieldDemo\"

METHOD=\"POST\">");

Page 116: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 103

// Putting information in session

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"visitor\"

VALUE=\"Yash\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"passno\" VALUE=\"Y-

125\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\" VALUE=\"Software

& Computing Department\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\"

VALUE=\"Advanced Networking Department\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\" VALUE=\"Gas &

Automobile Department\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\" VALUE=\"BioTech

and Bioinformation Tech Department\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\" VALUE=\"VLSI

Department\">");

out.println("<INPUT TYPE=\"hidden\" NAME=" +"\"dept\"

VALUE=\"Embeded Department\">");

out.println("<INPUT TYPE=\"submit\" VALUE=" +"\"Submit\">");

out.println("</FORM>");

out.println("</body></html>");

out.close();

}

//Posting request

public void doPost(HttpServletRequest request,HttpServletResponse

response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");

out.println("<head><title>Hidden Form Field Example </title></head>");

out.println("<body>");

// Reading hidden field data

String user = request.getParameter("visitor");

String session = request.getParameter("passno");

out.println("<H4>" + user +", various departments from our college

are:</H3><BR>");

Page 117: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 104

String[] deptmnt = request.getParameterValues("dept");

if ( deptmnt != null ) {

for ( int x = 0; x < deptmnt.length; x++ ) {

out.println(deptmnt[x] + "<BR>");

}

}

out.println("</body></html>");

out.close();

}

}

Advantages of Hidden Form Fields

1. Hidden fields have no UI representation, and so cannot be changed by

the browser user.

2. They are easy to implement and are supported by most browsers.

Disadvantages of Hidden Form Fields

1. You must change the HTML you are writing out to include this new

information.

3. Another problem with hidden fields is that they are notoriously easy to

"spoof".

2. It uses only dynamically generated fields.

4. You are not able to click the Back button on your browser without losing

the additional fields added to the current page.

Self Assessment Questions

9. Hidden Form data is visible in browser (True/false)

10. Given this deployment descriptor element for a Web application:

<session-config>

<session-timeout>400</session-timeout>

</session-config>

What is the default session timeout interval for all the sessions

created in this Web application?

a. 400 min

b. 400 sec

c. 400 msec

d. 400 hours

Page 118: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 105

11. Identify the techniques that can be used to implement 'sessions' if the

client browser supports cookies. Select 3 correct options.

a. Using Http headers

b. Using https protocol.

c. Hidden form fields

d. URL rewriting

e. Cookies.

5.5 Summary

This unit has covered the following topics with respect to Session Tracking

in Servlets.

1. Introduction to Sessions: A Session is a technique to manage the

states of both the Server and the Client during the communication

process. It is essential in a sense that both the client and the server

should know each other and able to trace out information regarding the

processes occurring at both sides. This topic discussed the meaning

and definition of Sessions and Session protocols.

2. Servlet API: API is a set of interfaces within the software that allow the

client or server programs to utilize them readily. The API provides a rich

set of coding modules for use in the existing applications reducing the

developmental cost. This topic discussed the importance and

applications of Servlet API in the context of Session tracking.

3. Session Tracking Techniques: There are various session tracking

techniques like usage of cookies, or hidden form fields, which record the

state information and can be utilized by the parties communicating with

each other. This topic described these techniques in detail.

5.6 Terminal Questions

1. What is a Session? What are the various techniques of Session

Managements?

2. What are Cookies? Explain with an example.

3. What are the advantages of URL-Rewriting over Cookies?

Page 119: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 5

Sikkim Manipal University Page No.: 106

5.7 Answers

Self Assessment Questions

1. getAttribute(), getAttributeNames()

2. false

3. false

4. false

5. a

6. b

7. getName or setName

8. non-executable

9. true

10. a

11. e

Terminal Questions

1. Session tracking is a technique that Servlets use to preserve the state

about a series of requests from the same user, which originates from the

same browser across some period of time. (see section 5.2)

There are various types of Session Management Techniques. They are

as follows:

a. Cookies

b. Re-Writing

c. Hidden Form Fields

(Refer Section 5.4)

2. Cookies are pieces of data that web server adds in the client browser

and later the web server for tracking the user uses the same.

(Refer Section 5.4)

3. a. URL-Rewriting takes part in session even browser does not support

Cookies.

b. URL-Rewriting store data at server-side and Cookies at client side.

(For more see section 5.4)

Page 120: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 107

Unit 6 Authentication in Servlets

Structure:

6.1 Introduction

Objectives

6.2 HTTP Basic Authentications

6.3 HTTP Digest Authentications

6.4 Form-Based Authentications

6.5 Client Certificate Authentications

6.6 Summary

6.7 Terminal Questions

6.8 Answers

6.1 Introduction

As you know that Internet has become an information hub, wherein you can

find any kind of information like personal details, social, sports, science &

technology, and so on. These might use important and highly secured

information, so almost every Website may need to maintain high security.

This unit is a walkthrough of Web Security techniques.

Basic Terminology

1. Authorization: Permission or power granted by an authority.

Authorization is equivalent to checking the guest list at an exclusive

party, or checking for your ticket when you are going to travel by Air,

Railway etc.

2. Authentication: The verification of the identity of a person or process.

The most common form of authentication is typing a user name and a

corresponding password that is presumed to be known only to the

individual being authenticated. Other methods of demonstrating identity

can be a smart card, retina scan, voice recognition, or fingerprints etc.

3. Access Control: A much more general way of talking about controlling

access to a Web resource. It is analogous to locking the resources by

setting different attributes like read-only, write or read, Full Control etc.

These three techniques are interdependent on one another. In

particular, authentication and authorization are, in most actual

implementations.

Page 121: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 108

If you have information on your Web site that is sensitive, or intended for

only a specific group of people, the techniques in this unit will help you to

make sure that those pages will be accessible only to authorized users.

Servlets provide the following authentication mechanisms:

BASIC for HTTP Basic Authentication

DIGEST for HTTP Digest Authentication

FORM for FORM-based Authentication

CLIENT-CERT for Client Certificate Authentication

Objectives:

After studying this unit, you should be able to:

define authentication and explain its importance in Web applications

describe various HTTP authentication mechanisms

explain form based and certificate based authentication mechanisms.

6.2 HTTP Basic Authentication

To maintain security in applications, users must be authenticated by server

before gaining entry into the application. HTTP Basic authentication is a

very simple way of authenticating user. In this technique, when a user

makes a request, the browser sends a dialog box asking his username and

password for the server to verify. Authorized user entry is maintained in

“..Tomcat 6.0\conf\tomcat-users.xml” file. This technique uses Base64

algorithm for encoding the password. The Base64-encoded string is

transmitted and decoded by the receiver, resulting in a colon-separated user

name and password string.

Example:

When you start Apache Tomcat, it asks for username and password. This

server uses HTTP Basic authentication for authenticating users.

Following are the steps for implementing HTTP Basic Authentication:

1. Add username and password with their roles in tomcat-users.xml file.

This is available in “\conf” folder of Tomcat installation folder.

2. Create a Servlet class.

3. Deploy this Servlet and provide necessary constraints in Web.xml.

Page 122: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 109

How to add username and password in tomcat-users.xml?

Open the file “tomcat-users.xml”, which is available in “conf” folder of

Tomcat installation folder. This file is called as Realm, where authentication

information is stored. Because Tomcat uses common file for all deployed

applications, it is also called as Memory Realm. This is a vendor specific

file.

for example : \Tomcat 6.0\conf\tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>

<tomcat-users>

<role rolename="Administrator"/>

<role rolename="Guest"/>

<user username="Yash" password="MyPune" roles="Administrator,

Guest"/>

<user username="Sweety" password="IAMSWEETY" roles="Guest"/>

</tomcat-users>

Create a Servlet class

Save following source code in BasicAuthority.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class BasicAuthority extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

{

res.setContentType("text/plain");

PrintWriter out = res.getWriter();

out.println("Wel-come ......!");

out.println("You are authorized by server....");

}

}

Page 123: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 110

Deploying Web Application in Deployment Descriptor (DD)

<?xml version="1.0" encoding="ISO-8859-1"?>

<Web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/Web-app_2_4.xsd" version="2.4">

<servlet>

<servlet-name>secret</servlet-name>

<servlet-class>BasicAuthority</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>secret</servlet-name>

<url-pattern>/BasicAuthority</url-pattern>

</servlet-mapping>

<!- - Security Constraints are defined here -->

<security-constraint>

<Web-resource-collection>

<Web-resource-name>Basic-Authority</Web-resource-name>

<url-pattern>/BasicAuthority</url-pattern>

<url-pattern>/secret</url-pattern>

<http-method>GET</http-method>

<http-method>POST</http-method>

</Web-resource-collection>

<auth-constraint>

<role-name>Administrator</role-name>

</auth-constraint>

Page 124: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 111

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>

http://localhost:8080/Sample/BasicAuthority

</realm-name>

</login-config>

<security-role>

<role-name>Administrator</role-name>

</security-role>

</Web-app>

When you request for an application, the server finds the role defined in DD

and check that with the role defined is “tomcat-users.xml”.

The following <login-config> tag defines which method of authentication is

used (BASIC, FORM, DIGEST or CLIENT-CERT)

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>

http://localhost:8080/Sample/BasicAuthority

</realm-name>

</login-config>

Following line of code gives security constraints to the mentioned URL-

pattern like which HTTP methods are allowed. Here only GET and POST

are allowed. Other methods like, HEAD, PUT, DELETE etc., are not

allowed.

<security-constraint>

<Web-resource-collection>

<Web-resource-name>Basic-Authority</Web-resource-name>

<url-pattern>/BasicAuthority</url-pattern>

<url-pattern>/secret</url-pattern>

<http-method>GET</http-method>

<http-method>POST</http-method>

Page 125: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 112

</Web-resource-collection>

<auth-constraint>

<role-name>Administrator</role-name>

</auth-constraint>

</security-constraint>

In <url-pattern> you can declare different URLs, which represent a single

Web application or multiple Web applications. The <auth-constraint>

specifies abstract roles that should have access to the given URLs. Using

auth constraint with no URLs auth-role-name means no direct access is

allowed.

Running the Application:

1. Start Tomcat server and type the following URL to execute the

BasicAuthority Servlet:

“http://localhost:8080/Sample/BasicAuthority”

2. In the following screen the server asks for Username and Password to

check for Authentication.

Fig. 6.1: Login Screen

Page 126: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 113

3. For unauthorized Username and Password, it shows (in Figure 6.2):

Fig. 6.2: Error in username and password entries

The above Figure 6.2 shows the username as “Sweety”, but access to

the requested resource has been denied because her role is Guest, and

as per Web.xml only “manager” role can access this resource.

4. Since the username “Yash” has been defined as a manager role, he has

permission to access this resource. The Figure 6.3 shows the output of

Servlet for this authorized user.

Fig. 6.3: Correct Username and Password

Page 127: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 114

Fig. 6.4: Welcome Screen

Advantages of HTTP Basic Authentication

1. All popular Web browsers support it.

2. It is very simple and easy to implement.

3. Complex routers or gateways can handle it, as the authentication

information is sent in the HTTP headers.

4. HTTP authentication works well with stateless applications.

Disadvantages of HTTP Basic Authentication

1. This technique uses Base64-encoding algorithm, a two-way algorithm

for encoding passwords, which is not a security measure.

2. All requests and responses are visible to anyone between the

requesting server and the API server.

3. Passwords can easily be decrypted by anyone who intercepts the

request.

4. It doesn‟t provide protection for the information passed back from the

server.

5. You can‟t change the look and feel of authentication dialog box.

6. There is no way for a user to log off without exiting the browser.

7. Usernames and passwords entered into а browser authentication dialog

box are remembered until the browser program is terminated or а new

set of credentials is collected.

8. HTTP does not support multiple realms i.e., HTTP doesn't allow for

multiple Authorization header fields in one request.

Self Assessment Questions

1. Http Basic Authentication uses secured Base64 two-way algorithm.

(True / False)

Page 128: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 115

2. <auto-method> tag of <login-config> is used to define type of method

used for authentication. (True / False)

3. –––––––– code indicates that the resource was not found/available.

4. A URL pattern always begins with –––––––– .

6.3 HTTP Digest Authentications

Digest Authentication is a proposed authentication scheme for HTTP. It is

planned to take over from unencrypted use of the Basic access

authentication, allowing user identity to be established securely without

having to send a password in plaintext over the network. So you can say

this is a direct replacement of Basic Authentication. This technique uses

MD5-base64 algorithm for password encryption. It takes text strings of

arbitrary length and generates a 16-byte checksum. It is designed so that if

you are given only an MD5 checksum, it is extremely difficult to find a block

of text that would result in that checksum. It can be considered a one-way

encryption algorithm.

For example, when the server receives a new request, it looks up the user

name in its password database and gets the user's real password. It then

computes the same three checksums above, using that real password. If the

result is the same as the one the browser sent, then the user either supplied

the correct password, or they got very lucky and found another password

that has the same checksum. Actually, the server should store the result of

the first MD5 checksum in the password database instead of storing the

clear-text password - this saves computation, and, more importantly,

protects the user's password.

The digest authentication standard includes some other features. It allows

for an MD5 checksum of the entire request or response to be included,

enabling the server or browser to detect if their messages have been

tampered with somewhere on the communication network between them. It

also allows the server to specify to which other pages the same

authentication can be applied.

Working of Digest authentication

Digest authentication is a challenge-response mechanism:

The browser sends an HTTP request (e.g. a GET) to a Web server.

Page 129: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 116

The server sees the URL being accessed has been configured to

require Digest authentication and replies with a 401 "Authentication

Required" status plus a "nonce": a unique hash of several data items,

one of which is a secret key known only to the server.

The browser pops up a dialog box requesting username and password.

Once the user enters his/her information, an MD5 hash of the

username, password, nonce and URL are computed and the browser

re-sends the original request along with the hash.

The Web server compares that hash with its own computation of the

same values. If they match, the original HTTP request is allowed to

complete.

Fig. 6.5: Digest Authentication

If both, client side password and sever generated passwords match, the

user gets permission to visit the pages.

Advantages

1. Passwords are never transmitted across the Internet in unencrypted

form.

2. The integrity of the URL data is certified, means, for example, that the

integrity of form information sent using the GET method is certified.

3. Since passwords are never sent over the net, it is very difficult to touch a

user's password.

Page 130: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 117

Disadvantages

1. Yet it is not an all-around security solution, because net searcher can

still see all the text of the request and the response, so it does not

protect the secrecy of the actual data sent or received.

2. For complete security, the HTTP server needs to keep a record of the

nonce values it has sent, and allow each to be used only once. This is

difficult, because it requires a lot of record keeping.

3. Passwords are stored in the server's password database.

Comparison of Digest with Basic Authentication

Both Digest and Basic Authentication are very much on the weak end of the

security strength spectrum. But a comparison between the two points out

the utility, even necessity, of replacing Basic by Digest. The greatest threat

to the type of transactions for which these protocols are used is network

snooping. This kind of transaction might involve, for example, online access

to a database whose use is restricted to paying subscribers. With Basic

authentication an eavesdropper can obtain the password of the user. This

not only permits him to access anything in the database, but, often worse,

will permit access to anything else the user protects with the same

password.

By contrast, with Digest Authentication, the eavesdropper only gets access

to the transaction in question and not to the user's password. The

information gained by the eavesdropper would permit a replay attack, but

only with a request for the same document, and even that may be limited by

the server's choice of nonce.

Self Assessment Questions

5. Which of the following is NOT an authentication method used by a web

container?

a. BASIC

b. DIGEST

c. SSL

d. FORM

Page 131: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 118

6. Consider the web.xml snippet shown in the exhibit.

Now consider the code for a jsp file named unprotected.jsp:

<html>

<body>

<jsp:include page="/MyPack/Valid.jsp" />

</body>

</html>

7. Which of the following statements hold true when Valid.jsp is requested

by an unauthorized user? (Select one correct answer)

<web-app>

...

<security-constraint>

<web-resource-collection>

<web-resource-name>test</web-resource-name>

<url-pattern>/jsp/protected.jsp</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

</auth-constraint>

</security-constraint>

...

</web-app>

a. The user will be prompted to enter user name and password

b. An exception will be thrown]

c. Valid.jsp will be executed but its output will not be included in the

response

d. The call to include will be ignored

e. None of these

6.4 Form-Based Authentication

Form-based authentication is, at its core, a vendor specific, container-

implemented authentication mechanism that allows the look and feel of the

login screen to be customized.

This is a cookie based authentication system where the username and

password is stored in a text file or a database. This is the most widely used

Page 132: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 119

authentication method on Web. The login is performed via a form that must

contain two fields for entering a username and a password, j_username

and j_password, respectively, and a special container-recognized action

j_security_check.

Apart from the login form, two very important elements, the login-config and

security-constraint elements in the Web.xml are used for the application-

specific implementation of form-based authentication.

The login-config element is used to indicate that an application is using

form-based authentication and to specify the locations of the login and

error pages to be used.

The security-constraint element is used to define which resources are

protected and to associate role-based constraints with these protected

resources.

When a user attempts to access a restricted resource, the container checks

the user's authentication. If the user is already authenticated and occupies a

role that is authorized to access the resource, the requested resource is

activated and a reference to it is returned. If the user is not authenticated,

the following series of events occur:

1. The login form is sent to the client and the container stores the original

client request.

2. The client posts the login form back to the server, which then attempts to

authenticate the client.

3. If authentication is successful, the user's roles are compared to the roles

necessary to access the resource. If the user's roles authorize access to

the resource, the client is redirected to the resource using the original

request URL path stored by the container in the first step.

4. If authentication is not successful, the user is redirected to the error

page defined in the login-config element.

Page 133: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 120

Fig. 6.6: Form-Based Authentication

Example:

Form-based authentication requires the following steps:

1. Create a login page.

2. Create an error page that will be displayed if login fails.

3. In the Web.xml (DD), specify form-based authentication and the login

and error pages.

4. You can define users either in tomcat-users.xml or in database file. For

this example consider tomcat-users.xml.

1. Creating Login page say Login.html

<html>

<body>

<table border=”1”>

<form action="j_security_check">

<tr><td>Enter User name </td><td><input type="text"

name="j_username"></td></tr>

<tr><td>Enter Password</td><td><input type="password"

name="j_password"></td></tr>

<tr><td>Login </td><td>Cancel</td></tr>

</table>

</form>

</body>

</html>

Page 134: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 121

In this login for action must be “j_security_check” and username and

password name must be j_username and j_password respectively.

2. Create error page, say Error.html

<html>

<body>

<font size='5' color='red'>

Incorrect username/password. <br><br>

Click <a href="Form.html">here</a>

to re-login

</body>

</form>

</html>

This page will be displayed if username and password are not matching. It

will show hyperlink for going to login page.

3. Deployment Descriptor Web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE Web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web

Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/Web-app_2.2.dtd">

<Web-app>

<servlet>

<servlet-name>secret</servlet-name>

<servlet-class>FormAuthority</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>secret</servlet-name>

<url-pattern>/FormAuthority</url-pattern>

</servlet-mapping>

<security-constraint>

<Web-resource-collection>

<Web-resource-name>A Protected Page</Web-resource-

name>

<url-pattern>/FormAuthority</url-pattern>

<http-method>GET</http-method>

Page 135: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 122

<http-method>POST</http-method>

<http-method>PUT</http-method>

<http-method>DELETE</http-method>

</Web-resource-collection>

<auth-constraint>

<role-name>Administrator</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/Login.html</form-login-page>

<form-error-page>/Error.html</form-error-page>

</form-login-config>

</login-config>

<security-role>

<role-name>Administrator</role-name>

</security-role>

</Web-app>

<login-config> tag is very much important, where you need to specify the

method type, BASIc, FORM, DIGEST etc. This tag is compulsory for Form-

Based Authentication.

Under this tag two more important tags are:

<form-login-page> where you can specify the Login page, in this case

Login.html.

<form-error-page> where you can specify the Error page, in this case

Error.html.

4. For Security role mapping context.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sun-Web-app PUBLIC

"-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN"

"http://www.sun.com/software/appserver/dtds/sun-Web-app_2_5-0.dtd">

<sun-Web-app>

Page 136: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 123

<context-root>/FormAuthority

</context-root>

<security-role-mapping>

<role-name>Administrator</role-name>

<group-name>user</group-name>

</security-role-mapping>

</sun-Web-app>

In this context.xml, you need to specify security role mapping which maps

with role defined in Web.xml.

The following screen shows:

1. Unauthorized user, Sweety has in the role of Guest and only

Administrator has permission to visit the restricted pages.

Fig. 6.7: Entry made by unauthorized user

2. Getting message Access to the requested resource has been denied.

Fig. 6.8: Access Denial Message

Page 137: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 124

3. For authorized user Yash, who is in the role of Administrator gets

permission.

Fig. 6.9: Entry Made by the Authorized user.

4. Executing the Servlet class.

Fig. 6.10: Welcome Message by Server for authorized user

To configure users in using JDBC realm, use following tag of server.xml:

<realmclassname="org.apache.catalina.realm.JDBCRealm" debug="99"

driver="org.gjt.mm.mysql.Driver" connectionurl="jdbc:mysql://localhost/appli

cationusers?user=test;password=test" usertable="users"

usernamecol="user_name" usercredcol="user_pass"

userroletable="user_roles" rolenamecol="role_name"/>

Before execution make sure that you have created database

“applicationusers”. Also you should have created the tables “users” and

“user-roles”. The JAR file containing the JDBC driver referenced by the

„driver‟ attribute is placed in CLASSPATH. You will also need to replace the

user and password values with the appropriate values for your database

Page 138: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 125

installation. This new <realm> entry defines a JDBCRealm that leverages

our database as its container of users.

Advantages of Form – Based Authentication

1. Look and feel of the login page can be customized.

2. Form authentication supports role-based authorization with role lookup

from a database.

3. It makes logout functionality possible.

4. The login page and the error page are supplied by the application. So

the application has control over recovery attempts.

5. The HTTP session holds the security token, not the browser.

6. This is very widely used because of the cost and complexity of using

SSL and the poor user experience of HTTP authentication.

Disadvantages of Form – Based Authentication

1. Like HTTP Basic Authentication, form-based authentication also

transmits user credentials in clear text on the network.

2. It will support for URL-Rewriting session handling.

3. It will not work if browser has cookies disabled.

4. The Container control maintains exclusive rights to the original client

URL request for a protected resource. Generally, this parameter is

neither accessible nor settable in a programmatic manner.

5. In most cases, container precludes the use of custom security filters. As

an example, filters on the j_security_check action prove to be very

unreliable across different application servers.

6. Container-controlled security does not support authentication unless the

client is explicitly attempting to access a protected resource. This feature

is often referred to as lazy authentication. That is, authentication is

performed only when it is needed--not when your application would like

it to be performed.

Self Assessment Questions

7. Which of the following requirements are needed for FORM based

authentication in a web based application?

a. The session attribute j_sessionid must be set.

b. The action or URL must be j_security_check.

c. The name attribute for the username must be j_username

d. The form method must be POST.

Page 139: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 126

e. The name attribute for the password must be j_password.

f. Client side cookie must be enabled.

6.6 Client Certificate Authentication

The CLIENT-CERT authentication method is typically used for identifying

the user by his X.509 certificate. It uses HTTP over Secure Sockets Layer

(SSL) wherein both the server and the user are identified by their own

certificates using public key certificates. This is a digital certificate issued to

an individual customer or to an individual associate of a company.

Certificate info (serial number, version, etc.)

CA Name

Validity Period

Client Name

Public Key / Private Key

Additional Info

Digital Signature of CA

Fig. 6.11: Client Certificate Fields

The Secure Socket Layer (SSL) provides data encryption, server

authentication, message integrity, and optional client authentication for a

TCP/IP connection. It is issued by a trusted organization, which is called a

Certificate Authority (CA). This is a very strong form of authentication.

The certificate resides in the users Internet browser or e-mail software and

contains the user‟s public key, basic identification details and a validity

period. Client certificates are like a passport, designed for universal

identification on the Internet. Sample diagram of Client certificate fields is

shown in Figure 6.11.

Two kinds of certificates are used in HTTPS authentication:

Server Certificates. They contain information about the server that

allows a client to identify the server before sharing sensitive information.

Client Certificates. They contain personal information about the user

and identifies the SSL client (the sender) to the server.

Page 140: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 127

Example of https:

When you are doing on-line shopping, on-line payment etc., your request

will redirect on third party for example, HDFCBank uses

https://www.billdesk.com for online payment deduction.

1. HDFC Bank bill payment

https://www.billdesk.com/pgidsk/pgijsp/instantPay_paymentoption_idea1

.jsp?

2. Airtel payment

https://ebpp.airtelworld.com/pkmslogout? filename=wpslogout.html

Advantages of Client Certificate Authentication

1. Both the server and the client can be sure of whom they are

communicating with.

2. Ensuring that the data is not exposed or disclosed to unauthorized

people.

3. Protection against data being improperly modified or duplicated.

4. Both the request and the response are protected from intermediate

snooping eyes.

Disadvantages of Client Certificate Authentication

1. Every request requires additional back and forth communications to set

up the secure socket.

2. The server must create a unique client certificate for each client that

wishes to access the API. These APIs must be created and stored in a

secure location and transmitted to the client via a secure channel.

Self Assessment Questions

8. What is the authentication type, which uses digital certificates as a

security mechanism for a web based application?

a. BASIC b. Form-Based c. Digest d. Client-Cert

9. What are the following deployment descriptor elements used for?

<login-config> <security-constraint> <security-role>

a. Authorization

b. Authentication

c. Privacy

d. Authentication and Authorization

e. Data integrity.

Page 141: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 128

6.6 Summary

This unit has covered the following topics with respect to Web

authentication:

1. HTTP Basic Authentications: It has dealt with the meaning and

importance of HTTP based Authentication. This topic discussed the

BASIC authentication mechanisms, declaration of authentications and

the Base64 authentication algorithm.

2. HTTP Digest Authentications: This topic described the need for

replacement of HTTP basic authentication with HTTP digest

authentication and the need for doing so. It also discussed the MD5

algorithm for encryption used in this mechanism.

3. Form-Based Authentications: This is a simple authentication

mechanism that allows changing the look and feel of forms used for

authentication. The implementation details of this mechanism have been

discussed in this topic.

4. Client Certificate Authentications: The CLIENT-CERT authentication

method is typically used for identifying the user by his X.509 certificate.

The implementation details of this mechanism have been discussed in

this topic.

6.7 Terminal Questions

1. What is BASIC Authentication? Explain with example.

2. Compare BASIC authentications with HTTP Digest authentications.

3. What are the advantages of Client-Cert authentications?

6.8 Answers

Self Assessment Questions

1. true

2. true

3. 404

4. /

5. c

6. e

7. b,c,d,e

8. d

9. d

Page 142: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 6

Sikkim Manipal University Page No.: 129

Terminal Questions

1. An authentication protocol defined within the HTTP protocol, which

allows user to make request, browser sends a dialog box to ask

username and password and verified by server. In this, user is not

allowed to change the look and feel of the dialog box. User entries are

maintained in web.xml file. (Refer Section 6.2)

2. (Refer Section 6.3)

3. a. Both the server and the client can be sure of whom they are

communicating with.

b. Ensuring that the data is not exposed or disclosed to unauthorized

people. (Refer Section 6.6)

Page 143: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 130

Unit 7 Java Database Connectivity

Structure:

7.1 Introduction

Objectives

7.2 Java Database Connectivity (JDBC) – An introduction

7.3 JDBC Architecture

7.4 Accessing data - Working with Result Sets

7.5 Transaction Control

7.6 Summary

7.7 Terminal Questions

7.8 Answers

7.1 Introduction

The previous units have dealt with two components: the client component

through which the user poses a query to the server and gets back the

response; the server component which generates the content in response to

the user request. In this unit, we are going to deal with connectivity to

various databases with Servlets and processing of the data using a Servlet.

It discusses various techniques to connect to a database, data retrieval and

manipulation and the required objects (like APIs) to deal with.

The Java Database Connectivity (JDBC) API provides interfaces and

classes for developing database applications in Java. JDBC is a part of Java

Standard Edition (Java SE). To use JDBC, you'll need at least JDK 1.1.

Currently Java SE 6 includes JDBC API 4.0 version. JDBC API’s are

available in java.sql and javax.sql packages. Most of web-application uses

JDBC to send SQL, PL/SQL statements to almost any relational database

like, Oracle, MySQL, Sybase, DB2 etc.

JDBC is a Java API for executing SQL statements and supports basic SQL

functionality. It provides RDBMS access by allowing you to embed SQL

inside Java code.

To get an understanding of this unit, you should be familiar with the

concepts of Relational Databases, Operations on Databases, and the tiered

architecture.

Page 144: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 131

Objectives:

After studying this unit, you should be able to:

describe JDBC connectivity

explain how to connect database with Java application.

discuss JDBC API Statements, PreparedStatements, and ResultSets

construct Java applications using JDBC.

perform data definition and data manipulation operations

7.2 Java Database Connectivity (JDBC) – An introduction

Java Database Connectivity is a Java API that enables you to connect any

databases like MySql, Oracle, Sybase, MS-Access, DB2 etc. To use JDBC,

you'll need at least JDK 1.1, a database, and JDBC drivers. As you know

Java runs on most of the platforms, JDBC makes it possible to write a single

database application that can run on different platforms and interact with

different databases.

There are many JDBC drivers available which support almost all popular

databases. You can use a specific driver for specific database, for example:

1. org.gjt.mm.mysql.Driver for MySql

2. oracle.jdbc.driver.OracleDriver for Oracle

For general, Sun has provided a driver which is compatible with ODBC, so

you can to connect to any ODBC compliant databases. It come with JDK, so

if this is installed, no need to install database specific drivers. But for this

you need to create an ODBC data source accessing database in your Java

applications.

7.3 JDBC Architecture

Before making connection check, JDK, JDBC API, Database is installed or

not. JDBC uses a simple hierarchy of API's for database objects as shown

in figure 7.1. These API's are available in the java.sql.* package.

Page 145: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 132

try { Class.forName("org.gjt.mm.mysql.Driver"); } catch(ClassNotFoundException e) { System.err.println("Error loading driver: " + e); }

try { Class.forName("oracle.jdbc.driver.OracleDriver"); }catch(ClassNotFoundException e) { System.err.println ("Error loading driver: " + e); }

Fig. 7.1: JDBC Architecture

As you know, Java is platform independent, which also implies that JDBC is

platform independent. To get portability in applications, JDBC is required.

This is just a specification given by SUN, and implemented by different

vendors. So to connect to a specific database, you require a vendor specific

database driver.

Following are the different steps of making JDBC connection.

Step – 1: Load JDBC Driver.

To load the driver, Class.forName(String) method is used. This method

takes a string representing a fully qualified class name and loads the

corresponding class with respect to database. Here are some examples:

// Connect to MySQL database Server

// Connect to Oracle Database Server

Page 146: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 133

The string taken in the Class.forName() method is the fully qualified class

name specific to database. Free JDBC drivers are available for most of the

databases, but there are many third-party vendors for older databases.

Before loading driver make sure that the driver class is set in the classpath,

otherwise, the forName() method may throw ClassNotFoundException.

Step – 2. Make JDBC Connection

Once a driver is loaded successfully, you can create an instance of the

Connection object. Since the Connection object is an interface, it can't be

instantiated directly. The following example shows one way of creating an

instance of the Connection interface.

Example:

Fig. 7.1: URL Description

The first parameter URL indicates the URL of the database. It includes

the protocol, the vendor, the driver, the database server name, the port

number, and a database name. And the username and password, of you

database.

Second and third parameters are the username and password, which

must be same as you would enter into a database to access your

account.

Step – 3. Process the Query Results

while ( rs.next() ) { // get the type_id, which is an int System.err.println("Type ID = " + rs.getInt("type_id")); // get the type_name, which is a String System.err.println("Type Name = " + rs.getString("type_name")); }

Page 147: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 134

Step – 4. Closing the Connections

JDBC Drivers

JDBC driver is a software component which allows Java program to connect

virtually with any type of databases.

By default the Java Software Development Kit (JSDK), provides JDBC-

ODBC bridge driver, which allows any kind of ODBC databases. But other

than this many vendor specific drivers are available. JDBC enables

maximum interoperability between the application and the database. A

single application can access any JDBC-enabled database.

JDBC drivers are classified into four types as given below:

Type 1: JDBC-ODBC Bridge driver (Bridge)

Type 2: Native-API/partly Java driver (Native)

Type 3: All Java/Net-protocol driver (Middleware)

Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver: JDBC-ODBC Bridge driver

This converts all JDBC calls into Open DataBase Connectivity (ODBC) calls

and forwards them to the ODBC driver. The Java Native Interface (JNI) is

used to call the ODBC functions from the JDBC driver. ODBC is a generic

API. The JDBC-ODBC Bridge driver is recommended only for experimental

use or when no other alternative is available. Before its use you need to

create a DSN Connection.

Fig. 7.3: Type 1-JDBC-ODBC Bridge

Advantages

1. Type 1 driver comes with JSDK, it is not required to install externally.

2. The JDBC-ODBC Bridge allows access to almost any database, since

the database's ODBC drivers are already available.

rs.close(); con.close();

Page 148: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 135

Disadvantages

1. Since it uses JNI (Java Native Interfaces) to call ODBC, Type 1 drivers

are not portable.

2. Every JDBC call goes through the bridge to the ODBC driver, then to the

database, and this applies even in the reverse process. They are the

slowest of all driver types.

3. A Type 1 driver needs to have the bridge driver installed and configured

before JDBC can be used with it. This can be a serious drawback for a

production application.

4. This is not suitable for Web applications.

Type 2 JDBC Driver: Native-API/partly Java driver

As the name stands, these are written partly in the Java programming

language and partly in native code. So these also use a native API to

communicate with a database system. These are database-specific drivers

that convert all JDBC calls into database-specific calls.

Fig. 7.4: Type 2-Native-API/partly Java Driver

Advantages

1. They are good in performance and faster in execution than Type 1.

Disadvantages

1. Native API must be installed in the Client System.

2. Like Type 1 drivers, this also uses Native library, which forms a

portability issue.

3. If we change the Database, we have to change the Native API as it is

specific to a database.

4. Very rarely used.

5. You cannot use a Type 2 driver in an applet since applets cannot load

native code.

Page 149: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 136

Type 3 JDBC Driver: All Java/Net-protocol driver

As the name suggests, it is written purely in Java, but it requires a middle-

tier server (which can be a full fledged Java EE Application server) as it

uses Network Protocol between Java program and the database. This

middle-tier server converts all JDBC calls into vendor specific databases.

Fig. 7.5: Type 3 - All Java/ Net-Protocol Driver

Advantages

1. Since it uses a middle-tier database server, client installation is not

required.

2. It satisfies “Write Once Run Anywhere” concept because it is written in

Java only.

3. It is suitable for the web and faster as compared to Type 1 and Type 2.

4. It gives better performance, and can be scalable with help of middle-tier

database server.

5. This driver is very flexible and it allows access to multiple databases

using one driver.

6. They are the most efficient amongst all driver types.

7. The middle-tier server can provide typical middleware services like

caching (connections, query results, and so on), load balancing, logging,

auditing etc.

Disadvantages

1. It requires another middle-tier server application to install and maintain.

This will add incur additional cost.

2. There is no direct connection with the database, it requires an additional

step, which might affect the speed of application execution.

Page 150: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 137

Type 4 JDBC Driver:Native-protocol/all-Java driver

Type 4 drivers are all Java drivers; means there is no client installation or

configuration. This is pure written in Java. So it’s a portable and mostly used

by Java developers. It uses Java networking libraries to communicate

directly with the database server. There is a direct communication between

application and database. No middleware server is required.

Fig. 7.6: Type 4 - Native-protocol/all-Java driver

Advantages

1. It is installed inside the Java Virtual Machine of the client.

2. It provides better performance over the Type 1 and 2 drivers as it does

not have the overhead of conversion of calls into ODBC or database API

calls

3. It is completely written in Java hence it is platform independent.

4. It is most suitable for the web.

Disadvantages

1. The major disadvantage is that it is database specific driver, requires

separate driver for each database.

Self Assessment Question

1. Which type of driver provides JDBC access via one or more ODBC

drivers?

a) Type 1 driver

b) Type 2 driver

c) Type 3 driver

d) Type 4 driver

JDBC Application Programming Interface (API)

JDBC API has provided many classes and interfaces to interact with

database. Following are some interfaces used to send database queries.

Page 151: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 138

1. Statement Interface

This is a simple and base interface for the PreparedStatement and

CallableStatement. Statement object can be created by calling create

Statement() of Connection interface. Query passed in createStatment() will

be compiled for each and every individual request.

The execute series are the most often used of Statement's methods:

executeQuery() is used to execute SQL statements that return a single

ResultSet.

executeUpdate() is used to execute SQL statements that modify a table

or values of columns in a table and return the number of rows affected

(which is zero in the case of DDL statements).

execute() can be used to execute any type of SQL statement, but is

intended for those that can return multiple results or values.

Example:

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.sql.*;

public class DatabaseDemo extends HttpServlet

{

Connection con = null;

Statement stmt = null;

ResultSet rs = null;

String URL = "jdbc:mysql://localhost/Customer";

String driver ="org.gjt.mm.mysql.Driver";

public void init()

{

try{

Class.forName(driver);

con = DriverManager.getConnection(URL,"root","root");

}catch(Exception e)

{

System.out.println("... no ...Driver could not found.......");

}

}

Page 152: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 139

stmt = con.createStatement(); rs = stmt.executeQuery("Select * from applicant");

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws IOException,ServletException

{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try{

out.println("<table border=1>");

while(rs.next())

{

out.println("<tr><td>Applicant ID :</td><td>"+

rs.getString("appid")+"</td></tr>");

out.println("<tr><td>Applicant Name :</td><td>"+

rs.getString("appname")+"</td></tr>");

out.println("<tr><td>Applicant City :</td><td>"+

rs.getString("appcity")+"</td></tr>");

}

}catch(Exception e)

{

out.println("Record no found...");

}

out.println("</table>");

out.close();

}

}

Only one ResultSet object per Statement object can be open at any point in

time. Therefore, if the reading of one ResultSet object already in used,

execute methods implicitly closes a statement's current ResultSet object.

Page 153: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 140

Table 7.1: Methods available in Statement Interface

Method Description

void addBatch(String) Adds an SQL command to the current batch of commands for this Statement object.

void cancel() Cancels this Statement object if both the DBMS and driver support aborting an SQL statement.

void clear Batch() Makes the set of commands in the current batch empty.

void clear Warnings() Clears all the warnings reported on this Statement object.

void close() Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

boolean execute(String) Executes an SQL statement that may return multiple results.

int[] execute Batch() Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

ResultSet execute Query(String)

Executes an SQL statement that returns a single ResultSet object.

int executeUpdate(String) Executes an SQL INSERT, UPDATE or DELETE statement.

Connection get Connection() Returns the Connection object that produced this Statement object.

int getFetchDirection() Retrieves the direction for fetching rows from database tables that is the default for result sets generated from this Statement object.

int getFetchSize() Retrieves the number of result set rows that is the default fetch size for result sets generated from this Statement object.

int getMaxFieldSize() Returns the maximum number of bytes allowed for any column value.

int getMaxRows() Retrieves the maximum number of rows that a ResultSet object can contain.

Page 154: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 141

boolean getMoreResults() Moves to a Statement object's next result.

int getQueryTimeout() Retrieves the number of seconds the driver will wait for a Statement object to execute.

ResultSet getResultSet() Returns the current result as a ResultSet object.

int getResultSetConcurrency() Retrieves the result set concurrency for ResultSet objects generated by this Statement object.

int getResultSetType() Retrieves the result set type for ResultSet objects generated by this Statement object.

int getUpdateCount() Returns the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned.

SQLWarning getWarnings() Retrieves the first warning reported by calls on this Statement object.

void setCursorName(String) Defines the SQL cursor name that will be used by subsequent Statement object execute methods.

void setEscapeProcessing(boolean)

Sets escape processing on or off.

void setFetchDirection(int) Gives the driver a hint as to the direction in which the rows in a result set will be processed.

void setFetchSize(int) Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.

void setMaxFieldSize(int) Sets the limit for the maximum number of bytes in a column to the given number of bytes.

void setMaxRows(int) Sets the limit for the maximum number of rows that any ResultSet object can contain to the given number.

svoid setQueryTimeout(int) Sets the number of seconds the driver will wait for a Statement object to execute to the given number of seconds.

Page 155: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 142

2. PreparedStatement Interface

A PreparedStatement is a sub-interface of Statement that offers several

benefits:

The contained SQL is sent to the database and compiled before hand

for next execution and compilation is bypassed. So it is also called as

“Pre-compiled statement”.

A PreparedStatement can take IN parameters, as arguments to a

method, for column values.

PreparedStatements deal with data conversions.

Precompiled SQL is useful if the same SQL is to be executed repeatedly, for

example, in a loop. To use Java preparedstatements, you must first create a

object by calling the Connection.prepareStatement() method.

Example:

String id = request.getParameter("id");

String name = request.getParameter("name");

String city =request.getParameter("city");

try{

stmt = con.prepareStatement("insert into applicant values (?,?,?)");

stmt.setString(1,id);

stmt.setString(2,name);

stmt.setString(3,city);

stmt.executeUpdate();

out.println("<h3>Record is updated</h3>");

}catch(Exception e)

{

out.println("Record no found...");

}

out.close();

The question marks are stand-ins for values to be set before executing the

statement called as parameter markers. These are referred to by number,

starting from 1, in left to right order. PreparedStatement's setXXX() methods

are used to set the IN parameters, which remain set until changed.

Page 156: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 143

Table 7.2: Methods of PreparedStatement Interface

void clearParameters() Clears all parameters.

void close() Closes this statement. All result sets that where created by this statement become invalid after calling this method.

boolean Execute()

Executes an arbitrary statement. If another result set exists for this statement, this will be closed (even if this statement fails). If auto commit is on, and the statement is not a select, this statement will be committed.

int[]Execute Batch() Executes the batch.

ResultSet Execute Query()

Executes a query (select statement) and returns the result set. If another result set exists for this statement, this will be closed (even if this statement fails).

int ExecuteUpdate() Executes a statement (insert, update, delete, create, drop, commit, rollback) and returns the update count.

void setByte(int paraInd, byte x) Sets the value of a parameter.

void setBytes(int pararInd, byte[] x) Sets the value of a parameter as a byte array.

void setDate(int paraInd, Date x, Calendar calendar)

Sets the date using a specified time zone.

void setDouble(int paraInd, double x) Sets the value of a parameter.

void setFloat(int paraInd, float x) Sets the value of a parameter.

void setInt(int paraInd, int x) Sets the value of a parameter.

void setLong(int paraInd, long x) Sets the value of a parameter.

void setString(int paraInd, String x) Sets the value of a parameter.

3. CallableStatement Interface

The CallableStatement object is another sub-interface of Statement and

provides call to a database stored procedure from a Java application. A

stored procedure is stored in a database; prepareCall() method of

Connection is used to call this procedure. This call may take one of two

forms:

one form with a result parameter, and

the other without a result parameter.

Page 157: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 144

Both forms may have a variable number of parameters used for input (IN

parameters), output (OUT parameters), or both (INOUT parameters). A

question mark (?) serves as a placeholder for a parameter which could be

IN, OUT, or INOUT parameters depends on the stored procedure

I. The syntax for a procedure that returns a result parameter is:

{? = call procedure_name[(?, ?, ?,?,...)]}

II. The syntax for invoking a stored procedure with no parameter.

i) First create its object by calling prepareCall() method of Connection.

CallableStatement cstmt = con.prepareCall()

ii) Then pass {call procedure_name ()} as a parameter in prepareCall().

{call procedure_name[(?, ?, ?,?...)]}

IN and OUT Parameters

The setXXX() method is used to set the value of IN parameter. To set Float

use setFloat to set int use setInt() and so on.

If the stored procedure returns OUT parameters, then need to following

statement:

the JDBC type of each OUT parameter must be registered before the

CallableStatement object can be executed.

registering the JDBC type is done with the method

registerOutParameter.

Then after the statement has been executed, CallableStatement's

getXXX methods retrieve the parameter value. The correct getXXX

method to use is the Java type that corresponds to the JDBC type

registered for that parameter.

INOUT Parameters

A parameter that supplies input as well as accepts output requires a call to

the appropriate setXXX method in addition to a call to the method

registerOutParameter. The setXXX method sets a parameter's value as an

input parameter, and the method registerOutParameter registers its JDBC

type as an output parameter. The setXXX method provides a Java value

which the driver converts to a JDBC value before sending it to the database.

The JDBC type of this IN value and the JDBC type supplied to the method

registerOutParameter should be the same. Then to retrieve the output

value, a corresponding getXXX method is used.

Page 158: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 145

cstmt = con.prepareCall("{call Calculate_salary(?, ?)}");

cstmt.setInt(1, 5000);

cstmt.setDouble(2, 8500.00);

cstmt.execute();

Self Assessment Questions

2. Which type of Statements can execute parameterized queries?

a) PreparedStatement

b) ParameterizedStatement

c) ParameterizedStatement and CallableStatement

d) All kinds of sub-interfaces of Statements

3. How can you execute a stored procedure in the database?

a) Call method execute() on a CallableStatement object

b) Call method executeProcedure() on a Statement object

c) Call method execute() on a StoredProcedure object

d) Call method run() on a ProcedureCommand object

7.4 Accessing Data - Working with Result Sets

ResultSet is an object used to store the result of executed SQL statement.

These ResultSet object can contain Rows. This ResultSet object is

maintained in cursor, which points to current row of table data. When

ResultSet object is created default cursor position is on before first row, if

ResultSet next method is called cursor set to first row of table data.

ResultSets are of three types:

1. ResultSet objects support 3 types of Scrollabilities: TYPE_FORWARD_

ONLY (default), TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_

SENSITIVE.

2. ResultSet objects support 2 types of update capabilities:

CONCUR_READ_ONLY (default) and CONCUR_UPDATABLE.

3. ResultSet objects support 3 types of fetch direction hints:

FETCH_FORWARD (default), FETCH_REVERSE, and FETCH_

UNKNOWN.

Non - Scrollable ResultSets

When you create Statement object using createStatement() without any

parameter, the ResultSet object that is returned by executeQuery() is a

nonscrollable ResultSet, or one that is of TYPE_FORWARD_ONLY.

Page 159: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 146

The following is the only method that you can use for moving through the

ResultSet object:

public boolean next()

When the executeQuery() method returns the ResultSet, the cursor is

positioned prior to the first row of data

To get to the first row of data, you must call the next() method.

Scrollable ResultSets

When you create Statement object using createStatement(int, int), the first

parameter sets the Scrollability. The scrollability refers to whether you can

move backward through the ResultSet.

The second parameter defines whether you can update the table through

the ResultSet.

For the first parameter, you can pass one of these three arguments:

ResultSet.TYPE_SCROLL_SENSITIVE

ResultSet.TYPE_SCROLL_INSENSITIVE

ResultSet.TYPE_FORWARD_ONLY

If changes occur to the database while you are going through a ResultSet,

TYPE_SCROLL_SENSITIVE see those changes;

TYPE_SCROLL_INSENSITIVE means you will not see the changes.

The TYPE_FORWARD_ONLY creates a non scrollable ResultSet that does

not see updates.

For scrollable ResultSets, the ResultSet class provides the following

methods for navigating through the ResultSet:

boolean next() boolean previous()

boolean first() boolean last()

void beforeFirst() void afterLast()

boolean absolute(int) boolean relative(int)

boolean isFirst() boolean isBeforeFirst()

boolean isLast() boolean isAfterLast()

void moveToInsertRow() void moveToCurrentRow()

int getRow()

Page 160: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 147

Using Updatable ResultSets

The second parameter in the createStatement(int, int) and

createStatement(int, int, int) methods determines whether you can update

the database through the ResultSet object.

To control the updatability of a ResultSet, you pass one of these two

arguments as the second parameter in the createStatement() method call:

ResultSet.CONCUR_READ_ONLY

ResultSet.CONCUR_UPDATABLE

Examples:

1. Forward Processing

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT empno, sal FROM

employee");

rs.afterLast();

while (rs.previous())

{

System.out.println(rs.getString("empno") + " " + rs.getFloat("sal"));

}

2. Backward Processing

Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery("SELECT empno, sal FROM

employee");

rs.afterLast();

while (rs.previous())

{

System.out.println(rs.getString("empno") + " " + rs.getFloat("sal"));

}

3. Update Processing

Statement stmt =

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery("SELECT empno, sal FROM

employee");

Page 161: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 148

if (rs.absolute(5)) // (returns false if row does not exist)

{

rs.updateString(1, "4510");

rs.updateFloat("sal", 25000.0f);

rs.updateRow();

}

ResultSetMetaData

JDBC Meta Data collects data about the data structure and property of a

column available in table. MetaData can answer:

How many columns are in ResultSets?

What is the name of given column?

What is the data type of specific column?

o And many such questions on ResultSets.

Methods of ResultSetMetaData

1. getColumnCount()

Gives you number of column in current ResultSet.

2. getColumnName()

Gives you name of column. You may use getColumnLabel() to get

suggested column name for print.

3. getColumnType()

Gives SQL type for column.

4. isSearchable()

Gives TURE / FALSE if column can be used in WHERE clause of SQL

statements.

5. isReadOnly()

indicates column where column is read-only or not.

6. isWritable()

indicates column is writable or not.

7. getColumnDisplaySize(int col):

gets the normal maximum width in characters for column

Many such methods are available in ResultSetMetaData.

getMetaData() - The ResultSet call getMetadata(), returns the property of

the retrieved ResultSet(length,field,column) and gives them to

ResultSetMetaData.

ResultSetMetaData rsmd = rs.getMetaData();

Page 162: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 149

Example:

import java.sql.*;

import java.servlet.*;

import java.servlet.http.*;

import java.io.*;

public class MetaDataExample {

public void doGet(HttpServletRequest req, HttpServletResponse res)throws

IOException, ServletException

{

res.setContenttype(“html/text”);

PrintWriter out = res.getWriter();

String driver = "org.gjt.mm.mysql.Driver";

String connection = "jdbc:mysql://localhost:/Customer";

String user = "root";

String password = "root";

try {

Class.forName(driver);

Connection con =

DriverManager.getConnection(connection, user, password);

Statement stmt = con.createStatement();

String sql = "select * from employee";

ResultSet rs = stmt.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();

int rcount = rsmd.getColumnCount();

out.println("<h4>Table Name : " + rsmd.getTableName(2) +

“</h4>”);

out.println("Column Name \t Size \tDataType");

for (int i = 1; i <= rcount; i++)

{

out.print(rsmd.getColumnName(i ) + " \t");

out.print(rsmd.getColumnDisplaySize(i) + "\t");

out.println(rsmd.getColumnType(i));

Page 163: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 150

out.println(rsmd.isReadOnly());

out.println(rsmd.isWritable());

}

} catch (Exception e)

{

e.printStackTrace();

}

}

}

Self Assessment Questions

4. What is the meaning of ResultSet.TYPE_SCROLL_INSENSITIVE

a) This means that the ResultSet is insensitive to scrolling

b) This means that the Resultset is sensitive to scrolling, but insensitive

to updates, i.e. not updateable

c) This means that the ResultSet is sensitive to scrolling, but insensitive

to changes made by others

d) The meaning depends on the type of data source, and the type and

version of the driver you use with this data source

5. How can you retrieve information from a ResultSet?

a) By invoking the method getXXX() on the ResultSet.

b) By invoking the method getValue (...), and cast the result to the

desired java type.

c) By invoking the special getter methods on the ResultSet: getString

(...), getBoolean (...)

d) getClob (...),...

7.5 Transaction Control

“A transaction is a group of operations that should be completed as

one unit or as whole.”

Most of the time in Web applications, user wants that some transaction

should show records while another should insert records or update records

or delete records and so on. This parallel transaction processing can done

by JDBC Transactions.

Page 164: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 151

Transaction Properties: ACID

In the abbreviation ACID, A stands for Atomicity, C for Consistency, I for

Isolation, and D for Durability. This property measures transactions.

Atomicity: All the individual operations must succeed till end. If any one in

the group fails, the transaction fails.

Consistency: The database must be updated correctly even any operation

from set either succeeds or fails. The design of a 'transaction' has to be that

the database is updated appropriately.

Isolation: The operations should be executed with any interruption. If any

other process wants to interrupt the task in the transactional set, it has to

wait. This prevents data from being corrupted by two different sources.

Durability: This indicates once a transaction is completed, there must be

guarantee of database updates. The programmer is not responsible for

database not being updated.

Committing Records: setAutoCommit() method

By default Connections are in auto-commit mode.

This means that each SQL statement is treated as a transaction and

will be automatically committed immediately after it is executed.

Committing records in a database can be set or disable using

setAutoCommit() methods of Connection. Default is true.

If setAutoCommit(false) is executed then no SQL statement will be

committed until the method setAutoCommit(true) is executed explicitly.

Handling Transaction Failure: rollback()

If any failure happens in the transaction set, results in Rollback to previous

state. Rollback can be made by calling the Connection's rollback() method.

Rollback is important operation for database integrity. This gives us

consistent database. Rollback transaction can be used with savepoints or

without savepoints. This rolls back the current transaction and restores the

database to the state bit was in before the start of the current transaction.

Failure to commit a transaction before closing the corresponding Connection

object will lead to an automatic rollback of the database updates; all work

will be lost. Developers should be sure that all work is committed to the

database before closing the Connection.

Page 165: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 152

Example:

Import java.servlet.*;

import java.servlet.http.*;

import java.io.*;

import java.sql.*;

public class TransactionDemo extends HttpServlet

{

Connection con = null;

Statement stmt=null;

String driver = "org.gjt.mm.mysql.Driver";

String url = "jdbc:mysql://localhost:/Customer";

String user = "root";

String password = "root";

String query=null;

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws IOException, ServletException

{

res.setContentType(“html/text”);

PrintWriter out = res.getWriter();

try{

Class.forName(driver).newInstance();

con = DriverManager.getConnection(url, username,password);

stmt=con.createStatement();

con.setAutoCommit(false); //Default committing is false

try{

for(int i=1;i<=20;i++)

{

query="insert into emplyee(empno, empname,sal)" +

" values('1234','Shreya','45000.00f')";

stmt.executeUpdate(query);

}

con.commit();

}

Page 166: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 153

catch(Exception e)

{

e.printStackTrace();

con.rollback(); //Rollback is called

}

finally

{

con.setAutoCommit(true); //will be committed even there is

} //exception

}

}

Self Assessment Questions

7. How can you start a database transaction in the database?

a) By asking a Transaction object to your Connection, and calling the

method begin() on it

b) By asking a Transaction object to your Connection, and setting the

autoCommit property of the Transaction to false

c) By calling the method beginTransaction() on the Connection object

d) By setting the autoCommit property of the Connection to false, and

execute a statement in the database

8. What statements are correct about JDBC transactions?

a) A transaction is a set of successfully executed statements in the

database

b) A transaction is finished when commit() or rollback() is called on the

Connection object,

c) A transaction is finished when commit() or rollback() is called on the

Transaction object

d) A transaction is finished when close() is called on the Connection

object.

7.6 Summary

JDBC – An introduction

Java Database Connectivity allows virtually any database to connect with

Java application. There are four JDBC drivers which does this task. This

topic has covered the basic features and architecture of JDBC.

Page 167: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 154

JDBC Architecture

These is standard way of connecting database, sending SQL queries. JDBC

architecture is nothing but the collection of different JDBC API's, JDBC

drivers.

Accessing data - Working with Result Sets

ResultSet contains all retrieved results of SQL queries. You can iterate

ResultSets by various methods. The three types of ResultSets are

discussed.

Transaction Control

Transactions are a set of operations which must follow the principle of all or

none, i.e. either the transaction should be committed in its entirety or in case

of a problem should be immediately rolled back. The setAutoCommit() and

rollback() methods are used to perform these tasks.

7.7 Terminal Questions

1. What is JDBC? Describe different JDBC drivers.

2. Describe the steps needed to establish database connectivity with

JDBC.

3. What are the different types of Resultsets?

4. What is a transaction? Explain the methods setAutoCommit() and

rollback().

7.8 Answers Self Assessment Questions

1. a

2. a

3. c

4. a

5. d

6. d

7. d

8. b, d

Page 168: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 7

Sikkim Manipal University Page No.: 155

Terminal Questions

1. Java DataBase Connectivity (JDBC) is a Java API which enables you to

connect to any database like MySql, Oracle, Sybase, MS-Access, DB2

etc.

(Refer Section 7.2)

2. To make a database connection you need to go through the following

sequence:

i) Load JDBC Driver: Loading the driver can be done by

Class.forName() method. This method takes the driver class of

the respective database in String format.

ii) Open database Connection: You open database connection using

DriverManager.getConnection(URL, Username, Password)

where URL represents path of database, and username and

passwords are string used to open database.

iii) Send queries

iv) Create ResultSet

v) Fetch Data from ResultSet

vi) Close Statement

vii) Close ResultSet

viii) Close Connection (Refer Section 7.3)

3. ResultSets are of three types which are as follows :

i) ResultSet objects support 3 types of Scrollabilities:

TYPE_FORWARD_ONLY (default),

TYPE_SCROLL_INSENSITIVE, and

TYPE_SCROLL_SENSITIVE.

ii) ResultSet objects support 2 types of update capabilities:

CONCUR_READ_ONLY (default) and CONCUR_UPDATABLE.

iii) ResultSet objects support 3 types of fetch direction hints:

FETCH_FORWARD (default), FETCH_REVERSE, and

FETCH_UNKNOWN. (Refer Section 7.4)

4. Transaction are set of operations which must executes all or should be

rollback. The setAutoCommit() and rollback() methods are used to do

these tasks. (Refer Section 7.5)

Page 169: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 156

Unit 8 Introduction to Java Server Pages (JSP) Structure:

8.1 Introduction

Objectives

8.2 Need of JSP

8.3 Working of JSP

8.4 JSP Architectures

8.5 JSP Elements

Declarations

Scriptlets

Expressions

Comments

Page directive

Include directive

8.6 Summary

8.7 Terminal Questions

8.8 Answers

8.1 Introduction

You have already learnt Java Servlet as Server Side Tool having its own

advantages and disadvantages. Because of its disadvantages, JSP comes

into picture. Java Server Pages (JSP) is one of the major components of

Java EE. It is an open source specification developed by Sun Microsystems.

This specification is based on Servlet functionalities. In this unit, these

specifications are discussed in detail.

The main idea behind developing JSP is to separate business logic from

presentation. JSP simplifies the process of development as compared to

Servlet, and creates layers in Web application. It is simple and powerful

scripting language. It is compiled by Web container. Users need not compile

JSP. It can create dynamic contents in web pages to interaction with end

user with the help of JSP form or HTML form. Behind the scenes, JSP

pages are dynamically assembled into Servlets, which are simply Java

classes. This means JSP supports the same modularity, reusability,

platform-independence, and access to Java APIs that Java programming

supports.

Page 170: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 157

JSP pages are textual documents containing HTML, XHTML, or XML

markup with embedded Java code and custom JSP tags. JSP works with

HTTP protocols; requires Web Server for its execution. It is supported by

almost all web servers. For example it can be Tomcat provided by Apache

Software Foundation (ASF). It can also be supported by jRun, jBoss, BEA

Weblogic, or IBM Websphere Application Servers.

Objectives:

After studying this unit, you should be able to:

explain the need for JSP.

explain the working of JSP

describe the architecture of JSP.

describe various JSP elements

8.2 Need of JSP

The main advantage of JSP over Servlets is that JSP separates the

presentation code from the Java Code. Generating HTML in Servlet using

out.println () is time-consuming. Due to integration of the Java code with

HTML, debugging is difficult. By implementing JSP you can make both the

HTML code generation and the Java code generation two separate procees.

To include business logic, you can also use JavaBeans, which could

connect to the EJB's. So there is complete separation between presentation

code and the business logic (JavaBeans/EJB code). The important

advantage of Servlet over JSP is that since JSPs have to be converted to a

Servlet upon their first request to the server and the Servlet code has to be

compiled and loaded into the Servlet Engine. The first response time of a

JSP is slower than a Servlet, but upon subsequent requests the response

times are the same.

JSP follows “Write Once Run Anywhere” feature which allows Java on any

platform that conforms to the Java EE specification. ASP is mostly found on

Microsoft platforms. The simplest mistake in ASP script can cause the

server to crash or hang, thereby bringing down your website.

ASP has to be compiled every time when it runs. Hence there is a need for

JSP over Servlet as well as ASP.

Page 171: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 158

8.3 Working of JSP

JSP is an open source specification developed by Sun Microsystems. This

specification is based on Servlet functionalities. The process execution

describes the working of JSP. Fig 8.1 describes the process execution of

JSP. The following nine points describe these processes.

Fig. 8.1: JSP Process Execution

1. The user makes request for JSP page. The web browser makes the

request via the Internet.

2. This JSP request is then forwarded to the Web server.

3. The Web Server passes (.jsp) file into translation phase where

Servlet/JSP engine translates into Servlet code.

4. If the JSP file has been called the first time, the JSP file is parsed,

otherwise go to step 7.

5. The next step is to generate a special Servlet from the JSP file. All the

HTML required is converted to println statements.

Page 172: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 159

6. The Servlet source code is compiled into a class. This is called Class

loading phase.

7. The Servlet is instantiated, calling the ispInit() and _jspService()

methods. The interface JspPage contains jspInit() and jspDestroy(). The

JSP specification has provided a special interface HttpJspPage for JSP

pages serving HTTP requests and this interface contains _jspService().

This phase is called Execution phase.

8. HTML from the Servlet output is sent via the Internet.

9. HTML results are displayed on the user's web browser.

Example:

The following example, Program HelloJSP.jsp generates the output

“Welcome in JSP”. Above mentioned process is required to develop this

output

1. JSP page HelloJSP.jsp

<%--

Document : HelloJSP

Created on : Aug 21, 2009, 12:24:24 PM

Author : root

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-

8">

<title>JSP Page</title>

</head>

<body>

<%="Welcome in JSP"%>

</body>

</html>

2. Servlet/JSP Engine translates .jsp into Servlet code with .java

extension.

compile-jsps:

Created dir: /root/NetBeansProjects/Book/build/generated/src

Page 173: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 160

Created dir: /root/NetBeansProjects/Book/build/generated/classes

Compiling 1 source file to

/root/NetBeansProjects/Book/build/generated/classes

Starting Tomcat process...

Waiting for Tomcat...

Tomcat server started.

Incrementally deploying http://localhost:8084/Book

Completed incremental distribution of http://localhost:8084/Book

run-deploy:

Browsing: http://localhost:8084/Book/HelloJSP.jsp

run-display-browser:

run:

BUILD SUCCESSFUL (total time: 26 seconds)

4. Above class then compiled and .class will be created.

5. Class loader creates instance of Servlet class

6. Then output in HTML will be generated and same will be sent to

Browser.

JSP Life Cycle Methods

jspInit(), _jspService() and jspDestroy() are called the life cycle methods of

the JSP.

1. Initialization using jspInit() method

jspInit() method is called immediately after the instance was created. It is

called only once during JSP life cycle.

Page 174: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 161

2. _jspService()method

This method is called for every request of this JSP during its life cycle.

So when a request comes to the JSP, _jspService() method is invoked,

the request is processed and the response is generated. Here the actual

business logic is written.

3. jspDestroy() method

This method is used for clean process and is called when JSP is

destroyed by the server. With this call the Servlet serves its purpose and

submits itself to heaven (garbage collection). This is the end of JSP life

cycle.

Self Assessment Questions

1. JSP pages are converted into ––––––––––––––– .

A. Plain Java class

B. Servlet class

C. Servlet interface

D. Servlet

2. What are the JSP life cycle methods?

A. init()

B. service()

C. _jspService()

D. destroy

3. <%= %> is equivalent to out.println() of servlet (True/Fals)

4. Which phase results in the creation of a servlet class corresponding to

the JSP page?

A. Request Phase

B. Service Phase

C. Translation Phase

D. Initialization Phase

E. Transformation Phase

8.4 JSP Architectures

There are two general approaches you can take when developing Web

applications using JSP.

I. Page-centric (Model 1) and

II. Servlet-centric architecture or N-tier architecture (Model 2)

Page 175: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 162

I. Model-1 Architecture (Page-Centric)

Page-centric architecture is the most common and easiest methodology for

developing dynamic Web applications. User can access JSP pages directly,

which means the user request is handled by JSP pages. This is also called

as Model-1 architecture.

As shown in fig 8.2, in model-1 architecture, the user makes request to JSP

page, which is responsible for processing the incoming request and replying

back to the client.

Fig. 8.2: Model-1 Architecture

The JSP contains embedded code and tags to access the Model

JavaBeans. Here also JSP separates presentation from business logic,

because all data access is performed using beans.

The JavaBeans contains logic to connect to the middle tier or directly to the

database using JDBC. The JSP is then rendered as HTML using the data in

the Model JavaBeans and other Helper classes and tags and replies back to

browser as a output.

Disadvantages:

1. Even if there is separation between presentation and business logic, it is

only good for small application.

2. JSP allows Java code which is difficult to maintain, if the application is

extended.

3. Application control is decentralized in Model 1 architecture since the

next page to be displayed is determined by the logic embedded in the

current page.

Page 176: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 163

All this leads us to use Model 2 architecture for designing JSP pages.

II. Model-2 Architecture (Servlet-Centric)

Model-2 architecture is based on Model-View-Controller (MVC) pattern,

which separates business logic from presentation. In MVC business logic is

handled by Controller and presentation is handled by JSP. This is also

called as Servlet centric, because every request is handled or controlled by

Servlet which acts as Controller and is responsible for request processing

and the creation of objects used by the JSP, as well as deciding, depending

on the user's actions, which JSP page to forward the request to. JavaBeans

manages information and notify view when there is update in the

information. It contains only data and functionality that are related by a

Fig. 8.3: Model-2 Architecture

common purpose. So the user can create manageable code and layer in

Web application. The main advantage of this approach is clear separation

between business logic and presentation. other advantages are mentioned

below

Advantages:

1. Creates manageable code and layer architecture in Web application by

separating business logic and presentation.

2. Creates reusable code.

3. Provides scalability.

Self Assessment Questions

5. Which pattern provides the benefit of plug-and-play between the data

presentation and data representation?

A. Singleton

B. Value Object

Page 177: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 164

C. Data Access Object

D. Model View Controller

6. ––––––––––– instructs updates in view of application.

A. Servlet

B. JSP

C. JavaBeans

D. Java class

8.5 JSP Elements

These are the building blocks of JSP. Every JSP contents Scripting

elements. There are three different types of Scripting elements:

1. Declaration

2. Scriptlets

3. Expression

8.5.1 Declaration

This part of scripting allows declaration of variables as well as methods.

This declaration goes in the Servlet class. You may call these variables and

methods as an instance variable and instance methods. So This can be

accessible throughout the class. Declaration generates output, so can be

used to Expressions and Scriptlets. Every tag must end with semicolon ( ; )

In JSP, declaration has two forms.

a) Using JSP tags

b) Using XML tags

a) Using JSP tags

It has form <%! Declaration here… %>. In between this tag you can declare

variables as well as methods.

For example:

<%! String name = “Shreya” ;

public show()

{

return name; } %>

b) Using XML tags

It has form <jsp:declare> decaration here……. </jsp:declare>. In between

this tag you can declare variables as well as methods

Page 178: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 165

Example:

<jsp:declare> String name = “Shreya”

public show()

{

return name; } </jsp:declare>

8.5.2 Scriptlets

Scriptlets allow you to put any valid Java code in it. Here you may declare

variables as well as methods. The code written in Scriptlets goes in service

method of Servlet. These are called local declaration. They have two forms

i) Using Jsp tags

ii) Using XML tags

i) Using JSP Tags

It has form <% scriptle here……… %>. Variables and methods are

accessible with _Jspservice() method only.

For example:

<% int age=18;

public int isEligible()

{

if(age>=18)

return “Candidate is eligible”;

else

return “Candidate is not elible;

}

%>

ii) Using XML tags

It has form <jsp:scriptlet> scriptle here……… </jsp:scriptlet>. Variables and

methods are accessible with Jsp_service() method only.

For example:

<jsp:scriptlet>

int age=18;

public int isEligible()

{

Page 179: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 166

if(age>=18)

return “Candidate is eligible”;

else

return “Candidate is not elible;

}

</jsp:scriptlet>

8.5.3 Expressions

This tag allows user to put any expression which goes in output. This is

alternative to out.println(). Semicolon (; ) is allowed with this tag. It has

form:

i) Using JSP tag

ii) Using XML tag

i) Using JSP Tag

Expression is declared using <%= expression %> tag.

For example:

<%=new java.util.Date() %>

<%= isEligible() %>

<%= show() %>

ii) Using XML Tag

It has form

<jsp:expression> expression </jsp:expression>

For example:

<jsp:expression> new java.util.Date() </jsp:expression>

<jsp:expression> isEligible() </jsp:expression>

<jsp:expression> show() </jsp:expression>

8.5.4 Comments

JSP comments are used for documenting JSP code. You can mark any line

or block of code as a comment. This is executed by Web Container. There

are two types of comments in JSP. Mostly comments are used for

troubleshooting. You can use JSP comments to hide specific pieces of

code.

Page 180: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 167

i) Hidden Comment

This is not visible in the output or in the browser source view. This can be

declared anywhere in JSP page using <%-- comment here --> tag.

ii) Output Comment

This is visible in the output or in the browser source view. These are just

uninterpreted HTML text. It is declared using <%-- comment here -->

Example:

<%--

Document : HelloJSP

Created on : Aug 21, 2009, 12:24:24 PM

Author : root

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>JSP Page</title>

</head>

<body>

<%="Welcome in JSP"%> <!-- Shows output -->

</body>

</html>

8.5.5 Page Directive

The page directive is a another JSP tag that you will use in almost every

JSP source file. The page directive has many attributes, which JSP

container applyiesto the entire JSP page. It is declared in the following way:

<%@ page attributename = attributeValue ,................. %>

For example:

<%@ page import = "java.util.*", contentType = "html/text" %>

In this example, page specifies that container will import all classes and

interfaces of java.util package as well as specifies contentType as simple

Text or HTML. You will learn more about Page directive in the next unit.

Page 181: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 168

8.5.6 Include Directive

The include directive adds the contents of another file in the JSP file, where

the directive is declared. It’s useful for including headers and footers,

copyright information, or anything which is common the application. There

are two ways of including contents. they are:

1. <%@ include file ="path" %>

2. <jsp:include page ="path"/>

Example:

<%--

Document : HelloJSP

Created on : Aug 21, 2009, 12:24:24 PM

Author : root

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>JSP Page</title>

</head>

<body>

<%@ include page = "header.jsp %> <!-- include directive -->

<%="Welcome in JSP"%>

<%@ include page = "footer.jsp" %>

</body>

</html>

You can see the content of the included file by viewing the page source

of the main JSP file while you are running HelloJSP. You will learn more

about Include directive in the next unit.

Page 182: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 169

Self Assessment Questions

7. What is the output of following code?

<%! int i; %>

<%! i = 50; %>

Value of i is: <%= ++i %>

A. Value of i is: 50

B. Value of i is: 51

C. Value of i is: null

D. Compilation fails

8. Which are the scripting elements in JSP?

A. Comment

B. Expression

C. Declaration

D. Page

E. Scriptlets

8.6 Summary

This unit has covered the following topics with respect to basics of Java

Server Pages:

Need of JSP: In Servlet, Presentation and Business logic are combined

together. JSP makes this separate which helps in troubleshooting errors,

creating layers in Web application, designing pages easily and many more

features.

Working of JSP: Execution of JSP under goes various phases, the phases

are request for JSP pages, sending request to web server in Translation

phase where it translates into Servlet source, Web server then compile and

creates class file after it works as like normal Servlet. So JSP ultimately

converted into Servlet class.

JSP Architectures: There are two types of model architecture: Model-1

which page-centric and Model-2 which is based on MVC design pattern.

JSP Elements: Without JSP elements JSP are incomplete, JSP has

provided various kinds of elements for designing Web pages. They are

Declarations, Scriptlets, Expressions, Comments, including directive, page

directive.

Page 183: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 8

Sikkim Manipal University Page No.: 170

8.7 Terminal Questions

1. What are the life cycle methods of JSP?

2. Explain various Scripting elements of JSP.

3. Explain Model-2 architecture of JSP.

8.8 Answers

Self Assessment Questions

1. B

2. C

3. True

4. C

5. D

6. C

7. D

8. B, C, E

Terminal Questions

1. Java Server Pages are ultimately converted into Servlet. Servlet follows

certain life cycle. So in the same way JSP also has life cycle and has

following cycle methods. Web Server will create these methods when

JSP goes into translation phase. Following are the life methods:

A. jspInit()

B. _jspService()

C. jspDestroy()

(Refer Section 8.3)

2. JSP has three scripting elements:

A. Declaration

B. Expression

C. Scriptlets

These are the building blocks of JSP. These tags allow Java code to be

embedded in HTML code.

(Refer Section 8.5)

3. Model-2 architecture is also called as Servlet centric architecture

because Servlet acts as Controller in this architecture. It is based on

Model-View-Controller design pattern. Controller is responsible for

handling request, business logic and response.

(Refer Section 8.3)

Page 184: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 171

Unit 9 JSP Tags

Structure:

9.1 Introduction

Objectives

9.2 The Role of Tag Libraries

9.3 Developing a Simple Custom Tag

Using a Simple Tag

The Tag Library Descriptor (TLD)

Custom Java Tags

Support Classes for Custom Tags

The Custom Tag lifecycle

9.4 Tags with Attributes

9.5 Tags that Define Script Variables

9.6 Iterative Tags

9.7 Co-operating Tags

9.8 Validating Attributes

9.9 Processing Tag Bodies

9.10 JavaServer Pages Standard Tag Library (JSPTL)

9.11 Summary

9.12 Terminal Questions

9.13 Answers

9.1 Introduction

In the previous units, you have learned about J2EE Web applications written

using servlets and JSPs. You have seen how servlets are most useful when

complex Java programming is needed and JSPs are easier to use when the

generated Web page requires large amounts of HTML (or JavaScript).

However, JSPs are essentially static in nature and require the developer to

write .Java code, in the form of scriptlets to support complex features.

In this unit, you are going to study about JSP tags, and their extensions

known as JSP Tag Libraries (TagLibs). How to write and deploy simple

custom tags using J2EE RI, use attributes to extend JSP pages, write co-

operating tags to support more complex functionality, such as iteration and

use the JSP Standard Tag Library (JSPTL) are also discussed in this unit.

Page 185: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 172

Objectives:

After studying this unit, you should be able to:

explain the role of JSP tags

describe the types of tags and their attributes

develop a simple custom tag

9.2 The Role of Tag Libraries

JSPs enable you to develop Web-based applications using Java, without

being a Java expert. By using well designed JavaBeans, it is possible to

work almost entirely with HTML and JSP tags. Tag Libraries extend the JSP

philosophy further so that it is possible for you to write most of your Web

pages without using Java code.

This can be utilized to good effect in development teams. By separating out

the Java code into custom tags, a development team can utilize its

individual skills more effectively. Java programmers are used to develop the

business logic in custom tags, while HTML/JSP developers can focus on

developing the presentation logic and look-and-feel of the Web pages.

Tag Libraries support custom JSP tags that can,

• Be customized by using attributes passed from the calling page

• Access the objects available to JSP pages

• Communicate with each other

• Be used in a hierarchical manner to support complex features, such as

Iteration.

Most Web servers supporting JSP now include some standard Tag

Libraries. However, these Tag Libraries are proprietary to each Web server,

leading to Web applications that can only be deployed on a specific

manufacturer’s server. In 2001, the Java Community Process (JCP)

proposed a JSP Standard Tag Library (JSPTL).

9.3 Developing a Simple Custom Tag

A custom tag is made up of two components:

A Java class file that implements the tag

An entry in a Tag Library Descriptor (TLD) file that defines the tag’s

name, its implementing Java class, and additional information necessary

to deploy and use the tag.

Page 186: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 173

Using a custom tag requires a reference to the Tag Library Descriptor (TLD)

at the start of the JSP. Multiple Tag Libraries can be used on the same Web

page. After the TLD has been referenced, the custom tag from the TLD can

be used like any other JSP tag.

9.3.1 Using a Simple Tag

To start learning to write and use TagLibs, you will implement a very simple

custom tag that writes ―Hello World‖ onto your Web page. This isn’t a good

use of a custom tag, but it will help you understand the principles involved,

and guide you through the deployment process.

The example shows a simple tag that inserts ―Hello World‖ on the JSP

Page.

Full Text of hello.jsp

1: <%@ taglib uri=‖/demo‖ prefix=‖demo‖ %>

2: <HTML>

3: <HEAD>

4: <TITLE>Tag Library Hello Demo</TITLE>

5: <BODY>

6: <demo:hello/>

7: </BODY>

8: </HTML>

9.3.2 The Tag Library Descriptor (TLD)

TLD files map the tag name used in the JSP page onto the Java class that

implements the tag. A TLD file is written in XML and an example is given,

which shows the TLD file for the ―Hello World‖ tag.

Full Text of demo.tld

1: <?xml version=‖1.0‖ encoding=‖ISO-8859-1‖ ?>

2: <!DOCTYPE taglib PUBLIC

3: ―-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN‖

4: ―http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd‖>

5: <taglib>

6: <tlib-version>1.0</tlib-version>

7: <jsp-version>1.2</jsp-version>

8: <short-name>demo</short-name>

9: <tag>

10: <name>hello</name>

Page 187: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 174

11: <tag-class>demo.HelloTag</tag-class>

12: <body-content>empty</body-content>

13: </tag>

14: </taglib>

Table 9.1: Tag Body Contents

Tag Description

empty The tag body must be empty. The page translation will fail if the developer puts any text between the start and end tags.

JSP The tag contains JSP data and will normally be processed in the same manner as other parts of the page.

tagdependent The text between the start and end tags will be processed by

the Java class and will not be interpreted as JSP tagged content.

9.3.3 Custom Java Tags

A custom tag requires a reference to Tag Library Descriptor TLD the at the

start of the JSP. You define custom tags by using Java classes that

implement one of the javax.servlet.jsp.tagext interfaces shown in Table 9.2

Table 9.2: Interfaces for custom tags

Java Interface Description

Tag Implement this interface for simple tags that do not need to process the tag body

IterationTag Implement this interface for tags that need to process the body text more than once to implement an iterative loop.

Implementing these interfaces requires that you define several methods to

manage the lifecycle of the custom tag. To simplify custom tag

development, two support classes are provided in the

javax.servlet.jsp.tagext package. These classes provide default behavior for

each of the required interface methods.

Page 188: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 175

9.3.4 Support Classes for Custom Tags

Table 9.3: Support Classes for Custom Tags

java Class Description

TagSupport implements Tag Extend this class for tags that do not have a body or do not interact with the tag body.

BodyTagSupport implements Tag,

Extend this class when the tag body must be processed

IterationTag, BodyTag As part of the tag, such as an iterative tag or a tag that interprets the body in some way.

The Tag, TagIteration, and TagSupport interfaces in the

javax.servlet.jsp.tagext package define several methods that control the

processing of the custom tag.

9.3.5 The Custom Tag lifecycle.

Fig. 9.1: custom Tag Life Cycle

Page 189: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 176

The doStartTag () Method

The doStartTag () method is called once when the start tag is processed.

This method must return an int value that tells the JSP how to process the

tag body. The returned value must be one of the following:

• Tag.SKIP_BODY The tag body must be ignored. The TLD should define

the <body-content> tag as empty.

• Tag.EVAL_BODY_INCLUDE The body tag must be evaluated and

included in the JSP page.

The TLD should define the <body-content> tag as JSP for tags that extend

Tag Support, or JSP or tagdependent for tags that extend BodyTagSupport.

The doEndTag () Method

The doEndTag () method is called once when the end tag is processed. This

method must return an int value indicating how the remainder of the JSP

page should be processed:

• Tag.EVAL_PAGE Evaluate the rest of the page.

• Tag.SKIP_PAGE Stop processing the page after this tag.

Where a tag has an empty body, the doEndTag () method is still called after

the doStartTag () method.

The release () Method

The release() method is called once when the JSP has finished using the

tag and is used to allow the tag to release any resources it may have

acquired. This method’s return type is void.

The doAfterBody () Method

The doAfterBody () method is called after the tag body has been processed

and before the doEndTag () method is called. This method is only called for

classes that implement Iteration Tag or Body Tag (those that extend

BodyTagSupport). It must return one of the following values to the JSP page

indicating how the tag body should be processed:

• IterationTag.EVAL_BODY_AGAIN This value is used to inform the page

that the tag body should be processed once more. The JSP processing

will read and process the tag body and call the doAfterBody() method

once more after the body has been processed again.

Page 190: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 177

Self Assessment Questions

1. Tag Libraries extend the JSP philosophy further so that it is possible for

you to write most of your Web pages without using Java code.

(True/False).

2. A custom tag requires a reference to the ___________ at the start of the

JSP.

3. The _______ method is called once when the end tag is processed

9.4 Tags with Attributes

Table 9.4: TLD Tags for Defining Attributes

Attributes are used to pass information into a custom tag to configure the

behavior of the tag. Tag attributes are like XML or HTML attributes and are

name/value pairs of data. The values must be quoted with single or double

quotes.

The JSP specification allows attributes to have values that can include Java

expressions. If the lookup name had been passed in as a request parameter

called agencyJNDIname,the lookup tag could have been written as follows:

<demo: lookup name=‖<%=request.getParameter

(―agencyJNDIname‖)%>‖/>

Tag Description

Attribute Introduces an attribute definition in the <tag> component of the TLD.

Name Defines the attribute name.

Required Followed by true if the attribute must be provided; otherwise, false.

Rtexprvalue Defines whether the attribute can be specified with a request time expression. Set this element to true to allow JSP scripting values to be used for the attribute; otherwise, the value must be a string literal.

Type Defines the type of an attribute and defaults to java.lang.String. This element must be defined if the rtexprvalue is true and the attribute value is not a String.

Page 191: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 178

Java expressions like this are referred to as request time expressions. Tag

attributes can be defined to disallow request time expressions, in which

case, the value must be a simplestring.

The TLD description for the tag must define any attributes it uses. Each

supported attribute name must be listed together with details of the attribute.

Every attribute must have an <attribute> tag with the sub-components

shown in the table.

9.5 Tags that Define Script Variables

A scripting variable can be added to the page context using the setAttribute

() method of the instance variable called pageContext that points to the

Javax.servlet.jsp.PageContext object of the Web page. The setAttribute ()

method takes the following parameters:

• The name of the scripting variable. This name is used to refer to the

variable on the Web page.

• The object reference to the variable to be added to the page.

• The scope of the variable that can be one of the following constants

defined in PageContext:

APPLICATION_SCOPE Available until the context is reclaimed

PAGE_SCOPE Available until the current page processing completes

(this is the default)

REQUEST_SCOPE Available until the current request completes

allowing the variable to be used by other pages should this page forward

the HTTP request

SESSION_SCOPE Available to all pages in the current session

Page 192: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 179

Table 9.5: TLD Tags for Defining Variables

9.6 Iterative Tags

One of the problems with processing dynamic data is that HTML and JSP

tags do not support repetitive data very well. There is no way of defining the

layout of one row of data and asking for this to be applied to all subsequent

rows; each row has to be defined explicitly in the page.

Iterative custom tags interact with the processing of the start and end tags to

ask for the tag body to be processed again, and again, and again….

An iterative tag must implement the IterationTag interface. This is most

commonly achieved by sub-classing the BodyTagSupport class. The

doAfterBody() method must return IterationTag.EVAL_BODY_AGAIN to

process the body again or Tag.SKIP_BODY to stop the iteration. Typically,

the doAfterBody() method will change the data for each iteration loop.

The iteration tag has complete control over the body content of the page

because it can return values from the page interaction methods, such as

doAfterBody() and then tell the JSP processor how to continue processing

the page.

The default behavior for the BodyTagSupport class is to buffer up the body

text of the custom tag and discard it when the end tag is processed. You will

Tag Description

name-given Defines the name for the scripting variable as a fixed value (cannot be specified if name-from-Attribute is defined)

name-from-attribute Specifies the attribute that is used to define the scripting variable name (cannot be specified if name-given is defined)

variable-class Specifies the class of the scripting variable

declare Specifies if the variable is a new object (defaults to true)

scope Defines the scope of the variable—must be one of NESTED, AT_BEGIN, or AT_END and refer to where in the Web page the variable can be accessed

Page 193: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 180

have to override this behavior in your custom tag so that it outputs the body

text either every time round the iteration loop or once at the end of the tag.

The BodyTagSupport class stores the body content in a BodyTagSupport

class instance variable called bodyContent (class javax.servlet.jsp.tagext.

BodyContent). The BodyContent class extends the JSPWriter class.

The following code illustrates the normal approach to writing the buffered

body content to the Web page:

JspWriter out = getPreviousOut();

out.print(bodyContent.getString());

bodyContent.clearBody();

9.7 Co-operating Tags

Cooperating tags are those that share information in some way. JSP

information can be shared using the following mechanisms:

• Scripting variables

• Hierarchical (or nested) tags

Using Shared Scripting Variables

One means of writing cooperating tags is to use scripting variables to pass

information between the tags. A tag can create a scripting variable that can

be retrieved by another tag on the current page.

Depending on the scope of the scripting variable, it can be passed on to

other pages in the same request or to pages in subsequent requests.

Variables defined by custom tags have the same scoping rules as other

variables defined on the page. Scripting variables are a very flexible means

of passing information between tags.

A tag can retrieve a scripting variable from the page context using the

getAttribute() method. This method takes the name of the variable as its

parameter. An overloaded version of the getAttribute() method takes a

second parameter that defines the scope of the variable to retrieve. The tag

needs to know the class of the variable it is retrieving.

Page 194: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 181

Hierarchical Tag Structures

An alternative means of passing information between tags is to use a

parent/child (or hierarchical) relationship. The parent (outer tag) contains

information that is accessed by a child (inner) tag.

The parent tag is often an iterative tag, and the child is used to retrieve

information for each iteration. The advantage of this approach over scripting

variables is that the information can only be used in the correct context. The

scope of the information can be constrained to the Web page between the

start and end tags of the parent tag.

Two static methods are provided in the javax.servlet.jsp.tagext.TagSupport

class for finding a parent tag from within the child:

TagSupport.findAncestorWithClass(from, class) This method searches

through the tag hierarchy until it finds a tag with the same class as the

second parameter. The first parameter defines the start point of the

search and is typically the this object.

TagSupport.getParent() This method finds the immediately enclosing

parent tag.

Self Assessment Questions

4. Tag attributes are like _____ attributes and are name/value pairs of

data.

5. __________ interact with the processing of the start and end tags to ask

for the tag body to be processed again.

6. An alternative means of passing information between tags is to use a

________ relationship.

9.8 Validating Attributes

The JSP is translated into a Java servlet that is then compiled. After the

compiled servlet is available, it is used to process the client’s HTTP request.

The process of translating the JSP text and compiling the servlet can fail.

Common errors for the failure are as follows:

JSP syntax errors

Compilation errors in embedded Java scriptlets

Incorrectly specifying tag attributes

Page 195: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 182

The first of these errors can be reduced by using JSP, HTML, and XML

syntax-aware editors.

The second problem is reduced when custom tags are used to encapsulate

Java code, enabling Java compilation errors to be detected and corrected

as the tag is developed.

Solving the third problem of misusing attributes for a custom tag is

addressed by defining a Tag Extra Info class to validate your attributes. You

would do this if you had specific rules about which attributes could be

defined or the value an attribute could have.

9.9 Processing Tag Bodies

So far, you have seen tags that treat the text in the body of the tag as simple

JSP (or HTML) data. But tags can also manipulate the tag body in any way

they choose. A simple example would be a tag that interprets its body as an

SQL statement and uses this to query the database.example given shows

simple use of such a tag.

Full Text of select.jsp

1: <%@ taglib uri=‖/demo‖ prefix=‖demo‖ %>

2: <HTML>

3: <HEAD>

4: <TITLE> Tag Library SQL Query Demo</TITLE>

5: <BODY>

6: <demo:select>

7: SELECT * FROM Customer

8: </demo:select>

9: </BODY>

10: </HTML>

9.10 JavaServer Pages Standard Tag Library (JSPTL)

The JavaServer Pages Standard Tag Library (JSPTL) is Java Community

Process initiative. Tag Libraries are a recent addition to JSP and have been

quickly adopted by the development community. As with all new

technologies, Tag Libraries are rapidly developing and changing.

Page 196: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 183

It is easy to write generic tags that provide useful functionality, such as

iteration. Many Tag Libraries are provided with JSP compliant. Web servers

include their own custom tags, many of which are generic tags.

The proliferation of different Tag Libraries providing similar features has

been seen as a problem, and the Java Community Process (JCP) is working

on a standard set of tags to be included in the JSP standard. The

JavaServer Pages Standard Tag Library (JSPTL) is Java Community

Process initiative and is specified on the JCP Web page at

http://jcp.org/jsr/detail/052.jsp.

The Jakarta project also provides a large number of other tag libraries

addressing common page requirements, such as support for JNDI, JMS,

and JDBC.

Self Assessment Questions

7. The problem of misusing attributes for a custom tag is addressed by

defining a ________ class to validate your attributes.

8. The Java Server Pages Standard Tag Library (JSPTL) is Java

Community Process initiative. (TRUE or FALSE)

9.11 Summary

This unit has covered the following topics with respect to JSP tags

Role of tag libraries: JSP Tag Libraries (TagLibs) are a natural extension

to the JSP tag syntax.

Developing simple custom tags: TagLibs are custom tags that are written

in Java but interact with the processing of the tags on the JSP page. Tag

Libraries support custom JSP tags that can be customized by using

attributes passed from the calling page. A custom tag requires a reference

to Tag Library Descriptor TLD at the start of the JSP.

Tags with attributes: Tag attributes are like XML or HTML attributes and

are name/value pairs of data. The values must be quoted with single or

double quotes.

Tags that define script variable: A scripting variable can be added to the

page context using the setAttribute () method of the instance variable called

pageContext that points to the Javax.servlet.jsp

Page 197: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 184

Iterative tags: Iterative custom tags interact with the processing of the start

and end tags to ask for the tag body to be processed again.

Cooperating tags: Cooperating tags are those that share information in

some way.

Validating arrtibutes: The process of translating the JSP text and

compiling the servlet can fail. Common errors for the failure are as follows:

JSP syntax errors

Compilation errors in embedded Java scriptlets

Incorrectly specifying tag attributes

Processing Tag bodies: A simple tag can be used in the program that

interprets its body as an SQL statement and uses this to query the

database.

JavaServer Pages Standard Tag Library (JSPTL): The JavaServer Pages

Standard Tag Library (JSPTL) is Java Community Process initiative

9.12 Terminal Questions

1. Explain the methods in the custom tag Life cycle.

2. What are attributes? Explain tags with attributes.

3. What is the common errors in the process of translating the JSP?

4. What are hierarchical tag structures? Explain.

9.13 Answers

Self Assessment Questions

1. TRUE

2. Tag Library Descriptor (TLD)

3. doEndTag ()

4. XML or HTML

5. Iterative custom tags

6. Parent/Child or Hierarchical .

7. Tag Extra Info

8. TRUE

Page 198: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 9

Sikkim Manipal University Page No.: 185

Terminal Questions

1. The following are the methods in custom tag life cycle :

The doStartTag () Method

The doEndTag () Method

The release () Method

The doAfterBody () Method (Refer section 9.3.5)

2. Attributes are used to pass information into a custom tag to configure

the behavior of the tag. Tag attributes are like XML or HTML attributes

and are name/value pairs of data. The values must be quoted with

single or double quotes. (Refer section 9.4)

3. Common errors are,

JSP syntax errors

Compilation errors in embedded Java scriptlets

Incorrectly specifying tag attributes

4. Hierarchical tags structure are used as an alternative means of passing

information between tags that use a parent/child relationship. The

parent (outer tag) contains information that is accessed by a child (inner)

tag. (Refer section 9.7)

Page 199: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 186

Unit 10 JSP 2.0 Expression Language – I

Structure:

10.1 Introduction

Objectives

10.2 Motivating Expression Language (EL) Usage

10.3 Invoking the EL

10.4 Preventing EL Evaluation

10.5 Preventing Use of Standard Scripting Elements

10.6 Accessing Scoped Variables

10.7 Summary

10.8 Terminal Questions

10.9 Answers

10.1 Introduction

JSP 2.0 introduced a shorthand language for evaluating and outputting the

values of Java objects that are stored in standard locations. This expression

language (EL) is one of the two most important new features of JSP 2.0; the

other is the ability to define custom tags with JSP syntax instead of Java

syntax. The previous unit discussed about the JSP Tags and corresponding

libraries.

This unit discusses the Expression Language and its features.

Objectives:

After studying this unit, you should be able to:

explain the motivation behind the usage of Expression Language

describe the procedure of invoking the Expression Language

illustrate the methods of preventing the EL Evaluation

illustrate the methods of preventing the use of Standard Scripting

elements

describe the process of accessing scoped variables.

Warning: The JSP expression language cannot be used in servers that support only JSP 1.2 or earlier.

Page 200: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 187

10.2 Motivating Expression Language (EL) Usage

As illustrated in Figure 10.1, there are a number of different strategies that

JSP pages can use to invoke Java code. One of the best and most flexible

options is the MVC approach. In that approach, a Servlet responds to the

request; invokes the appropriate business logic or data access code; places

the resultant data in beans; stores the beans in the request, session, or

servlet context; and forwards the request to a JSP page to present the result.

Complex application or

large development team.

Simple application or

small development team.

• Call Java code directly. Place all Java code in

JSP page. Appropriate only for very small

amounts of code.

• Call Java code indirectly. Develop separate

utility classes. Insert into JSP page only the

Java code needed to invoke the utility classes.

• Use beans. Develop separate utility classes

structured as beans. Use jsp:useBean, jsp:get

Property, and jsp:setProperty to invoke the

code.

• Use the MVC architecture. Have a Servlet

respond to original request, look up data, and

store results in beans. Forward to a JSP page to

present results. JSP page uses beans.

• Use the JSP expression language. Use

shorthand syntax to access and output object

properties. Usually used in conjunction with

beans and MVC.

• Use custom tags. Develop tag handler classes.

Invoke the tag handlers with XML-like custom

tags

Fig. 10.1: Strategies for invoking dynamic code from JSP.

The one inconvenient part about this approach is the final step: presenting

the results in the JSP page. You normally use jsp:useBean and

jsp:getProperty, but these elements are a bit verbose and clumsy.

Furthermore, jsp:getProperty only supports access to simple bean

properties; if the property is a collection or another bean, accessing the

Page 201: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 188

“subproperties” requires you to use complex Java syntax (precisely the thing

you are often trying to avoid when using the MVC approach).

The JSP 2.0 expression language lets you simplify the presentation layer by

replacing hard-to-maintain Java scripting elements or clumsy jsp:useBean

and jsp:getProperty elements with short and readable entries of the

following form.

${expression}

In particular, the expression language supports the following capabilities:

Concise access to stored objects: To output a “scoped variable” (object

stored with setAttribute in the PageContext, HttpServletRequest,

HttpSession, or ServletContext) named saleItem, you use ${saleItem}.

Shorthand notation for Bean properties: To output the companyName

property (i.e., result of the getCompanyName method) of a scoped variable

named company, you use ${company.companyName}. To access the

firstName property of the president property of a scoped variable named

company, you use ${company.president.firstName}.

Simple access to Collection elements: To access an element of an array,

List, or Map, you use ${variable[indexOrKey]}. Provided that the index or

key is in a form that is legal for Java variable names, the dot notation for

beans is interchangeable with the bracket notation for collections.

Succinct access to request parameters, cookies, and other request

data: To access the standard types of request data, you can use one of

several pre-defined implicit objects.

A small but useful set of simple operators: To manipulate objects within

EL expressions, you can use any of several arithmetic, relational, logical, or

empty-testing operators. Conditional output. To choose among output

options, you do not have to resort to Java scripting elements. Instead, you

can use ${test? option1 : option2}.

Automatic type conversion: The expression language removes the need

for most typecasts and for much of the code that parses strings as numbers.

Empty values instead of error messages: In most cases, missing values

or NullPointerExceptions result in empty strings, not thrown exceptions.

Page 202: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 189

10.3 Invoking the EL

In JSP 2.0, you invoke the expression language with elements of the

following form.

${expression}

These EL elements can appear in ordinary text or in JSP tag attributes,

provided that those attributes permit regular JSP expressions. For example:

When you use the expression language in tag attributes, you can use

multiple expressions (possibly intermixed with static text) and the results are

coerced to strings and concatenated.

Example:

When you use the expression language in tag attributes, you can use

multiple expressions (possibly intermixed with static text) and the results are

coerced to strings and concatenated.

Example:

<jsp:include page="${expr1}blah${expr2}" />

Escaping Special Characters

If you want ${ to appear in the page output, use \${ in the JSP page. If you

want to use a single or double quote within an EL expression, use \' and \",

respectively.

Self Assessment Questions

1. The _______ only supports access to simple bean properties.

2. In case of escaping special characters, for ${ to appear in the page

output, __________ should be used in a JSP Page.

10.4 Preventing EL Evaluation

In JSP 1.2 and earlier, strings of the form ${...} had no special meaning. So,

it is possible that the characters $ {appear within a previously created page

that is now being used on a server that supports JSP 2.0. In such a case,

<UL>

<LI>Name: ${expression1}

<LI>Address: ${expression2}

</UL>

<jsp:include page="${expression3}" />

Page 203: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 190

you need to deactivate the expression language in that page. You have four

options for doing so.

Deactivating the expression language in an entire Web application.

You use a web.xml file that refers to servlets 2.3 (JSP 1.2) or earlier.

Deactivating the expression language in multiple JSP pages. You

use the jsp-property-group web.xml element to designate the

appropriate pages.

Deactivating the expression language in individual JSP pages. You

use the isELEnabled attribute of the page directive.

Deactivating individual expression language statements. In JSP 1.2

pages that need to be ported unmodified across multiple JSP versions

(with no web.xml changes), you can replace $ with &#36;, the HTML

character entity for $. In JSP 2.0 pages that contain both expression

language statements and literal ${ strings, you can use \${ when you

want ${ in the output.

Note: These techniques are only necessary when the page contains the sequence ${.

Deactivating the Expression Language in an Entire Web Application:

The JSP 2.0 expression language is automatically deactivated in Web

applications whose deployment descriptor (i.e., WEB-INF/web.xml file)

refers to servlet specification version 2.3 or earlier (i.e., JSP 1.2 or earlier).

For example, the following empty-but-legal web.xml file is compatible with

JSP 1.2, and thus indicates that the expression language should be

deactivated by default.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application

2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

</web-app>

Page 204: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 191

On the other hand, the following web.xml file is compatible with JSP 2.0,

and thus stipulates that the expression language should be activated by

default.

Deactivating the Expression Language in Multiple JSP Pages:

In a Web application whose deployment descriptor specifies Servlets 2.4

(JSP 2.0), you use the el-ignored sub-element of the jsp-property-group

web.xml element to designate the pages in which the expression language

should be ignored. Here is an example that deactivates the expression

language for all JSP pages in the legacy directory.

Deactivating the Expression Language in Individual JSP Pages:

To disable EL evaluation in an individual page, supply false as the value of

the isELEnabled attribute of the page directive, as follows.

<%@ page isELEnabled="false" %>

Note that the isELEnabled attribute is new in JSP 2.0 and it is an error to

use it in a server that supports only JSP 1.2 or earlier. So, you cannot use

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"

version="2.4">

</web-app>

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"

version="2.4">

<jsp-property-group>

<url-pattern>/legacy/*.jsp</url-pattern>

<el-ignored>true</el-ignored>

</jsp-property-group>

</web-app>

Page 205: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 192

this technique to allow the same JSP page to run in either old or new

servers without modification. Consequently, the jsp-property-group element

is usually a better choice than the isELEnabled attribute.

Deactivating Individual Expression Language Statements:

Suppose you have a JSP 1.2 page containing ${ that you want to use in

multiple places. In particular, you want to use it in both JSP 1.2 Web

applications and in Web applications that contain expression language

pages. You want to be able to drop the page in any Web application without

making any changes either to it or to the web.xml file. Although this is an

unlikely scenario, it could happen, and none of the previously discussed

constructs will serve the purpose. In such a case, you simply replace the $

with the HTML character entity corresponding to the ISO 8859-1

value of $ (36). So, you replace ${ with &#36;{ throughout the page.

For example, &#36;{blah} will display

${blah}

to the user. Note, however, that the character entity is translated to $ by the

browser, not by the server, so this technique will only work when you are

outputting HTML to a Web browser.

Finally, suppose you have a JSP 2.0 page that contains both expression

language statements and literal ${ strings. In such a case, simply put a

backslash in front of the dollar sign.

So, for example,

\${1+1} is ${1+1}.

will give the output

${1+1} is 2.

10.5 Preventing Use of Standard Scripting Elements

The JSP expression language provides succinct and easy-to-read access to

scoped variables (Java objects stored in the standard locations). This

capability eliminates much of the need for the explicit Java scripting

elements. In fact, some developers prefer to use a no-classic-scripting-

elements approach throughout their entire projects. You can use the

scripting-invalid sub-element of jsp-property-group to enforce this restriction.

For example, the following web.xml file indicates that use of classic scripting

elements in any JSP page will result in an error.

Page 206: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 193

Self Assessment Questions

3. To disable EL evaluation in an individual page, supply ____ as the value

of the isELEnabled attribute of the page directive.

4. The statement \${1+1} is ${1+1} gives the output ________.

10.6 Accessing Scoped Variables

When you use the MVC approach, a Servlet invokes code that creates the

data, then uses RequestDispatcher.forward or response.sendRedirect to

transfer control to the appropriate JSP page. To permit the JSP page to

access the data, the Servlet needs to use setAttribute to store the data in

one of the standard locations: the HttpServletRequest, the HttpSession, or

the ServletContext.

Objects in these locations are known as “scoped variables,” and the

expression language has a quick and easy way to access them. You can

also have scoped variables stored in the PageContext object, but this is

much less useful because the Servlet and the JSP page do not share

PageContext objects. So, page-scoped variables apply only to objects

stored earlier in the same JSP page, not to objects stored by a servlet.

To output a scoped variable, you simply use its name in an expression

language element. For example,

${name}

means to search the PageContext, HttpServletRequest, HttpSession, and

ServletContext (in that order) for an attribute named name. If the attribute is

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=

"http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"

version="2.4">

<jsp-property-group>

<url-pattern>*.jsp</url-pattern>

<scripting-invalid>true</scripting-invalid>

</jsp-property-group>

</web-app>

Page 207: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 194

found, its toString method is called and that result is returned. If nothing is

found, an empty string (not null or an error message) is returned. So, for

example, the following two expressions are equivalent.

${name}

<%= pageContext.findAttribute("name") %>

The problems with the latter approach are that it is verbose and it requires

explicit Java syntax. It is possible to eliminate the Java syntax, but doing so

requires the following even more verbose jsp:useBean code.

<jsp:useBean id="name" type="somePackage.SomeClass"

scope="...">

<%= name %>

Besides, with jsp:useBean, you have to know which scope the Servlet has

used, and you have to know the fully qualified class name of the attribute.

This is a significant inconvenience, especially when the JSP page author is

someone other than the Servlet author.

Choosing Attribute Names

To use the JSP expression language to access scoped variables, you must

choose attribute names that would be legal as Java variable names. So,

avoid dots, spaces, dashes, and other characters that are permitted in

strings but forbidden in variable names.

Also, you should avoid using attribute names that conflict with any of the

predefined names.

Example

To illustrate access to scoped variables, the ScopedVars servlet (Listing

10.1) stores a String in the HttpServletRequest, another String in the

HttpSession, and a Date in the ServletContext. The servlet forwards the

request to a JSP page (Listing 10.2, Figure 10.2) that uses ${attributeName}

to access and output the objects.

Notice that the JSP page uses the same syntax to access the attributes,

regardless of the scope in which they were stored. This is usually a

convenient feature because MVC servlets almost always use unique

attribute names for the objects they store.

Page 208: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 195

However, it is technically possible for attribute names to be repeated, so you

should be aware that the expression language searches the PageContext,

HttpServlet-Request, HttpSession, and ServletContext, in that order.

To illustrate this, the servlet stores an object in each of the three shared

scopes, using the attribute name repeated in all three cases. The value

returned by ${repeated} (see Figure 10.2) is the first attribute found when

searching the scopes in the defined order (i.e., the HttpServletRequest in

this case).

Listing 10.1: ScopedVars.java

package coreservlets;

/** Servlet that creates some scoped variables (objects stored

* as attributes in one of the standard locations). Forwards

* to a JSP page that uses the expression language to

* display the values.

*/

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ScopedVars extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

request.setAttribute("attribute1", "First Value");

HttpSession session = request.getSession();

session.setAttribute("attribute2", "Second Value");

Page 209: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 196

Listing 10.2: scoped-vars.jsp

ServletContext application = getServletContext(); application.setAttribute("attribute3", new java.util.Date()); request.setAttribute("repeated", "Request"); session.setAttribute("repeated", "Session"); application.setAttribute("repeated", "ServletContext"); RequestDispatcher dispatcher = request.getRequestDispatcher("/el/scoped-vars.jsp"); dispatcher.forward(request, response); } }

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Accessing Scoped Variables</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Accessing Scoped Variables </TABLE> <P> <UL> <LI><B>attribute1:</B> ${attribute1} <LI><B>attribute2:</B> ${attribute2} <LI><B>attribute3:</B> ${attribute3} <LI><B>Source of "repeated" attribute:</B> ${repeated} </UL> </BODY></HTML>

Page 210: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 197

Figure 10.2: The JSP 2.0 expression language simplifies access to scoped variables:objects stored as attributes of the page, request, session, or servlet context.

Self Assessment Questions

5. To permit the JSP page to access the data, the Servlet needs to use

____ to store the data in one of the standard locations: the HttpServlet

Request, the HttpSession, or the ServletContext.

6. The _____ page uses the same syntax to access the attributes,

regardless of the scope in which they were stored.

10.7 Summary

1. Motivating EL Usage: This topic discusses about the need and

motivation for usage of Expression Languages in Server Side

Programming. It also describes different strategies that JSP pages can

use to invoke Java code.

2. Invoking the EL: This topic explains the invocation mechanisms of the

expression language with appropriate elements.

3. Preventing EL Evaluation: In JSP 1.2 and earlier, strings of the form

${...} had no special meaning. So, it is possible that the characters $

{appear within a previously created page that is now being used on a

server that supports JSP 2.0. In such a case, you need to deactivate the

Page 211: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 198

expression language in that page. This topic discusses various places in

a Web page where the action of de-activation has to be carried out.

4. Preventing use of Standard Scripting elements: The JSP expression

language provides succinct and easy-to-read access to scoped

variables (Java objects stored in the standard locations). This capability

eliminates much of the need for the explicit Java scripting elements. In

fact, some developers prefer to use a no-classic-scripting-elements

approach throughout their entire projects. You can use the scripting-

invalid sub-element of jsp-property-group to enforce this restriction. This

topic discusses various ways of preventing the usage of standard

scripting elements.

5. Accessing Scoped Variables: When you use the MVC approach, a

Servlet invokes code that creates the data, then uses

RequestDispatcher.forward or response.sendRedirect to transfer control

to the appropriate JSP page. To permit the JSP page to access the

data, the Servlet needs to use setAttribute to store the data in one of the

standard locations: the HttpServletRequest, the HttpSession, or the

ServletContext. This topic discusses about the usage of scoped

variables in programming context.

10.8 Terminal Questions

1. Describe the process of deactivating Individual Expression Language

Statements.

2. Describe the theory behind accessing scoped variables.

10.9 Answers

Self Assessment Questions

1. jsp:getProperty

2. \${

3. false

4. ${1+1} is 2

5. setAttribute

6. JSP

Page 212: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 10

Sikkim Manipal University Page No.: 199

Terminal Questions

1. Suppose you have a JSP 1.2 page containing ${ that you want to use in

multiple places. In particular, you want to use it in both JSP 1.2 Web

applications and in Web applications that contain expression language

pages. You want to be able to drop the page in any Web application

without making any changes either to it or to the web.xml file. Although

this is an unlikely scenario, it could happen, and none of the previously

discussed constructs will serve the purpose. In such a case, you simply

replace the $ with the HTML character entity corresponding to the ISO

8859-1. (Refer Section 10.4)

2. When you use the MVC approach, a servlet invokes code that creates

the data, then uses RequestDispatcher.forward or response. Send

Redirect to transfer control to the appropriate JSP page. To permit the

JSP page to access the data, the servlet needs to use setAttribute to

store the data in one of the standard locations: the HttpServletRequest,

the HttpSession, or the ServletContext.

Objects in these locations are known as “scoped variables,” and the

expression language has a quick and easy way to access them. You

can also have scoped variables stored in the PageContext object, but

this is much less useful because the Servlet and the JSP page do not

share PageContext objects. So, page-scoped variables apply only to

objects stored earlier in the same JSP page, not to objects stored by a

servlet. (Refer Section 10.6)

Page 213: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 200

Unit 11 JSP 2.0 Expression Language – II

Structure:

11.1 Introduction

Objectives

11.2 Accessing Bean Properties

11.3 Accessing Collections

11.4 Referencing Implicit Objects

11.5 Using Expression Language (EL) Operators

11.6 Evaluating Expressions Conditionally

11.7 Summary

11.8 Terminal Questions

11.9 Answers

11.1 Introduction

In the previous unit, we have covered few EL concepts like invoking the EL,

prevention of EL evaluation, and accessing scoped variables. In this unit we

are going discuss the extensions of the EL covering the concept of Beans,

collections, implicit objects, and EL operators.

For a better understanding of the topics discussed in this unit, you can go

through the web site http://www.java.sun.com and specifically search for the

topic of Java Beans.

Objectives:

After studying this unit, you should be able to:

describe and illustrate the properties of Beans

explain accessing methods of Collection objects

describe the process of referencing implicit objects

illustrate the usage of EL Operators with suitable examples

describe conditional expression evaluation

11.2 Accessing Bean Properties

When you simply use ${name}, the system finds the object named name,

coerces it to a String, and returns it. Although this behavior is convenient,

you rarely want to output the actual object that the MVC Servlet stored.

Rather, you typically want to output individual properties of that object.

Page 214: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 201

The JSP expression language provides a simple but very powerful dot

notation for accessing bean properties. To return the firstName property of a

scoped variable named customer, you merely use ${customer.firstName}.

Although this form appears very simple, the system must perform reflection

(analysis of the internals of the object) to support this behavior. So,

assuming the object is of type NameBean and that NameBean is in the

coreservlets package, to do the same thing with explicit Java syntax, you

would have to replace

${customer.firstName}

with

<%@ page import="coreservlets.NameBean" %>

<%

NameBean person =

(NameBean)pageContext.findAttribute("customer");

%>

<%= person.getFirstName() %>

Furthermore, the version with the JSP expression language returns an

empty string if the attribute is not found, whereas the scripting element

version would need additional code to avoid a NullPointerException in the

same situation.

Now, JSP scripting elements are not the only alternative to use of the

expression language. As long as you know the scope and fully qualified

class name, you could replace

${customer.firstName}

with

<jsp:useBean id="customer" type="coreservlets.NameBean"

scope="request, session, or application" />

<jsp:getProperty name="customer" property="firstName" />

However, the expression language lets you nest properties arbitrarily. For

example, if the NameBean class had an address property (i.e., a

getAddress method) that returned an Address object with a zipCode

property (i.e., a getZipCode method), you could access this zipCode

property with the following simple form.

${customer.address.zipCode}

Page 215: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 202

There is no combination of jsp:useBean and jsp:getProperty that lets you do

the same thing without explicit Java syntax.

Equivalence of Dot Notation and Array Notation

Finally, note that the expression language lets you replace dot notation with

array notation (square brackets). So, for example, you can replace

${name.property}

with

${name["property"]}

The second form is rarely used with bean properties. However, it has two

advantages.

First, it lets you compute the name of the property at request time. With the

array notation, the value inside the brackets can itself be a variable; with dot

notation the property name must be a literal value.

Second, the array notation lets you use values that are illegal as property

names. This is of no use when accessing bean properties, but it is very

useful when accessing collections or request headers.

Example

To illustrate the use of bean properties, consider the BeanProperties Servlet

of Listing 11.1.

Page 216: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 203

Listing 11.1: BeanProperties.java

The Servlet creates an EmployeeBean (Listing 11.2), stores it in the request

object with an attribute named employee, and forwards the request to a JSP

page.

Listing 11.2: EmployeeBean.java

package coreservlets; /** Servlet that creates some beans whose properties will * be displayed with the JSP 2.0 expression language. */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class BeanProperties extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { NameBean name = new NameBean("Marty", "Hall"); CompanyBean company = new CompanyBean("coreservlets.com", "J2EE Training and Consulting"); EmployeeBean employee = new EmployeeBean(name, company); request.setAttribute("employee", employee); RequestDispatcher dispatcher = request.getRequestDispatcher("/el/bean-properties.jsp"); dispatcher.forward(request, response); } }

package coreservlets;

public class EmployeeBean {

private NameBean name;

private CompanyBean company;

public EmployeeBean(NameBean name, CompanyBean company) {

setName(name); setCompany(company); }

public NameBean getName() { return(name); }

public void setName(NameBean newName) { name = newName; }

public CompanyBean getCompany() { return(company); }

public void setCompany(CompanyBean newCompany) {

company = newCompany; } }

Page 217: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 204

The EmployeeBean class has name and company properties that refer to

Name-Bean (Listing 11.3) and CompanyBean (Listing 11.4) objects,

respectively. The NameBean class has firstName and lastName properties

and the CompanyBean class has companyName and business properties.

Listing 11.3: NameBean.java

Listing 11.4: CompanyBean.java

package coreservlets; public class NameBean { private String firstName = "Missing first name"; private String lastName = "Missing last name"; public NameBean() {} public NameBean(String firstName, String lastName) { setFirstName(firstName); setLastName(lastName); } public String getFirstName() { return(firstName); } public void setFirstName(String newFirstName) { firstName = newFirstName; } public String getLastName() { return(lastName); } public void setLastName(String newLastName) { lastName = newLastName; } }

package coreservlets; public class CompanyBean { private String companyName; private String business; public CompanyBean(String companyName, String business) { setCompanyName(companyName); setBusiness(business); } public String getCompanyName() { return(companyName); } public void setCompanyName(String newCompanyName) { companyName = newCompanyName; } public String getBusiness() { return(business); } public void setBusiness(String newBusiness) { business = newBusiness; } }

Page 218: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 205

The JSP page (Listing 11.5) uses the following simple EL expressions to

access the four attributes:

1) ${employee.name.firstName}

2) ${employee.name.lastName}

3) ${employee.company.companyName}

4) ${employee.company.business}

Listing 11.5: bean-properties.jsp

Figure 11.1 shows the results.

Fig. 11.1: Using dots or array notation to access bean properties.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Accessing Bean Properties</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Accessing Bean Properties </TABLE> <P> <UL> <LI><B>First Name:</B> ${employee.name.firstName} <LI><B>Last Name:</B> ${employee.name.lastName} <LI><B>Company Name:</B> ${employee.company.companyName} <LI><B>Company Business:</B> ${employee.company.business} </UL> </BODY></HTML>

Page 219: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 206

Self Assessment Question

1. The _________ notation of is of no use when accessing bean

properties, but it is very useful when accessing collections or request

headers.

11.3 Accessing Collections

The JSP 2.0 expression language lets you access different types of

collections in the same way: using array notation. For instance, if

attributeName is a scoped variable referring to an array, List, or Map, you

access an entry in the collection with the following:

${attributeName[entryName]}

If the scoped variable is an array, the entry name is the index and the value

is obtained with theArray[index]. For example, if customerNames refers to

an array of strings,

${customerNames[0]}

would output the first entry in the array.

If the scoped variable is an object that implements the List interface, the

entry name is the index and the value is obtained with theList.get(index). For

example, if supplierNames refers to an ArrayList,

${supplierNames[0]}

would output the first entry in the ArrayList.

If the scoped variable is an object that implements the Map interface, the

entry name is the key and the value is obtained with theMap.get(key). For

example, if stateCapitals refers to a HashMap whose keys are U.S. state

names and whose values are city names,

${stateCapitals["maryland"]}

would return "annapolis". If the Map key is of a form that would be legal as a

Java variable name, you can replace the array notation with dot notation.

So, the previous example could also be written as:

${stateCapitals.maryland}

However, note that the array notation lets you choose the key at request

time, whereas the dot notation requires you to know the key in advance.

Page 220: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 207

Example

To illustrate the use of EL expressions to access collections, the Collections

Servlet (Listing 11.6) creates an array of strings, an ArrayList, and a

HashMap.

Listing 11.6: Collections.java

The Servlet then forwards the request to a JSP page (Listing 11.7, Figure

11.2) that uses uniform array notation to access the elements of all three

objects.

Purely numeric values are illegal as bean properties, so the array and

ArrayList entries must be accessed with array notation. However, the

HashMap entries could be accessed with either array or dot notation. We

use array notation for consistency, but, for example,

${company["Ellison"]}

could be replaced with

${company.Ellison}

in Listing 11.7.

package coreservlets; import java.util.*; /** Servlet that creates some collections whose elements will be displayed with the JSP 2.0 expression language. * <P> */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Collections extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] firstNames = { "Bill", "Scott", "Larry" }; ArrayList lastNames = new ArrayList(); lastNames.add("Ellison"); lastNames.add("Gates"); lastNames.add("McNealy"); HashMap companyNames = new HashMap(); companyNames.put("Ellison", "Sun"); companyNames.put("Gates", "Oracle"); companyNames.put("McNealy", "Microsoft"); request.setAttribute("first", firstNames); request.setAttribute("last", lastNames); request.setAttribute("company", companyNames); RequestDispatcher dispatcher = request.getRequestDispatcher("/el/collections.jsp"); dispatcher.forward(request, response); } }

Page 221: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 208

Listing 11.7: collections.jsp

Figure 11.2: Using array notation or dots to access collections.

Dots can be used only when the key is in a form that would be legal as a Java

variable name.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD><TITLE>Accessing Collections</TITLE>

<LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css">

</HEAD> <BODY>

<TABLE BORDER=5 ALIGN="CENTER">

<TR><TH CLASS="TITLE">

Accessing Collections

</TABLE> <P> <UL>

<LI>${first[0]} ${last[0]} (${company["Ellison"]})

<LI>${first[1]} ${last[1]} (${company["Gates"]})

<LI>${first[2]} ${last[2]} (${company["McNealy"]})

</UL>

</BODY></HTML>

Page 222: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 209

Self Assessment Questions

2. The JSP 2.0 expression language lets you access different types of

collections using ______ notation.

3. If the _____ key is of a form that would be legal as a Java variable

name, you can replace the array notation with dot notation.

11.4 Referencing Implicit Objects

In most cases, you use the JSP expression language in conjunction with the

Model-View-Controller architecture in which the Servlet creates the data and

the JSP page presents the data. In such a scenario, the JSP page is usually

only interested in the objects that the servlet created, and the general bean-

access and collection-access mechanisms are sufficient.

However, the expression language is not restricted to use in the MVC

approach; if the server supports JSP 2.0 and the web.xml file refers to

servlets 2.4, the expression language can be used in any JSP page. To

make this capability useful, the specification defines the following implicit

objects.

pageContext

The pageContext object refers to the PageContext of the current page. The

PageContext class, in turn, has request, response, session, out, and

servletContext properties (i.e., getRequest, getResponse, getSession,

getOut, and getServletContext methods). So, for example, the following

outputs the current session ID.

${pageContext.session.id}

param and paramValues

These objects let you access the primary request parameter value (param)

or the array of request parameter values (paramValues). So, for example,

the following outputs the value of the custID request parameter (with an

empty string, not null, returned if the parameter does not exist in the current

request).

${param.custID}

header and headerValues

These objects access the primary and complete HTTP request header

values, respectively. Remember that dot notation cannot be used when the

Page 223: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 210

value after the dot would be an illegal property name. So, for example, to

access the Accept header, you could use either

${header.Accept}

or

${header["Accept"]}

But, to access the Accept-Encoding header, you must use

${header["Accept-Encoding"]}

Cookie

The cookie object lets you quickly refer incoming cookies. However, the

return value is the Cookie object, not the cookie value. To access the value,

use the standard value property (i.e., the getValue method) of the Cookie

class. So, for example, either of the following outputs the value of the cookie

named userCookie (or an empty string if no such cookie is found).

${cookie.userCookie.value}

${cookie["userCookie"].value}

initParam

The initParam object lets you easily access context initialization parameters.

For example, the following outputs the value of the init param named

defaultColor.

${initParam.defaultColor}

pageScope, requestScope, sessionScope, and applicationScope

These objects let you restrict where the system looks for scoped variables.

For example, with

${name}

the system searches for name in the PageContext, the HttpServlet-Request,

the HttpSession, and the ServletContext, returning the first match it finds.

On the other hand, with

${requestScope.name}

the system only looks in the HttpServletRequest.

Example

The JSP page of Listing 11.8 uses the implicit objects to output a request

parameter, an HTTP request header, a cookie value, and information about

the server.

Page 224: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 211

Listing 11.8: implicit-objects.jsp

Figure 11.3 shows the results.

Figure 11.3: A number of scoped variables are defined automatically.

These predefined variables are called “implicit objects.”

Self Assessment Questions

4. The _____ class, in turn, has request, response, session, out, and

servletContext properties.

5. With ________ the system searches for name in the PageContext, the

HttpServlet-Request, the HttpSession, and the ServletContext, returning

the first match it finds.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Using Implicit Objects</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Using Implicit Objects </TABLE> <P> <UL> <LI><B>test Request Parameter:</B> ${param.test} <LI><B>User-Agent Header:</B> ${header["User-Agent"]} <LI><B>JSESSIONID Cookie Value:</B> ${cookie.JSESSIONID.value} <LI><B>Server:</B> ${pageContext.servletContext.serverInfo} </UL> </BODY></HTML>

Page 225: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 212

11.5 Using Expression Language (EL) Operators

The JSP 2.0 expression language defines a number of arithmetic, relational,

logical, and missing-value-testing operators. Although the use of the

operators often result in code that is a bit shorter than the equivalent Java

code, you should keep in mind the main purpose of the expression

language: to provide concise access to existing objects, usually in the

context of the MVC architecture. So, we see little benefit in replacing long

and complex scripting elements with only slightly shorter expression

language elements. Both approaches are wrong; complex business- or

data-access logic does not belong in JSP pages at all. As much as possible,

restrict the use of the expression language to presentation logic; keep the

business logic in normal Java classes that are invoked by Servlets.

1) Arithmetic Operators

These operators are typically used to perform simple manipulation of values

already stored in beans. Resist using them for complex algorithms; put such

code in regular Java code instead.

+ and –: These are the normal addition and subtraction operators, with two

exceptions. First, if either of the operands is a string, the string is

automatically parsed to a number (however, the system does not

automatically catch NumberFormat-Exception). Second, if either of the

operands is of type BigInteger or BigDecimal, the system uses the

corresponding add and subtract methods.

*, /, and div: These are the normal multiplication and division operators,

with a few exceptions. First, types are converted automatically as with the +

and – operators. Second, the normal arithmetic operator precedence

applies, so, for instance,

${ 1 + 2 * 3}

returns 7, not 9. You can use parentheses to change the operator

precedence. Third, the / and div operators are equivalent; both are provided

for the sake of compatibility with both XPath and JavaScript (ECMAScript).

Core Approach: Use the expression language operators for simple tasks oriented toward presentation logic (deciding how to present the data). Avoid using the operators for business logic (creating and processing the data). Instead, put business logic in regular Java classes and invoke the code from the Servlet that starts the MVC process.

Page 226: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 213

% and mod: The % (or equivalently, mod) operator computes the modulus

(remainder), just as with % in the Java programming language.

2) Relational Operators

These operators are most frequently used with either the JSP expression

language conditional operator or with custom tags whose attributes expect

boolean values.

== and eq: These two equivalent operators check whether the arguments

are equal. However, they operate more like the Java equals method than

the Java == operator. If the two operands are the same object, true is

returned. If the two operands are numbers, they are compared with Java ==.

If either operand is null, false is returned. If either operand is a BigInteger or

BigDecimal, the operands are compared with compareTo. Otherwise, the

operands are compared with equals.

!= and ne: These two equivalent operators check whether the arguments

are different. Again, however, they operate more like the negation of the

Java equals method than the Java != operator. If the two operands are the

same object, false is returned. If the two operands are numbers, they are

compared with Java !=. If either operand is null, true is returned. If either

operand is a BigInteger or BigDecimal, the operands are compared with

compareTo. Otherwise, the operands are compared with equals and the

opposite result is returned.

< and lt, > and gt, <= and le, >= and ge: These are the standard arithmetic

operators with two exceptions. First, type conversions are performed as with

== and !=. Second, if the arguments are strings, they are compared

lexically.

3) Logical Operators

These operators are used to combine results from the relational operators.

&&, and, ||, or, !, not

These are the standard logical AND, OR, and NOT operators. They operate

by coercing their arguments to Boolean, and they use the normal Java

“short circuit” evaluation in which the testing is stopped as soon as the result

can be determined. && and and are equivalent, || and or are equivalent, and

! and not are equivalent.

Page 227: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 214

4) The empty Operator

This operator returns true if its argument is null, an empty string, an empty

array, an empty Map, or an empty collection. Otherwise it returns false.

Example: Listing 11.9 illustrates several of the standard operators; Figure

11.4 shows the result.

Listing 11.9: operators.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>EL Operators</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> EL Operators </TABLE> <P> <TABLE BORDER=1 ALIGN="CENTER"> <TR><TH CLASS="COLORED" COLSPAN=2>Arithmetic Operators <TH CLASS="COLORED" COLSPAN=2>Relational Operators <TR><TH>Expression<TH>Result<TH>Expression<TH>Result <TR ALIGN="CENTER"> <TD>\${3+2-1}<TD>${3+2-1} <%-- Addition/Subtraction --%> <TD>\${1&lt;2}<TD>${1<2} <%-- Numerical comparison --%> <TR ALIGN="CENTER"> <TD>\${"1"+2}<TD>${"1"+2} <%-- String conversion --%> <TD>\${"a"&lt;"b"}<TD>${"a"<"b"} <%-- Lexical comparison --%> <TR ALIGN="CENTER"> <TD>\${1 + 2*3 + 3/4}<TD>${1 + 2*3 + 3/4} <%-- Mult/Div --%> <TD>\${2/3 &gt;= 3/2}<TD>${2/3 >= 3/2} <%-- >= --%> <TR ALIGN="CENTER"> <TD>\${3%2}<TD>${3%2} <%-- Modulo --%> <TD>\${3/4 == 0.75}<TD>${3/4 == 0.75} <%-- Numeric = --%> <TR ALIGN="CENTER"> <%-- div and mod are alternatives to / and % --%> <TD>\${(8 div 2) mod 3}<TD>${(8 div 2) mod 3} <%-- Compares with "equals" but returns false for null --%> <TD>\${null == "test"}<TD>${null == "test"} <TR><TH CLASS="COLORED" COLSPAN=2>Logical Operators <TH CLASS="COLORED" COLSPAN=2><CODE>empty</CODE> Operator <TR><TH>Expression<TH>Result<TH>Expression<TH>Result <TR ALIGN="CENTER">

Page 228: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 215

Listing 11.9: operators.jsp (Continued)

Figure 11.4: The expression language defines a small set of operators.

Use them with great restraint; invoke business logic from servlets, not from JSP pages.

11.6 Evaluating Expressions Conditionally

The JSP 2.0 expression language does not, in itself, provide a rich

conditional evaluation facility. That capability is provided by the c:if and

c:choose tags of the JSP Standard Tag Library (JSTL) or by another custom

tag library.

However, the expression language supports the rudimentary ?: operator as

in the Java, C, and C++ languages. For example, if test evaluates to true, ${

test ? expression1 : expression2 }

<TD>\${(1&lt;2) && (4&lt;3)}<TD>${(1<2) && (4<3)} <%--AND--%>

<TD>\${empty ""}<TD>${empty ""} <%-- Empty string --%>

<TR ALIGN="CENTER">

<TD>\${(1&lt;2) || (4&lt;3)}<TD>${(1<2) || (4<3)} <%--OR--%>

<TD>\${empty null}<TD>${empty null} <%-- null --%>

<TR ALIGN="CENTER">

<TD>\${!(1&lt;2)}<TD>${!(1<2)} <%-- NOT -%>

<%-- Handles null or empty string in request param --%>

<TD>\${empty param.blah}<TD>${empty param.blah}

</TABLE> </BODY></HTML>

Page 229: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 216

returns the value of expression1; otherwise, it returns the value of

expression2. Just remember that the main purpose of the expression

language is to simplify presentation logic; avoid using this technique for

business logic.

Example

The Servlet of Listing 11.10 creates two SalesBean objects (Listing 11.11)

and forwards the request to a JSP page (Listing 11.12) for presentation

(Figure 11.5). However, if the total sales number is negative, the JSP page

wants to use a table cell with a red background. If it is negative, the page

wants to use a white background. Implementing this behavior is a

presentation task, so the ?: operator is appropriate.

Listing 11.10: Conditionals.java

package coreservlets;

/** Servlet that creates scoped variables that will be used

* to illustrate the EL conditional operator (xxx ? xxx : xxx).

*/

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Conditionals extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

SalesBean apples = new SalesBean(150.25, -75.25, 22.25, -33.57);

SalesBean oranges = new SalesBean(-220.25, -49.57, 138.25, 12.25);

request.setAttribute("apples", apples); request.setAttribute("oranges",

oranges);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/el/conditionals.jsp");

dispatcher.forward(request, response);

} }

Page 230: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 217

Listing 11.11: SalesBean.java

package coreservlets;

public class SalesBean {

private double q1, q2, q3, q4;

public SalesBean(double q1Sales,

double q2Sales,

double q3Sales,

double q4Sales) {

q1 = q1Sales;

q2 = q2Sales;

q3 = q3Sales;

q4 = q4Sales;

}

public double getQ1() { return(q1); }

public double getQ2() { return(q2); }

public double getQ3() { return(q3); }

public double getQ4() { return(q4); }

public double getTotal() { return(q1 + q2 + q3 + q4); }

}

Page 231: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 218

Listing 11.12: conditionals.jsp

Self Assessment Questions

6. The _______ operators are most frequently used with either the JSP

expression language conditional operator or with custom tags whose

attributes expect boolean values.

7. A rich _________ facility is provided by the c:if and c:choose tags of the

JSP Standard Tag Library (JSTL) or by another custom tag library.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>Conditional Evaluation</TITLE> <LINK REL=STYLESHEET HREF="/el/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Conditional Evaluation </TABLE> <P> <TABLE BORDER=1 ALIGN="CENTER"> <TR><TH> <TH CLASS="COLORED">Apples <TH CLASS="COLORED">Oranges <TR><TH CLASS="COLORED">First Quarter <TD ALIGN="RIGHT">${apples.q1} <TD ALIGN="RIGHT">${oranges.q1} <TR><TH CLASS="COLORED">Second Quarter <TD ALIGN="RIGHT">${apples.q2} <TD ALIGN="RIGHT">${oranges.q2} <TR><TH CLASS="COLORED">Third Quarter <TD ALIGN="RIGHT">${apples.q3} <TD ALIGN="RIGHT">${oranges.q3} <TR><TH CLASS="COLORED">Fourth Quarter <TD ALIGN="RIGHT">${apples.q4} <TD ALIGN="RIGHT">${oranges.q4} <TR><TH CLASS="COLORED">Total <TD ALIGN="RIGHT" BGCOLOR="${(apples.total < 0) ? "RED" : "WHITE" }"> ${apples.total} <TD ALIGN="RIGHT" BGCOLOR="${(oranges.total < 0) ? "RED" : "WHITE" }"> ${oranges.total} </TABLE> </BODY></HTML>

Page 232: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 219

Figure 11.5: Using the C-style ?: operator to conditionally output different

elements.

However, the JSP Standard Tag Library (JSTL) is often a better alternative

for this kind of conditional operation.

11.7 Summary

Accessing Bean Properties: This topic covered the usage of bean

properties in Java Server Pages on different objects used in

programming. It also demonstrated the use of MVC architecture and

expression language usage in beans.

Accessing Collections: This topic covered the usage of JSP 2.0

expression language to access different types of collections using array

notations.

Referencing Implicit Objects: The expression language is not

restricted to use in the MVC approach. If the server supports JSP 2.0

and the web.xml file refers to Servlets 2.4, the expression language can

be used in any JSP page. To make this capability useful, the implicit

objects are used.

Using EL Operators: The JSP 2.0 expression language defines a

number of arithmetic, relational, logical, and missing-value-testing

operators. The usage of these operators has been covered. As much as

possible, restrict the use of the expression language to presentation

Page 233: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 220

logic; keep the business logic in normal Java classes that are invoked by

Servlets.

Evaluating Expressions Conditionally: The JSP 2.0 expression

language does not, in itself, provide a rich conditional evaluation facility.

That capability is provided by the c:if and c:choose tags of the JSP

Standard Tag Library (JSTL) or by another custom tag library. However,

the support of expression language at a basic level has been discussed.

11.8 Terminal Questions

1. Describe the theory behind accessing bean properties.

2. Explain the theory of referencing implicit objects with a suitable example.

3. Discuss the usage of EL operators with suitable examples.

11.9 Answers

Self Assessment Questions

1. array

2. array

3. Map

4. PageContext

5. ${name}

6. logical

7. conditional evaluation

Terminal Questions

1. When you simply use ${name}, the system finds the object named name,

coerces it to a String, and returns it. Although this behavior is

convenient, you rarely want to output the actual object that the MVC

Servlet stored. Rather, you typically want to output individual properties

of that object.

The JSP expression language provides a simple but very powerful dot

notation for accessing bean properties. (Refer Section 11.2)

2. The expression language is not restricted to use in the MVC approach; if

the server supports JSP 2.0 and the web.xml file refers to Servlets 2.4,

the expression language can be used in any JSP page. To make this

capability useful, the specification defines the following implicit objects.

(Refer Section 11.4)

Page 234: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 11

Sikkim Manipal University Page No.: 221

3. The JSP 2.0 expression language defines a number of arithmetic,

relational, logical, and missing-value-testing operators. Although use of

the operators often results in code that is a bit shorter than the

equivalent Java code, you should keep in mind the main purpose of the

expression language: to provide concise access to existing objects,

usually in the context of the MVC architecture. So, we see little benefit in

replacing long and complex scripting elements with only slightly shorter

expression language elements. (Refer Section 11.5)

Page 235: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 222

Unit 12 JSP Page Directives

Structure:

12.1 Introduction

Objectives

12.2 The import Attribute

12.3 The contentType and pageEncoding Attributes

12.4 Conditionally Generating Excel Spreadsheets

12.5 The Session Attribute

12.6 The isELIgnored Attribute

12.7 The buffer and autoFlush Attributes

12.8 The errorPage and isErrorPage Attributes

12.9 The isThreadSafe Attribute

12.10 The extends and Language Attributes

12.11 Summary

12.12 Terminal Questions

12.13 Answers

12.1 Introduction

In the previous unit, we have seen the Expression Language and its

operators being used in Server Programming, which form a part of the entire

program code that you would be writing for giving requests to and getting

responses from the server.

In this unit, we are going to discuss about the Page Directives. A JSP page

directive affects the overall structure of the Servlet that results from the JSP

page. The following templates show the two possible forms for directives.

Single quotes can be substituted for the double quotes around the attribute

values, but the quotation marks cannot be omitted altogether. To obtain

quotation marks within an attribute value, precede them with a backslash,

using \’ for ’ and \" for ".

<%@ directive attribute="value" %>

<%@ directive attribute1="value1"

attribute2="value2"

...

attributeN="valueN" %>

Page 236: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 223

In JSP, there are three main types of directives: page, include, and taglib.

The page directive lets you control the structure of the servlet by importing

classes, customizing the servlet superclass, setting the content type, and

the like. A page directive can be placed anywhere within the document; its

use is the topic of this chapter. The second directive, include, lets you insert

a file into the JSP page at the time the JSP file is translated into a Servlet.

An include directive should be placed in the document at the point at which

you want the file to be inserted

The page directive lets you define one or more of the following case-

sensitive attributes (listed in approximate order of frequency of use): import,

contentType, pageEncoding, session, isELIgnored (JSP 2.0 only), buffer,

autoFlush, info, errorPage, isErrorPage, isThreadSafe, language, and

extends. These attributes are explained in the following sections.

Objectives:

After studying this unit, you should be able to:

describe the importance of import attribute

designate which classes are imported

specify the MIME type of the page

generate Excel spreadsheets

describe the usage of isElIgnored attribute

illustrate the use of buffer and AutoFlush attributes

illustrate the use of errorPage and isErrorPage attributes

describe the application of isThreadSafe attributes

apply extends and language attributes to Server pages

12.2 The import Attribute

The import attribute of the page directive lets you specify the packages that

should be imported by the Servlet into which the JSP page gets translated.

As illustrated in Figure 12.1, using separate utility (helper) classes makes

your dynamic code easier to write, maintain, debug, test, and reuse.

Page 237: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 224

Simple application or small development team.

Complex application or large development team.

Call Java code directly. Place all Java code in

JSP page. Appropriate only for very small

amounts of code.

Call Java code indirectly. Develop separate

utility classes. Insert into JSP page only the

Java code needed to invoke the utility classes.

Use beans. Develop separate utility classes

structured as beans. Use jsp:useBean,

jsp:getProperty, and jsp:setProperty to invoke

the code.

Use the MVC architecture. Have a Servlet

respond to original request, look up data, and

store results in beans. Forward to a JSP page

to present results. JSP page uses beans.

Use the JSP expression language. Use

shorthand syntax to access and output object

properties. Usually used in conjunction with

beans and MVC.

Use custom tags. Develop tag handler

classes. Invoke the tag handlers with XML-like

custom tags

Fig. 12.1: Strategies for invoking dynamic code from JSP.

When you use utility classes, remember that they should always be in

packages. For one thing, packages are a good strategy on any large project

because they help protect against name conflicts. With JSP, however,

packages are absolutely required. The reason is that, in the absence of

packages, classes your references are assumed to be in the same package

as the current class. For example, suppose that a JSP page contains the

following scriptlet.

<% Test t = new Test(); %>

Now, if Test is in an imported package, there is no ambiguity. But, if Test is

not in a package or the package to which Test belongs is not explicitly

Page 238: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 225

imported, then the system will assume that Test is in the same package as

the autogenerated servlet.

The problem is that the autogenerated servlet’s package is not known! It is

quite common for servers to create servlets whose package is determined

by the directory in which the JSP page is placed. Other servers use different

approaches. So, you simply cannot rely on packageless classes working

properly. The same argument applies to beans, since beans are just classes

that follow some simple naming and structure conventions.

Core Approach: Always put your utility classes and beans in packages.

By default, the servlet imports java.lang.*, javax.servlet.*, javax.servlet.jsp.*,

javax.servlet.http.*, and possibly some number of server-specific entries.

Never write JSP code that relies on any server-specific classes being

imported automatically; doing so makes your code nonportable.

Use of the import attribute takes one of the following two forms.

<%@ page import="package.class" %>

<%@ page import="package.class1,...,package.classN" %>

For example, the following directive signifies that all classes in the java.util

package should be available to use without explicit package identifiers.

<%@ page import="java.util.*" %>

The import attribute is the only page attribute that is allowed to appear

multiple times within the same document. Although page directives can

appear anywhere within the document, it is traditional to place import

statements either near the top of the document or just before the first place

that the referenced package is used.

Note that, although the JSP pages go in the normal HTML directories of the

server, the classes you write that are used by JSP pages must be placed in

the special Java-code directories (e.g., .../WEB-INF/classes/directory

MatchingPackageName).

For example, Listing 12.1 presents a page that illustrates each of the three

scripting elements. The page uses three classes not in the standard JSP

import list: java.util.Date, coreservlets.CookieUtilities (Utility that simplifies

retrieving the cookie (or value of cookie) with the designated name.), and

coreservlets.LongLivedCookie (Cookie that persists one year. Default

Page 239: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 226

Cookie doesn't persist past current browsing session.). So, to simplify

references to these classes, the JSP page uses

<%@ page import="java.util.*,coreservlets.*" %>

Listing 12.1: ImportAttribute.jsp

Figures 12.2 and 12.3 below show some typical results.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>The import Attribute</TITLE>

<LINK REL=STYLESHEET

HREF="JSP-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<H2>The import Attribute</H2>

<%-- JSP page Directive --%>

<%@ page import="java.util.*,coreservlets.*" %>

<%-- JSP Declaration --%>

<%!

private String randomID() {

int num = (int)(Math.random()*10000000.0);

return("id" + num);

}

private final String NO_VALUE = "<I>No Value</I>";

%>

<%-- JSP Scriptlet --%>

<%

String oldID =

CookieUtilities.getCookieValue(request, "userID", NO_VALUE);

if (oldID.equals(NO_VALUE)) {

String newID = randomID();

Cookie cookie = new LongLivedCookie("userID", newID);

response.addCookie(cookie);

}

%>

<%-- JSP Expressions --%>

This page was accessed on <%= new Date() %> with a userID

cookie of <%= oldID %>.

</BODY></HTML>

Page 240: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 227

Fig. 12.2: ImportAttribute.jsp when first accessed.

Fig. 12.3: ImportAttribute.jsp when accessed in a subsequent request.

Self Assessment Questions

1. When you use utility classes, remember they should always be in

_______.

2. Using separate ______ classes makes your dynamic code easier to

write, maintain, debug, test, and reuse.

12.3 The contentType and pageEncoding Attributes

The contentType attribute sets the Content-Type response header,

indicating the MIME type of the document being sent to the client.

Use of the contentType attribute takes one of the following two forms.

<%@ page contentType="MIME-Type" %>

<%@ page contentType="MIME-Type; charset=Character-

Set" %>

For example, the directive

<%@ page contentType="application/vnd.ms-excel" %>

Page 241: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 228

has the same basic effect as the scriptlet

<% response.setContentType("application/vnd.ms-excel");

%>

The first difference between the two forms is that response.setContentType

uses explicit Java code (an approach some developers try to avoid),

whereas the page directive uses only JSP syntax. The second difference is

that directives are parsed specially; they don’t directly become _jspService

code at the location at which they appear. This means that

response.setContentType can be invoked conditionally whereas the page

directive cannot be. Setting the content type conditionally is useful when the

same content can be displayed in different forms – for an example, see the

next section (Conditionally Generating Excel Spreadsheets).

Unlike regular servlets, for which the default MIME type is text/plain, the

default for JSP pages is text/html (with a default character set of ISO-8859-

1). Thus, JSP pages that output HTML in a Latin character set need not use

contentType at all. If you want to change both the content type and the

character set, you can do the following.

<%@ page contentType="someMimeType;

charset=someCharacterSet" %>

However, if you only want to change the character set, it is simpler to use

the pageEncoding attribute. For example, Japanese JSP pages might use

the following.

<%@ page pageEncoding="Shift_JIS" %>

Generating Excel Spreadsheets

Listing 12.2 shows a JSP page that uses the contentType attribute and tab-

separated data to generate Excel output. Note that the page directive and

comment are at the bottom so that the carriage returns at the ends of the

lines don’t show up in the Excel document. (Note: JSP does not ignore white

space — JSP usually generates HTML in which most white space is ignored

by the browser, but JSP itself maintains the white space and sends it to the

client.) Figure 12.4 shows the result in Internet Explorer on a system that

has Microsoft Office installed.

Page 242: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 229

Listing 12.2 Excel.jsp

Fig. 12.4: Excel document (Excel.jsp) in Internet Explorer.

12.4 Conditionally Generating Excel Spreadsheets

In most cases in which you generate non-HTML content with JSP, you know

the content type in advance. In those cases, the contentType attribute of the

page directive is appropriate: it requires no explicit Java syntax and can

appear anywhere in the page.

Occasionally, however, you may want to build the same content, but change

the listed content type depending on the situation. For example, many word

processing and desktop publishing systems can import HTML pages. So,

you could arrange to have the page come up either in the publishing system

or in the browser, depending on the content type you send. Similarly,

Microsoft Excel can import tables that are represented in HTML with the

TABLE tag. This capability suggests a simple method of returning either

HTML or Excel content, depending on which the user prefers: just use an

First Last Email

Address

Marty Hall [email protected]

Larry Brown [email protected]

Steve Balmer [email protected]

Scott McNealy [email protected]

<%@ page contentType="application/vnd.ms-excel" %>

<%-- There are tabs, not spaces, between columns. --%>

Page 243: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 230

HTML table and set the content type to application/vnd.ms-excel only if the

user requests the results in Excel.

Unfortunately, this approach brings to light a small deficiency in the page

directive:

attribute values cannot be computed at runtime, nor can page directives be

conditionally inserted as can template text. So, the following attempt results

in Excel content regardless of the result of the checkUserRequest method.

<% boolean usingExcel = checkUserRequest(request); %>

<% if (usingExcel) { %>

<%@ page contentType="application/vnd.ms-excel" %>

<% } %>

Fortunately, there is a simple solution to the problem of conditionally setting

the content type: just use scriptlets and the normal servlet approach of

response.set-ContentType, as in the following snippet:

<%

String format = request.getParameter("format");

if ((format != null) && (format.equals("excel"))) {

response.setContentType("application/vnd.ms-excel"); }

%>

For example, we once worked on a project that displayed financial (budget)

information to authorized users. The data could be displayed in a table in a

regular Web page if the user merely wanted to review it, or it could be

placed into an Excel spreadsheet if the user wanted to put it into a report.

When we first joined the project, there were two entirely separate pieces of

code for each task. We changed it to build the same HTML table either way

and to merely change the content type. Voila!

Listing 12.3 shows a page that uses this approach; Figures 12.5 and 12.6

show the results. In a real application, of course, the data would almost

certainly come from a database. We use static values here for simplicity.

Page 244: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 231

Listing 12.3: ApplesAndOranges.jsp

Fig. 12.5: The default result of ApplesAndOranges.jsp is HTML content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Comparing Apples and Oranges</TITLE>

<LINK REL=STYLESHEET

HREF="JSP-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<CENTER>

<H2>Comparing Apples and Oranges</H2>

<%

String format = request.getParameter("format");

if ((format != null) && (format.equals("excel"))) {

response.setContentType("application/vnd.ms-excel");

}

%>

<TABLE BORDER=1>

<TR><TH></TH> <TH>Apples<TH>Oranges

<TR><TH>First Quarter <TD>2307 <TD>4706

<TR><TH>Second Quarter<TD>2982 <TD>5104

<TR><TH>Third Quarter <TD>3011 <TD>5220

<TR><TH>Fourth Quarter<TD>3055 <TD>5287

</TABLE>

</CENTER></BODY></HTML>

Page 245: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 232

Fig. 12.6: Specifying format=excel for ApplesAndOranges.jsp

results in Excel content.

Self Assessment Questions

3. Unlike regular Servlets, for which the default MIME type is text/plain, the

default for JSP pages is ______.

4. The _____ values cannot be computed at runtime, nor can page

directives be conditionally inserted as can template text.

12.5 The Session Attribute

The session attribute controls the page participation in HTTP sessions.

Use of this attribute takes one of the following two forms.

<%@ page session="true" %> <%-- Default --%>

<%@ page session="false" %>

A value of true (the default) signifies that the predefined variable session (of

type HttpSession) should be bound to the existing session if one exists;

otherwise, a new session should be created and bound to session. A value

of false means that no sessions will be automatically created and that

attempts to access the variable session will result in errors at the time the

JSP page is translated into a Servlet.

Using session="false" may save significant amounts of server memory on

high-traffic sites. However, note that using session="false" does not disable

session tracking – it merely prevents the JSP page from creating new

Page 246: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 233

sessions for users who don’t have them already. So, since sessions are

user specific, not page specific, they do not do any good to turn off session

tracking for one page unless you also turn it off for related pages that are

likely to be visited in the same client session.

12.6 The isELIgnored Attribute

The isELIgnored attribute controls whether the JSP 2.0 Expression

Language (EL) is ignored (true) or evaluated normally (false). This attribute

is new in JSP 2.0; it is illegal to use it in a server that supports only JSP 1.2

or earlier. The default value of the attribute depends on the version of

web.xml you use for your Web application.

If your web.xml specifies servlets 2.3 (corresponding to JSP 1.2) or earlier,

the default is true (but it is still legal to change the default – you are

permitted to use this attribute in a JSP-2.0-compliant server regardless of

the web.xml version). If your web.xml specifies servlets 2.4 (corresponding

to JSP 2.0) or later, the default is false. Use of this attribute takes one of the

following two forms.

<%@ page isELIgnored="false" %>

<%@ page isELIgnored="true" %>

JSP 2.0 introduced a concise expression language for accessing request

parameters, cookies, HTTP headers, bean properties and Collection

elements from within a JSP page. Expressions in the JSP EL take the form

${expression}.

Normally, these expressions are convenient. However, what would happen

if you had a JSP 1.2 page that, just by happenstance, contained a string of

the form ${...}? In JSP 2.0, this could cause problems. Using

isELIgnored="true" prevents these problems.

12.7 The buffer and autoFlush Attributes

The buffer attribute specifies the size of the buffer used by the out variable,

which is of type JspWriter. Use of this attribute takes one of two forms:

<%@ page buffer="sizekb" %>

<%@ page buffer="none" %>

Page 247: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 234

Servers can use a larger buffer than you specify, but not a smaller one. For

example, <%@ page buffer="32kb" %> means the document content should

be buffered and not sent to the client until at least 32 kilobytes are

accumulated, the page is completed, or the output is explicitly flushed

(e.g., with response.flushBuffer). The default buffer size is server specific,

but must be at least 8 kilobytes. Be cautious about turning off buffering;

doing so requires JSP elements that set headers or status codes to appear

at the top of the file, before any HTML content.

On the other hand, disabling buffering or using a small buffer is occasionally

useful when it takes a very long time to generate each line of the output; in

this scenario, users would see each line as soon as it is ready, rather than

waiting even longer to see groups of lines. The autoFlush attribute controls

whether the output buffer should be automatically flushed when it is full (the

default) or whether an exception should be raised when the buffer overflows

(autoFlush="false"). Use of this attribute takes one of the following two

forms.

<%@ page autoFlush="true" %> <%-- Default --%>

<%@ page autoFlush="false" %>

A value of false is illegal when buffer="none" is also used. Use of auto-

Flush="false" is exceedingly rare when the client is a normal Web browser.

However, if the client is a custom application, you might want to guarantee

that the application either receives a complete message or no message at

all. A value of false could also be used to catch database queries that

generate too much data, but it is generally better to place that logic in the

data access code, not the presentation code.

The info Attribute

The info attribute defines a string that can be retrieved from the servlet by

means of the getServletInfo method. Use of info takes the following form.

<%@ page info="Some Message" %>

Self Assessment Questions

5. In a session attribute, a value of ______ signifies that the predefined

variable session (of type HttpSession) should be bound to the existing

session if one exists.

Page 248: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 235

6. The _____ attribute controls whether the JSP 2.0 Expression Language

(EL) is ignored (true) or evaluated normally (false).

7. The buffer attribute specifies the size of the buffer used by the out

variable, which is of type ____.

12.8 The errorPage and isErrorPage Attributes

The errorPage attribute specifies a JSP page that should process any

exceptions (i.e., something of type Throwable) thrown but not caught in the

current page. It is used as follows:

<%@ page errorPage="Relative URL" %>

The exception thrown will automatically be available to the designated error

page by means of the exception variable.

The isErrorPage attribute indicates whether or not the current page can act

as the error page for another JSP page. Use of isErrorPage takes one of the

following two forms:

<%@ page isErrorPage="true" %>

<%@ page isErrorPage="false" %> <%-- Default --%>

For example, Listing 12.4 shows a JSP page that computes speed based on

distance and time parameters. The page neglects to check whether the

input parameters are missing or malformed, so an error could easily occur at

runtime.

Page 249: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 236

Listing 12.4: ComputeSpeed.jsp

However, the page designates SpeedErrors.jsp (Listing 12.5) as the page to

handle errors that occur in ComputeSpeed.jsp, so the user does not receive

the typical terse JSP error messages. Note that SpeedErrors.jsp is placed in

the WEB-INF directory.

Because servers prohibit direct client access to WEB-INF, this arrangement

prevents clients from accidentally accessing SpeedErrors.jsp directly. When

an error occurs, Speed-Errors.jsp is accessed by the server, not by the

client: error pages of this sort do not result in response.sendRedirect calls,

and the client sees only the URL of the originally requested page, not the

URL of the error page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Computing Speed</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <%@ page errorPage="/WEB-INF/SpeedErrors.jsp" %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Computing Speed</TABLE> <%! // Note lack of try/catch for NumberFormatException if // value is null or malformed. private double toDouble(String value) { return(Double.parseDouble(value)); } %> <% double furlongs = toDouble(request.getParameter("furlongs")); double fortnights = toDouble(request.getParameter("fortnights")); double speed = furlongs/fortnights; %> <UL> <LI>Distance: <%= furlongs %> furlongs. <LI>Time: <%= fortnights %> fortnights. <LI>Speed: <%= speed %> furlongs per fortnight. </UL> </BODY></HTML>

Page 250: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 237

Listing 12.5: SpeedErrors.jsp

Figures 12.7 and 12.8 show results when good and bad input parameters

are received, respectively. Note that the errorPage attribute designates

page-specific error pages. To designate error pages that apply to an entire

Web application or to various categories of errors within an application, use

the error-page element in web.xml.

Fig. 12.7: ComputeSpeed.jsp when it receives legal values.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Error Computing Speed</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <%@ page isErrorPage="true" %> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Error Computing Speed</TABLE> <P> ComputeSpeed.jsp reported the following error: <I><%= exception %></I>. This problem occurred in the following place: <PRE> <%@ page import="java.io.*" %> <% exception.printStackTrace(new PrintWriter(out)); %> </PRE> </BODY></HTML>

Page 251: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 238

Figure 12.8: ComputeSpeed.jsp when it receives illegal values.

Note that the address line shows the URL of ComputeSpeed.jsp, not

SpeedErrors.jsp.

12.9 The isThreadSafe Attribute

The isThreadSafe attribute controls whether the servlet that results from the

JSP page will allow concurrent access (the default) or will guarantee that no

Servlet instance processes more than one request at a time

(isThreadSafe="false"). Use of the isThreadSafe attribute takes one of the

following two forms.

<%@ page isThreadSafe="true" %> <%-- Default --%>

<%@ page isThreadSafe="false" %>

Unfortunately, the standard mechanism for preventing concurrent access is

to implement the SingleThreadModel interface. Although Single-

ThreadModel and isThreadSafe="false" were recommended in the early

days, recent experience has shown that SingleThreadModel was so poorly

designed that it is basically useless. So, you should avoid isThreadSafe

method and use explicit synchronization instead.

Note: Do not use isThreadSafe method. Use explicit synchronization

instead.

To understand why isThreadSafe="false" is a bad idea, consider the

following non-thread-safe snippet to compute user IDs. It is not thread safe

since a thread could be preempted after reading idNum but before updating

it, yielding two users with the same user ID.

Page 252: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 239

<%! private int idNum = 0; %>

<%

String userID = "userID" + idNum;

out.println("Your ID is " + userID + ".");

idNum = idNum + 1;

%>

The code should have used a synchronized block. This construct is written

as

synchronized(someObject) { ... }

and means that once a thread enters the block of code, no other thread can

enter the same block (or any other block marked with the same object

reference) until the first thread exits.

So, the previous snippet should have been written in the following manner.

<%! private int idNum = 0; %>

<%

synchronized(this) {

String userID = "userID" + idNum;

out.println("Your ID is " + userID + ".");

idNum = idNum + 1;

}

%>

There are two reasons why this explicitly synchronized version is superior to

the original version with the addition of <%@ page isThreadSafe="false"

%>.

First, the explicitly synchronized version will probably have better

performance if the page is accessed frequently. The reason is that most

JSP pages are not CPU limited but are I/O limited. So, while the system

waits for I/O (e.g., a response from a database, the result of an EJB call,

output sent over the network to the user), it should be doing something else.

Since most servers implement SingleThreadModel by queueing up requests

and handling them one at a time, high-traffic JSP pages can be much slower

with this approach.

Even worse, the version that uses SingleThreadModel might not even get

the right answer!

Page 253: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 240

Rather than queueing up requests, servers are permitted to implement

SingleThreadModel by making a pool of servlet instances, as long as no

instance is invoked concurrently. This, of course, totally defeats the purpose

of using fields for persistence, since each instance would have a different

field (instance variable), and multiple users could still get the same user ID.

Defining the idNum field as static does not solve the problem either; the

‘this’ reference would be different for each Servlet instance, so the

protection would be ineffective. These problems are basically intractable.

Give up. Forget SingleThreadModel and isThreadSafe="false". Synchronize

your code explicitly instead.

12.10 The extends and Language Attributes

The extends attribute designates the superclass of the servlet that will be

generated for the JSP page. It takes the following form.

<%@ page extends="package.class" %>

This attribute is normally reserved for developers or vendors that implement

fundamental changes to the way in which pages operate (e.g., to add in

personalization features). Ordinary mortals should steer clear of this

attribute except when referring to classes provided by the server vendor for

this purpose.

At some point, the language attribute is intended to specify the scripting

language being used, as below.

<%@ page language="cobol" %>

For now, don’t bother with this attribute since java is both the default and the

only legal choice.

Self Assessment Questions

8. The _____ attribute controls whether the servlet that results from the

JSP page will allow concurrent access (the default) or will guarantee

that no Servlet instance processes more than one request at a time

(isThreadSafe="false").

9. The standard mechanism for preventing concurrent access is to

implement the _____ interface.

Page 254: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 241

10. The ____ attribute specifies a JSP page that should process any

exceptions (i.e., something of type Throwable) thrown but not caught

in the current page.

12.11 Summary

The Import attribute: The import attribute of the page directive lets you

specify the packages that should be imported by the Servlet into which the

JSP page gets translated.

The contentType and pageEncoding Attributes: The contentType

attribute sets the Content-Type response header, indicating the MIME type

of the document being sent to the client.

Conditionally Generating Excel Spreadsheets: In most cases in which

you generate non-HTML content with JSP, you know the content type in

advance. In those cases, the contentType attribute of the page directive is

appropriate: it requires no explicit Java syntax and can appear anywhere in

the page. This topic covered the usage of other objects like excel

spreadsheets, their generation using ASP objects and so on.

The Session Attribute: The session attribute controls whether the page

participates in HTTP sessions. This topic covered the usage of sessions in

communication between the client and the server.

The isELIgnored Attribute: The isELIgnored attribute controls whether the

JSP 2.0 Expression Language (EL) is ignored (true) or evaluated normally

(false). This attribute is new in JSP 2.0; it is illegal to use it in a server that

supports only JSP 1.2 or earlier. The default value of the attribute depends

on the version of web.xml you use for your Web application.

The buffer and autoFlush Attributes: This topic covered the usage of

buffers in programming and their clearance or automatic flushing

programmatically.

The errorPage and isErrorPage Attributes: The errorPage attribute

specifies a JSP page that should process any exceptions (i.e., something of

type Throwable) thrown but not caught in the current page. The isErrorPage

attribute indicates whether or not the current page can act as the error page

for another JSP page. The usage and application of these attributes has

been covered in this topic.

Page 255: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 242

The isThreadSafe Attribute: The isThreadSafe attribute controls whether

the servlet that results from the JSP page will allow concurrent access (the

default) or will guarantee that no Servlet instance processes more than one

request at a time (isThreadSafe="false"). This topic covered the application

of this attribute in the usage of threads within a program.

The extends and Language Attributes: The extends attribute designates

the superclass of the servlet that will be generated for the JSP page. The

language attribute is intended to specify the scripting language being used.

12.12 Terminal Questions

1. Describe the isELIgnored attribute.

2. Explain the buffer and autoFlush attributes.

3. Explain the application of isThreadSafe attribute.

12.13 Answers

Self Assessment Questions

1. packages

2. utility (helper)

3. text/html

4. attribute

5. true (the default)

6. isELIgnored

7. JspWriter

8. isThreadSafe

9. SingleThreadModel

10. errorPage

Terminal Questions

1. The isELIgnored attribute controls whether the JSP 2.0 Expression

Language (EL) is ignored (true) or evaluated normally (false). This

attribute is new in JSP 2.0; it is illegal to use it in a server that supports

only JSP 1.2 or earlier. The default value of the attribute depends on the

version of web.xml you use for your Web application.

If your web.xml specifies servlets 2.3 (corresponding to JSP 1.2) or

earlier, the default is true (but it is still legal to change the default – you

Page 256: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 12

Sikkim Manipal University Page No.: 243

are permitted to use this attribute in a JSP-2.0-compliant server

regardless of the web.xml version). (Refer Section 12.6)

2. The buffer attribute specifies the size of the buffer used by the out

variable, which is of type JspWriter. Use of this attribute takes one of the

two forms:

<%@ page buffer="sizekb" %>

OR

<%@ page buffer="none" %>

Servers can use a larger buffer than you specify, but not a smaller one.

For example, <%@ page buffer="32kb" %> means the document

content should be buffered and not sent to the client until at least 32

kilobytes are accumulated, the page is completed, or the output is

explicitly flushed (e.g., with response.flushBuffer). (Refer Section 12.7)

3. The isThreadSafe attribute controls whether the Servlet that results from

the JSP page will allow concurrent access (the default) or will guarantee

that no Servlet instance processes more than one request at a time

(isThreadSafe="false"). (Refer Section 12.9)

Page 257: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 244

Unit 13 JSP File Inclusions

Structure:

13.1 Introduction

Objectives

13.2 The jsp:include Action

13.3 The include Directive

13.4 Forwarding Requests with jsp:forward

13.5 Including Applets for the Java Plug-In

13.6 Summary

13.7 Terminal Questions

13.8 Answers

13.1 Introduction

In the previous unit you have learned about the various attributes of JSP

such as import attribute, content Type and page Encoding attributes,

session attribute. This unit describes about JSP File Inclusions. The

following topics are discussed in the unit JSP. The jsp:include action:

jsp:include action lets you include the output of a page at request

time,include directive:this directive construct lets you insert JSP code into

the main page before that main page is translated into a servlet, The jsp:

plugin action:jsp:plugin element is used to insert applets that use the Java

Plug-in into JSP pages.

Objectives:

After studying this unit, you should be able to:

include pages at request time using jsp:include

include files at page translation time using <%@ include ... %> (the

include directive)

explain why jsp:include is better than include directive.

include applets for the Java Plug-in using jsp: plugin.

13.2 The jsp:include Action

Suppose you have a series of pages, all of which have the same navigation

bar, contact information, or footer. What can you do? Well, one common

“solution” is to cut and paste the same HTML snippets into all the pages.

Page 258: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 245

This is a bad idea because when you change the common piece, you have

to change every page that uses it. Common solution is to use some sort of

server-side include mechanism. This general approach is a good one, but

the typical mechanisms are server specific. Enter jsp:include, a portable

mechanism that lets you insert any of the following into the JSP output:

The content of an HTML page.

The content of a plain text document.

The output of JSP page.

The output of a Servlet.

The jsp:include action includes the output of a secondary page at the time

the main page is requested. Although the output of the included pages

cannot contain JSP, the pages can be the result of resources that use

Servlets or JSP to create the output. That is, the URL that refers to the

included resource is interpreted in the normal manner by the server and

thus can be a Servlet or JSP page. The server runs the included page in the

usual way and places the output into the main page. This is precisely the

behavior of the include method of the RequestDispatcher class, which is

what Servlets use if they want to do this type of file inclusion.

The page Attribute: Specifying the Included Page

You designate the included page with the page attribute, as shown below.

This attribute is required; it should be a relative URL referencing the

resource whose output should be included.

<jsp:include page="relative-path-to-resource" />

Relative URLs that do not start with a slash are interpreted relative to the

location of the main page. Relative URLs that start with a slash are

interpreted relative to the base Web application directory, not relative to the

server root. For example, consider a JSP page in the headlines Web

application that is accessed by the URL http://host/headlines/sports/table-

tennis.jsp. The table-tennis.jsp file is in the sports subdirectory of whatever

directory is used by the headlines Web application. Now, consider the

following two include statements.

<jsp:include page="bios/cheng-yinghua.jsp" />

<jsp:include page="/templates/footer.jsp" />

Page 259: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 246

In the first case, the system would look for cheng-yinghua.jsp in the bios

subdirectory of sports (i.e., in the sports/bios sub-subdirectory of the main

directory of the headlines application). In the second case, the system would

look for footer.jsp in the templates subdirectory of the headlines application,

not in the templates subdirectory of the server root. The jsp:include action

never causes the system to look at files outside the current Web application.

If you have trouble remembering how the system interprets URLs that begin

with slashes, remember this rule: they are interpreted relative to the current

Web application whenever the server handles them; they are interpreted

relative to the server root only when the client (browser) handles them. For

example, the URL in

<jsp:include page="/path/file" />

is interpreted within the context of the current Web application because the

server resolves the URL; the browser never sees it. But, the URL in

<IMG SRC="/path/file" ...>

is interpreted relative to the server’s base directory because the browser

resolves the URL; the browser knows nothing about Web applications.

Note: URLs that start with slashes are interpreted differently by the server

than by the browser. The server always interprets them relative to the

current Web application. The browser always interprets them relative to the

server root.

Finally, note that you are permitted to place your pages in the WEB-INF

directory. Although the client is prohibited from directly accessing files in this

directory, it is the server, not the client, that accesses files referenced by the

page attribute of jsp:include. In fact, placing the included pages in WEB-INF

is a recommended practice; doing so will prevent them from being

accidentally accessed by the client (which would be bad, since they are

usually incomplete HTML documents).

Core Approach: To prevent the included files from being accessed

separately, place them in WEB-INF or a subdirectory thereof.

Page 260: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 247

XML Syntax and jsp:include

The jsp:include action is one of the first JSP constructs we have seen that

has only XML syntax, with no equivalent “classic” syntax. If you are

unfamiliar with XML, note three things:

XML element names can contain colons. So, do not be thrown off by

the fact that the element name is jsp:include. In fact, the XML-

compatible version of all standard JSP elements starts with the jsp prefix

(or namespace).

XML tags are case sensitive. In standard HTML, it does not matter if

you say BODY, body, or Body. In XML, it matters. So, be sure to use

jsp:include in all lower case.

XML tags must be explicitly closed. In HTML, there are container

elements such as H1 that have both start and end tags (<H1> ...</H1>)

as well as standalone elements such as IMG or HR that have no end

tags (<HR>). In addition, the HTML specification defines the end tags of

some container elements (e.g., TR, P) to be optional. In XML, all

elements are container elements, and end tags are never optional.

However, as a convenience, you can replace bodyless snippets such as

<blah></blah> with <blah/>. So when using jsp:include, be sure to

include that trailing slash.

The flush Attribute

In addition to the required page attribute, jsp:include has a second attribute:

flush, as shown below. This attribute is optional; it specifies whether the

output stream of the main page should be flushed before the inclusion of the

page (the default is false). Note, however, that in JSP 1.1, flush was a

required attribute and the only legal value was true.

<jsp:include page="relative-path-to-resource" flush="true" />

A News Headline Page

As an example of a typical use of jsp:include, consider the simple news

summary page shown in Listing 13.1. Page developers can change the

news items in the files Item1.html through Item3.html (Listings 13.2 through

13.4) without having to update the main news page. Figure 13.1 shows the

result.

Page 261: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 248

Notice that the included pieces are not complete Web pages. The included

pages can be HTML files, plain text files, JSP pages, or servlets (but with

JSP pages and servlets, only the output of the page is included, not the

actual code). In all cases, however, the client sees only the composite

result.

So, if both the main page and the included pieces contain tags such as

DOCTYPE, BODY, etc., the result will be illegal HTML because these tags

will appear twice in the result that the client sees. With servlets and JSP, it is

always a good habit to view the HTML source and submit the URL to an

HTML validator. When jsp:include is used, this advice is even more

important because beginners often erroneously design both the main page

and the included page as complete HTML documents.

Core Approach: Do not use complete HTML documents for your included

pages. Include only the HTML tags appropriate to the place where the

included files will be inserted.

Listing 13.1: WhatsNew.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>What's New at JspNews.com</TITLE>

<LINK REL=STYLESHEET

HREF="JSP-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">

<TR><TH CLASS="TITLE">

What's New at JspNews.com</TABLE>

<P>

Here is a summary of our three most recent news stories:

<OL>

<LI><jsp:include page="/WEB-INF/Item1.html" />

<LI><jsp:include page="/WEB-INF/Item2.html" />

<LI><jsp:include page="/WEB-INF/Item3.html" />

</OL>

</BODY></HTML>

Page 262: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 249

Listing 13.2: /WEB-INF/Item1.html

Listing 13.3: /WEB-INF/Item2.html

Listing 13.4: /WEB-INF/Item3.html

Fig. 13.1: Including files at request time lets you update the individual files

without changing the main page.

<B>Bill Gates acts humble.</B> In a startling and unexpected

development, Microsoft big wig Bill Gates put on an open act of

humility yesterday.

<A HREF="http://www.microsoft.com/Never.html">More details...</A>

<B>Scott McNealy acts serious.</B> In an unexpected twist,

wisecracking Sun head Scott McNealy was sober and subdued at

yesterday's meeting.

<A HREF="http://www.sun.com/Imposter.html">More details...</A>

<B>Larry Ellison acts conciliatory.</B> Catching his competitors

off guard yesterday, Oracle prez Larry Ellison referred to his

rivals in friendly and respectful terms.

<A HREF="http://www.oracle.com/Mistake.html">More details...</A>

Page 263: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 250

The jsp:param Element:

Augmenting Request Parameters

The included page uses the same request object as the originally requested

page. As a result, the included page normally sees the same request

parameters as the main page. If, however, you want to add to or replace

those parameters, you can use the jsp:param element (which has name and

value attributes) to do so. For example, consider the following snippet.

<jsp:include page="/fragments/StandardHeading.jsp">

<jsp:param name="bgColor" value="YELLOW" />

</jsp:include>

Now, suppose the main page is invoked by means of http://host/path/

MainPage.jsp?fgColor=RED. In such a case, the following list summarizes

the results of various getParameter calls.

In main page (MainPage.jsp). (Regardless of whether the getParameter

calls are before or after the file inclusion.)

request.getParameter("fgColor") returns "RED".

request.getParameter("bgColor") returns null.

In included page (StandardHeading.jsp).

request.getParameter("fgColor") returns "RED".

request.getParameter("bgColor") returns "YELLOW".

If the main page receives a request parameter that is also specified with the

jsp:param element, the value from jsp:param takes precedence only in the

included page.

Self Assessment Questions

1. With Servlets and JSP, it is always necessary to view the HTML source

and submit the URL to an HTML validator. (True / False).

2. We have to include HTML tags appropriate to the place where the

included files will be inserted. (True / False)

13.3 The include Directive

You use the include directive to include a file in the main JSP document at

the time the document is translated into a servlet (which is typically the first

time it is accessed). The syntax is as follows:

<%@ include file="Relative URL" %>

Page 264: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 251

Think of the include directive as a preprocessor: the included file is inserted

character for character into the main page, then the resultant page is treated

as a single JSP page. So, the fundamental difference between jsp:include

and the include directive is the time at which they are invoked: jsp:include is

invoked at request time, whereas the include directive is invoked at page

translation time.

However, there are more implications of this difference than you might first

think. We summarize them in Table 13.1.

Table 13.1: Differences Between jsp:include and the include Directive

Jsp:include

Action

Include Directive

Basic Syntax <jsp:include

page="..." />

<%@ include

file="..." %>

Inclusion occurs at Request time Page translation time

Included Output of page Actual content of file

Resulting number of Servlets Two (main page

and

included page

each become

a separate servlet)

One (included file is

inserted into main

page,

then that page is

translated

into a servlet)

Inclusion of page set

response headers that affect

the main page

No Yes

Inclusion of page definition

fields or methods used by the

main page.

No Yes

Necessity of updation of

main page when page

changes are included

No Yes

Equivalent Servlet code include method of

RequestDispatcher

None

Page 265: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 252

There are many ramifications of the fact that the included file is inserted at

page translation time with the include directive (<%@ include ... %>), not at

request time as with jsp:include. However, there are two really important

implications: maintenance and power. We discuss these two items in the

following two subsections.

Maintenance Problems with the include Directive

The first ramification of the inclusion occurring at page translation time is

that it is much more difficult to maintain pages that use the include directive

than is the case with jsp:include. With the include directive (<%@ include ...

%>), if the included file changes, all the JSP files that use it may need to be

updated. Servers are required to detect when a JSP page changes and to

translate it into a new Servlet before handling the next request.

Unfortunately, however, they are not required to detect when the included

file changes, only when the main page changes. Servers are allowed to

support a mechanism for detecting that an included file has changed (and

then recompiling the Servlet), but they are not required to do so.

In practice, few do. So, with most servers, whenever an included file

changes, you have to update the modification dates of each JSP page that

uses the file.

This is a significant inconvenience; it results in such serious maintenance

problems that the include directive should be used only in situations in which

jsp:include would not suffice. Some developers have argued that using the

include directive results in code that executes faster than it would with the

jsp:include action. Although this may be true in principle, the performance

difference is so small that it is difficult to measure, and the maintenance

advantages of jsp:include are so great that it is virtually always preferred

when both options are available. In fact, some developers find the

maintenance burden of the include directive so onerous that they avoid it

altogether. Perhaps this is an overreaction, but, at the very least, reserve

the include directive for situations for which you really need the extra power

it affords.

Note: For file inclusion, use jsp:include whenever possible. Reserve the

include directive (<%@ include ... %>) for cases in which the included file

defines fields or methods that the main page uses or when the included file

sets response headers of the main page.

Page 266: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 253

Additional Power from the include Directive

If the include directive results in hard-to-maintain code, why would anyone

want to use it? Well, that brings up the second difference between

jsp:include and the include directive. The include directive is more powerful.

With the include directive, the included file is permitted to contain JSP code

such as response header settings and field definitions that affect the main

page. For example, suppose snippet.jsp contained the following line of

code:

<%! int accessCount = 0; %>

In such a case, you could do the following in the main page:

<%@ include file="snippet.jsp" %> <%-- Defines accessCount --%>

<%= accessCount++ %> <%-- Uses accessCount --%>

With jsp:include, of course, this would be impossible because of the

undefined accessCount variable; the main page would not translate

successfully into a Servlet. Besides, even if it could be translated without

error, there would be no point; jsp:include includes the output of the auxiliary

page, and snippet.jsp has no output.

Updating the Main Page

With most servers, if you use the include directive and change the included

file, you also have to update the modification date of the main page. Some

operating systems have commands that update the modification date

without your actually editing the file (e.g., the Unix touch command), but a

simple portable alternative is to include a JSP comment in the top-level

page. Update the comment whenever the included file changes. For

example, you might put the modification date of the included file in the

comment, as below.

<%-- Navbar.jsp modified 9/1/03 --%>

<%@ include file="Navbar.jsp" %>

XML Syntax for the include Directive

The XML-compatible equivalent of

<%@ include file="..." %> is

<jsp:directive.include file="..." />

When this form is used, both the main page and the included file must use

XML-compatible syntax throughout.

Page 267: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 254

Example: Reusing Footers

As an example of a situation in which you would use the include directive

instead of jsp:include, suppose you have a JSP page that generates an

HTML snippet containing a small footer that includes access counts and

information about the most recent accesses to the current page. Listing 13.5

shows just such a page.

Now suppose you have several pages that want to have footers of that type.

You could put the footer in WEB-INF (where it is protected from direct client

access) and then have the pages that want to use it do so with the following.

<%@ include file="/WEB-INF/ContactSection.jsp" %>

Listing 13.6 shows a page that uses this approach; Figure 13.2 shows the

result. “Hold on!” you say, “Yes, ContactSection.jsp defines some instance

variables (fields). And, if the main page used those instance variables, I

would agree that you would have to use the include directive.

But, in this particular case, the main page does not use the instance

variables, so jsp:include should be used instead. Right?” Wrong. If you used

jsp:include here, then all the pages that used the footer would see the same

access count. You want each page that uses the footer to maintain a

different access count. You do not want ContactSection.jsp to be its own

Servlet; you want ContactSection.jsp to provide code that will be part of

each separate Servlet that results from a JSP page that uses

ContactSection.jsp. You need the include directive.

Page 268: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 255

Listing 13.5: ContactSection.jsp

Listing 13.6: SomeRandomPage.jsp

<%@ page import="java.util.Date" %>

<%-- The following become fields in each servlet that

results from a JSP page that includes this file. --%>

<%!

private int accessCount = 0;

private Date accessDate = new Date();

private String accessHost = "<I>No previous access</I>";

%>

<P>

<HR>

This page &copy; 2003

<A HREF="http//www.my-company.com/">my-company.com</A>.

This page has been accessed <%= ++accessCount %>

times since server reboot. It was most recently accessed from

<%= accessHost %> at <%= accessDate %>.

<% accessHost = request.getRemoteHost(); %>

<% accessDate = new Date(); %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Some Random Page</TITLE>

<META NAME="author" CONTENT="J. Random Hacker">

<META NAME="keywords"

CONTENT="foo,bar,baz,quux">

<META NAME="description"

CONTENT="Some random Web page.">

<LINK REL=STYLESHEET

HREF="JSP-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<TABLE BORDER=5 ALIGN="CENTER">

<TR><TH CLASS="TITLE">

Some Random Page</TABLE>

<P>

Information about our products and services.

<P>

Blah, blah, blah.

<P>

Yadda, yadda, yadda.

<%@ include file="/WEB-INF/ContactSection.jsp" %>

</BODY></HTML>

Page 269: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 256

Fig. 13.2: Result of SomeRandomPage.jsp.

Fig 13.2 uses the include directive so that it maintains access counts and

most-recent-hosts entries separately from any other pages that use

ContactSection.jsp.

13.4 Forwarding Requests with jsp:forward

You use jsp:include to combine output from the main page and the auxiliary

page. Instead, you can use jsp:forward to obtain the complete output from

the auxiliary page. For example, here is a page that randomly selects either

page1.jsp or page2.jsp to output.

<% String destination;

if (Math.random() > 0.5) {

destination = "/examples/page1.jsp";

} else {

destination = "/examples/page2.jsp";

}

%>

<jsp:forward page="<%= destination %>" />

To use jsp:forward, the main page must not have any output. This brings up

the question, what benefit does JSP provide, then? The answer is, none! In

fact, use of JSP is a hindrance in this type of situation because a real

situation would be more complex, and complex code is easier to develop

and test in a Servlet than it is in a JSP page. We recommend that you

completely avoid the use of jsp:forward. If you want to perform a task similar

Page 270: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 257

to this example, use a Servlet and have it call the forward method of

RequestDispatcher.

Self Assessment Questions

3. In JSP include action inclusion occurs at page translation time

(True/False).

4. In JSP include action, Inclusion of page set response headers that affect

the main Page (True/False).

5. _______ is used to obtain the complete output from the auxiliary page.

13.5 Including Applets for the Java Plug-In

Early in the evolution of the Java programming language, the main

application area was applets (Java programs embedded in Web pages and

executed by Web browsers). Furthermore, most browsers supported the

most up-to-date Java version. Now, however, applets are a very small part

of the Java world, and the only major browser that supports the Java 2

platform (i.e., JDK 1.2–1.4) is Netscape 6 and later.

This leaves applet developers with three choices:

Develop the applets with JDK 1.1 or even 1.02 (to support really old

browsers).

Have users install version 1.4 of the Java Runtime Environment (JRE),

then use JDK 1.4 for the applets.

Have users install any version of the Java 2 Plug-in, then use Java 2 for

the applets.

The first option is the one generally chosen for applets that will be deployed

to the general public, because that option does not require users to install

any special software. You need no special JSP syntax to use this option:

just use the normal HTML APPLET tag. Remember that .class files for

applets need to go in the Web-accessible directories, not WEB-INF/classes,

because it is the browser, not the server, that executes them.

However, the lack of support for the Java 2 Platform imposes several

restrictions on these applets:

To use Swing, you must send the Swing files over the network. This

process is time consuming and fails in Internet Explorer 3 and Netscape

3.x and 4.01– 4.05 (which only support JDK 1.02), since Swing depends

on JDK 1.1.

Page 271: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 258

You cannot use Java 2D.

You cannot use the Java 2 collections package.

Your code runs more slowly, since most compilers for the Java 2

platform are significantly improved over their 1.1 predecessors.

So, developers of complex applets for corporate intranets often choose one

of the second two options. The second option is best if the users all have

Internet Explorer 6 (or later) or Netscape 6 (or later). With those browsers,

version 1.4 of the JRE will replace the Java Virtual Machine (JVM) that

comes bundled with the browser. Again, you need no special JSP syntax to

use this option: just use the normal HTML APPLET tag. And again,

remember that .class files for applets need to go in the Web-accessible

directories, not WEB-INF/classes, because it is the browser, not the server

that executes them.

Note: No matter what approach you use for applets, the applet .class files

must go in the Web-accessible directories, not in WEB-INF/classes. The

browser, not the server, uses them.

In large organizations, however, many users have earlier browser versions,

and the second choice is not a viable option. So, to address this problem,

Sun developed a browser plug-in for Netscape and Internet Explorer that

lets you use the Java 2 platform in a variety of browser versions. This plug-

in is available at http://java.sun.com/ products/plugin/ and also comes

bundled with JDK 1.2.2 and later.

Since the plug-in is quite large (several megabytes), it is not reasonable to

expect users on the WWW at large to download and install it just to run your

applets. On the other hand, it is a reasonable alternative for fast corporate

intranets, especially since applets can automatically prompt browsers that

lack the plug-in to download it.

Unfortunately, in some browsers, the normal APPLET tag will not work with

the plug-in, since these older browsers are specifically designed to use only

their built-in virtual machine when they see APPLET. Instead, you have to

use a long and messy OBJECT tag for Internet Explorer and an equally long

EMBED tag for Netscape.

Furthermore, since you typically don’t know which browser type will be

accessing your page, you have to either include both OBJECT and EMBED

Page 272: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 259

(placing the EMBED within the COMMENT section of OBJECT) or identify

the browser type at the time of the request and conditionally build the right

tag. This process is straightforward but tedious and time consuming.

The jsp:plugin element instructs the server to build a tag appropriate for

applets that use the plug-in. This element does not add any Java

capabilities to the client. How could it? JSP runs entirely on the server; the

client knows nothing about JSP. The jsp:plugin element merely simplifies

the generation of the OBJECT or EMBED tags.

Note: The jsp:plugin element does not add any Java capability to the

browser. It merely simplifies the creation of the cumbersome OBJECT and

EMBED tags needed by the Java 2 Plug-in.

Servers are permitted some leeway in exactly how they implement

jsp:plugin but most simply include both OBJECT and EMBED. To see

exactly how your server translates jsp:plugin, insert into a page a simple

jsp:plugin element with type, code, width, and height attributes as in the

following example. Then, access the page from your browser and view the

HTML source. For example, Listing 13.7 shows the HTML code generated

by Tomcat for the following jsp:plugin element.

<jsp:plugin type="applet"

code="SomeApplet.class"

width="300" height="200">

</jsp:plugin>

Listing 13.7: Code Generated by Tomcat for jsp:plugin

<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

width="300" height="200"

codebase="http://java.sun.com/products/plugin/1.2.2/jinst

all-1_2_2-win.cab#Version=1,2,2,0">

<param name="java_code" value="SomeApplet.class">

<param name="type" value="application/x-java-applet;">

<COMMENT>

<embed type="application/x-java-applet;" width="300" height="200"

pluginspage="http://java.sun.com/products/plugin/"

java_code="SomeApplet.class"

>

<noembed>

</COMMENT>

</noembed></embed>

</object>

Page 273: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 260

The jsp:plugin Element

The simplest way to use jsp:plugin is to supply four attributes: type, code,

width, and height. You supply a value of applet for the type attribute and use

the other three attributes in exactly the same way as with the APPLET

element, with two exceptions: the attribute names are case sensitive, and

single or double quotes are always required around the attribute values. So,

for example, you could replace:

<APPLET CODE="MyApplet.class"

WIDTH=475 HEIGHT=350>

</APPLET>

with

<jsp:plugin type="applet"

code="MyApplet.class"

width="475" height="350">

</jsp:plugin>

The jsp:plugin element has a number of other optional attributes. Most

parallel the attributes of the APPLET element. Here is a full list.

Table 13.2: JSP: Plugin Optional Attribute

Jsp:plugin

Optional

Attribute

Meaning

type

For applets, this attribute should have a value of applet.

However, the Java Plug-in also permits you to embed

JavaBeans components in Web pages. Use a value of bean in

such a case.

code

This attribute is used identically to the CODE attribute of

APPLET, specifying the top-level applet class file that extends

Applet or JApplet.

width

This attribute is used identically to the WIDTH attribute of

APPLET, specifying the width in pixels to be reserved for the

applet.

height

This attribute is used identically to the HEIGHT attribute of

APPLET, specifying the height in pixels to be reserved for the

applet.

Page 274: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 261

codebase

This attribute is used identically to the CODEBASE attribute of

APPLET, specifying the base directory for the applets. The code

attribute is interpreted relative to this directory. As with the

APPLET element, if you omit this attribute, the directory of the

current page is used as the default. In the case of JSP, this

default location is the directory in which the original JSP file

resided, not the system-specific location of the servlet that

results from the JSP file.

align

This attribute is used identically to the ALIGN attribute of

APPLET and IMG, specifying the alignment of the applet within

the Web page. Legal values are left, right, top, bottom, and

middle.

hspace

This attribute is used identically to the HSPACE attribute of

APPLET, specifying empty space in pixels reserved on the left

and right of the applet.

vspace

This attribute is used identically to the VSPACE attribute of

APPLET, specifying empty space in pixels reserved on the top

and bottom of the applet.

archive

This attribute is used identically to the ARCHIVE attribute of

APPLET, specifying a JAR file from which classes and images

should be loaded.

name

This attribute is used identically to the NAME attribute of

APPLET, specifying a name to use for interapplet

communication or for identifying the applet to scripting

languages like JavaScript.

title

This attribute is used identically to the very rarely used TITLE

attribute of APPLET (and virtually all other HTML elements in

HTML 4.0), specifying a title that could be used for a tool-tip or

for indexing.

jreversion

This attribute identifies the version of the Java Runtime

Environment (JRE) that is required. The default is 1.2.

iepluginurl

This attribute designates a URL from which the plug-in for

Internet Explorer can be downloaded. Users who don’t already

have the plug-in installed will be prompted to download it from

this location. The default value will direct the user to the Sun

site, but for intranet use you might want to direct the user to a

local copy.

nspluginurl

This attribute designates a URL from which the plug-in for

Netscape can be downloaded. The default value will direct the

user to the Sun site, but for intranet use you might want to direct

the user to a local copy.

Page 275: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 262

The jsp:param and jsp:params Elements

The jsp:param element is used with jsp:plugin in a manner similar to the way

that PARAM is used with APPLET, specifying a name and value that are

accessed from within the applet by getParameter. There are two main

differences, however. First, since jsp:param follows XML syntax, attribute

names must be lower case, attribute values must be enclosed in single or

double quotes, and the element must end with />, not just >. Second, all

jsp:param entries must be enclosed within a jsp:params elements.

So, for example, you would replace

<APPLET CODE="MyApplet.class"

WIDTH=475 HEIGHT=350>

<PARAM NAME="PARAM1" VALUE="VALUE1">

<PARAM NAME="PARAM2" VALUE="VALUE2">

</APPLET>

with

<jsp:plugin type="applet"

code="MyApplet.class"

width="475" height="350">

<jsp:params>

<jsp:param name="PARAM1" value="VALUE1" />

<jsp:param name="PARAM2" value="VALUE2" />

</jsp:params>

</jsp:plugin>

The jsp:fallback Element

The jsp:fallback element provides alternative text to browsers that do not

support OBJECT or EMBED. You use this element in almost the same way

as you would use alternative text placed within an APPLET element. So, for

example, you would replace

<APPLET CODE="MyApplet.class"

WIDTH=475 HEIGHT=350>

<B>Error: this example requires Java.</B>

</APPLET>

with

<jsp:plugin type="applet"

code="MyApplet.class"

Page 276: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 263

width="475" height="350">

<jsp:fallback>

<B>Error: this example requires Java.</B>

</jsp:fallback>

</jsp:plugin>

A jsp: plugin Example

Listing 13.8 shows a JSP page that uses the jsp:plugin element to generate

an entry for the Java 2 Plug-in.

Listing 13.8: PluginApplet.jsp

Listing 13.9 shows the code for the applet itself (which uses Swing, Java 2D

and the auxiliary classes of Listings 13.10 through 13.12). Figure 13.3

shows the result.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>Using jsp:plugin</TITLE>

<LINK REL=STYLESHEET

HREF="JSP-Styles.css"

TYPE="text/css">

</HEAD>

<BODY>

<CENTER>

<TABLE BORDER=5>

<TR><TH CLASS="TITLE">

Using jsp:plugin</TABLE>

<P>

<jsp:plugin type="applet"

code="PluginApplet.class"

width="370" height="420">

</jsp:plugin>

</CENTER></BODY></HTML>

Page 277: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 264

Listing 13.9: PluginApplet.java

Listing 13.10: TextPanel.java

import javax.swing.*;

/** An applet that uses Swing and Java 2D and thus requires

* the Java Plug-in.

*/

public class PluginApplet extends JApplet {

public void init() {

WindowUtilities.setNativeLookAndFeel();

setContentPane(new TextPanel());

}

}

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/** JPanel that places a panel with text drawn at various angles

* in the top part of the window and a JComboBox containing

* font choices in the bottom part.

*/

public class TextPanel extends JPanel

implements ActionListener {

private JComboBox fontBox;

private DrawingPanel drawingPanel;

public TextPanel() {

GraphicsEnvironment env =

GraphicsEnvironment.getLocalGraphicsEnvironment();

String[] fontNames = env.getAvailableFontFamilyNames();

fontBox = new JComboBox(fontNames);

setLayout(new BorderLayout());

JPanel fontPanel = new JPanel();

fontPanel.add(new JLabel("Font:"));

fontPanel.add(fontBox);

JButton drawButton = new JButton("Draw");

drawButton.addActionListener(this);

fontPanel.add(drawButton);

add(fontPanel, BorderLayout.SOUTH);

drawingPanel = new DrawingPanel();

fontBox.setSelectedItem("Serif");

drawingPanel.setFontName("Serif");

add(drawingPanel, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

drawingPanel.setFontName((String)fontBox.getSelectedItem());

drawingPanel.repaint(); } }

Page 278: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 265

Listing 13.11: DrawingPanel.java

Listing 13.12: WindowUtilities.java

import java.awt.*;

import java.awt.geom.*;

import javax.swing.*;

/** A window with text drawn at an angle. The font is

* set by means of the setFontName method.

*/

class DrawingPanel extends JPanel {

private Ellipse2D.Double circle =

new Ellipse2D.Double(10, 10, 350, 350);

private GradientPaint gradient =

new GradientPaint(0, 0, Color.red, 180, 180, Color.yellow, true);

// true means to repeat pattern

private Color[] colors = { Color.white, Color.black };

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D)g;

g2d.setPaint(gradient);

g2d.fill(circle);

g2d.translate(185, 185);

for (int i=0; i<16; i++) {

g2d.rotate(Math.PI/8.0);

g2d.setPaint(colors[i%2]);

g2d.drawString("jsp:plugin", 0, 0);

}

}

public void setFontName(String fontName) {

setFont(new Font(fontName, Font.BOLD, 35));

}

}

import javax.swing.*;

import java.awt.*;

/** A few utilities that simplify using windows in Swing. */

public class WindowUtilities {

/** Tell system to use native look and feel, as in previous releases. Metal (Java) LAF *is the

default otherwise. */

public static void setNativeLookAndFeel() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch(Exception e) { System.out.println("Error setting native LAF: " + e);

} }

... // See www.coreservlets.com for remaining code.

}

Page 279: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 266

Figure 13.3: Result of PluginApplet.jsp in Internet Explorer

with the JDK 1.4 plug-in.

Self Assessment Questions

6. _______ attributes specify empty space in pixels reserved on the left

and right of the applet.

7. _______ attribute specifies a name to use for interapplet communication

or for identifying the applet to scripting languages like JavaScript.

8. The__________ element provides alternative text to browsers that do

not support OBJECT or EMBED.

13.6 Summary

This unit has covered the following topics with respect to JSP File Inclusion.

The jsp: include Action

jsp:include, a portable mechanism that lets you insert any of the following

into the JSP output.

Page 280: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 267

Its main advantage is that it saves you from changing the main page when

the included pages change. Its main disadvantage is that since it includes

the output of the secondary page, not the secondary page’s actual code as

with the include directive, the included pages cannot use any JSP

constructs that affect the main page as a whole. The advantages generally

far outweigh the disadvantages, and you will almost certainly use it much

more than the other inclusion mechanisms.

include directive: The include directive is invoked at page translation time.

Its main advantage is that it is powerful: the included code can contain JSP

constructs such as field definitions and content-type settings that affect the

main page as a whole. Its main disadvantage is that it is hard to maintain:

you have to update the main page whenever any of the included pages

change.

Forwarding Requests with jsp: forward

jsp:forward to obtain the complete output from the auxiliary page. It is

recommend to completely avoid the use of jsp:forward. If you want to

perform a task a that randomly selects either page1.jsp or page2.jsp to

output.,use a Servlet and have it call the forward method of

RequestDispatcher.

Including Applets for the Java Plug-In

Applets are a very small part of the Java world, and the only major browser

that supports the Java 2 platform (i.e., JDK 1.2–1.4) is Netscape 6 and later.

So, developers thought of complex applets for corporate intranets, .class

files for applets need to go in the Web-accessible directories, not WEB-

INF/classes, because it is the browser, not the server that executes them.

13.7 Terminal Questions

1. What is the function of jsp: plugin element? What are the advantages of

it?

2. What is the difference between JSP: include and include directive?

3. What is the function of jsp: fallback element?

4. What is the function of flush Attribute?

5. What are the differences between jsp:param and jsp:params Elements?

Page 281: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 13

Sikkim Manipal University Page No.: 268

13.8 Answers

Self Assessment Questions

1. False

2. True

3. True

4. False

5. jsp:forward

6. hspace

7. name

8. jsp:fallback

Terminal Questions

1. jsp:plugin is used to insert applets that use the Java Plug-in into JSP

pages. Its main advantage is that it saves you from writing long, tedious,

and error-prone OBJECT and EMBED tags in your HTML. Its main

disadvantage is that it applies to applets, and applets are relatively

infrequently used. (Refer Section 13.1)

2. The fundamental difference between jsp:include and the include

directive is the time at which they are invoked: jsp:include is invoked at

request time, whereas the include directive is invoked at page

translation time. (Refer section 13.3)

3. The jsp: fallback element provides alternative text to browsers that do

not support OBJECT or EMBED. You use this element in almost the

same way as you would use alternative text placed within an APPLET

element.

4. Flush Attribute is optional. It specifies whether the output stream of the

main page should be flushed before the inclusion of the page (the

default is false). (Refer Section 13.2).

5. The jsp:param element is used with jsp:plugin in a manner similar to the

way that PARAM is used with APPLET, specifying a name and value

that are accessed from within the applet by get Parameter. There are

two main differences, however. First, since jsp: param follows XML

syntax, attribute names must be lower case, attribute values must be

enclosed in single or double quotes, and the element must end with />,

not just >. Second, all jsp: param entries must be enclosed within a jsp:

params element. (Refer section 13.2)

Page 282: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 269

Unit 14 Model View Controller Architecture

Structure:

14.1 Introduction

Objectives

14.2 Need for Model View Controller (MVC)

14.3 Implementing MVC with Request Dispatcher

14.4 Summarizing MVC Code

14.5 Interpreting Relative URLs in the Destination Page

14.6 MVC Applications

14.7 Forwarding Requests from JSP Pages

14.8 Including Pages

14.9 Summary

14.10 Terminal Questions

14.11 Answers

14.1 Introduction

In the previous unit you have learned about jsp:include action and include

directive. This unit describes how to combine Servlets and JSP pages.

Servlets are good at data processing: reading and checking data,

communicating with databases, invoking business logic, and so on. JSP

pages are good at presentation: building HTML to represent the results of

requests, to make best use of the strengths of each technology it is good to

combine Servlets and JSP pages.

Objectives:

After studying this unit, you should be able to:

explain the benefits of MVC

describe Request Dispatcher to implement MVC

explain Interpreting Relative URLs in the Destination Page

discuss on MVC Applications

explain how to forward requests from JSP pages

discuss on including pages instead of forwarding them

14.2 Need for Model View Controller (MVC)

Servlets are great when your application requires a lot of real programming

to accomplish its task. Servlets can manipulate HTTP status codes and

Page 283: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 270

headers, use cookies, track sessions, save information between requests,

compress pages, access databases, generate JPEG images on-the-fly, and

perform many other tasks flexibly and efficiently. But, generating HTML with

Servlets can be tedious and can yield a result that is hard to modify.

That’s where JSP comes in: as illustrated in Figure 14.1, JSP lets you

separate much of the presentation from the dynamic content. That way, you

can write the HTML in the normal manner, even using HTML-specific tools

and putting your Web content developers to work on your JSP documents.

JSP expressions, scriptlets, and declarations let you insert simple Java code

into the Servlet that results from the JSP page, and directives let you control

the overall layout of the page. For more complex requirements, you can

wrap Java code inside beans or even define your own JSP tags.

Simple application or small development

team.

Complex application

or large development

team.

Call Java Code Directly. Place all Java code in

JSP page. Appropriate only for very small amounts

of code.

Call Java Code Indirectly. Develop separate utility

classes. Insert into JSP page only the Java code

needed to invoke the utility classes.

Use Beans. Develop separate utility classes

structured as beans. Use jsp:useBean, jsp:get

roperty, and jsp:setProperty to invoke the code.

Use the MVC Architecture. Have a Servlet

respond to original request, look up data, and store

results in beans. Forward to a JSP page to present

results. JSP page uses beans.

Use the JSP Expression Language. Use

shorthand syntax to access and output object

properties. Usually used in conjunction with beans

and MVC.

Use Custom Tags. Develop tag handler classes.

Invoke the tag handlers with XML-like custom tags.

The assumption behind a JSP document is that it provides a single overall

presentation. What if you want to give totally different results depending on

the data that you receive? Scripting expressions, beans, and custom tags,

although extremely powerful and flexible, don’t overcome the limitation that

the JSP page defines a relatively fixed, top-level page appearance.

Page 284: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 271

Similarly, what if you need complex reasoning just to determine the type of

data that applies to the current situation? JSP is poor at this type of

business logic.

The solution is to use both Servlets and Java Server Pages. In this

approach, known as the Model View Controller (MVC) or Model 2

architecture, you let each technology concentrate on what it excels at. The

original request is handled by a Servlet. The Servlet invokes the business-

logic and data-access code and creates beans to represent the results

(that’s the model). Then, the Servlet decides which JSP page is appropriate

to present those particular results and forwards the request there (the JSP

page is the view). The Servlet decides what business logic code applies and

which JSP page should present the results (the Servlet is the controller).

MVC Frameworks

The key motivation behind the MVC approach is the desire to separate the

code that creates and manipulates the data from the code that presents the

data. The basic tools needed to implement this presentation-layer

separation are standard in the Servlet API and are the topic of this unit.

However, in very complex applications, a more elaborate MVC framework is

sometimes beneficial. The most popular of these frameworks is Apache

Struts. Although Struts is useful and widely used, you should not feel that

you must use Struts in order to apply the MVC approach. For simple and

moderately complex applications, implementing MVC from scratch with

Request Dispatcher is straightforward and flexible. Do not be intimidated: go

ahead and start with the basic approach.

In many situations, you will stick with the basic approach for the entire life of

your application. Even if you decide to use Struts or another MVC

framework later, you will recoup much of your investment because most of

your work will also apply to the elaborate frameworks.

Architecture or Approach?

The term “architecture” often connotes “overall system design.” Although

many systems are indeed designed with MVC at their core, it is not

necessary to redesign your overall system just to make use of the MVC

approach. It is quite common for applications to handle some requests with

Servlets, other requests with JSP pages, and still others with Servlets and

Page 285: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 272

JSP acting in conjunction as described in this unit. Do not feel that you have

to rework your entire system architecture just to use the MVC approach: go

ahead and start applying it in the parts of your application where it fits best.

Self Assessment Questions

1. The approach of Combining Servlets and Java Server Pages is known

as _________.

2 In MVC approach there is a separation between the code that creates

and manipulates the data from the code that presents the data

(True/False).

14.3 Implementing MVC with Request Dispatcher

The most important point about MVC is the idea of separating the business

logic and data access layers from the presentation layer. The syntax is quite

simple, and in fact you should be familiar with much of it already. Here is a

quick summary of the required steps; the following subsections supply

details.

Define Beans for Data Representation: Beans are just Java objects that

follow a few simple conventions. Your first step is defining beans to

represent the results that will be presented to the user.

Use Servlets for Request Handling: In most cases, the Servlet reads

request parameters.

Populate the Beans: The Servlet invokes business logic (application

specific code) or data-access code to obtain the results. Results are placed

in the beans that were defined in step 1.

Storing Beans in the Request, Session, or Servlet Context: The Servlet

calls set attribute on the request, session, or Servlet context objects to store

a reference to the beans that represent the results of the request.

Forward the Request to a JSP Page: The Servlet determines which JSP

page is appropriate to the situation and uses the forward method of Request

Dispatcher to transfer control to that page.

Extract the Data from the Beans: The JSP page accesses beans with jsp:

useBean and a scope matching the location of step 4. The page then uses

jsp: getProperty to output the bean properties. The JSP page does not

Page 286: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 273

create or modify the bean; it merely extracts and displays data that the

Servlet created.

Defining Beans to Represent the Data

Beans are Java objects that follow a few simple conventions. In this case,

since a Servlet or other Java routine (never a JSP page) will be creating the

beans, the requirement for an empty (zero-argument) constructor is waived.

So, your objects merely need to follow the normal recommended practices

of keeping the instance variables private and using accessory methods that

follow the get/set naming convention.

Since the JSP page will only access the beans, not create or modify them, a

common practice is to define value objects: objects that represent results

but have little or no additional functionality.

Writing Servlets to Handle Requests

Once the bean classes are defined, the next task is to write a Servlet to read

the request information. Since, with MVC, a Servlet responds to the initial

request, the normal approaches are used to read request parameters and

request headers, respectively.

Although Servlets use the normal techniques to read the request information

and generate the data, they do not use the normal techniques to output the

results. In fact, with the MVC approach the Servlets do not create any

output; the output is completely handled by the JSP pages. So, the Servlets

do not call response setContentType, response.getWriter, or out.println.

Populating the Beans

After you read the form parameters, you use them to determine the results

of the request. These results are determined in a completely application-

specific manner. You might call some business logic code, invoke an

Enterprise JavaBeans component, or query a database. No matter how you

come up with the data, you need to use that data to fill in the value object

beans that you defined in the first step.

Storing the Results

You have read the form information. You have created data specific to the

request. You have placed that data in beans. Now you need to store those

beans in a location that the JSP pages will be able to access.

Page 287: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 274

A Servlet can store data for JSP pages in three main places: in the

HttpServlet-Request, in the HttpSession, and in the ServletContext. These

storage locations correspond to the three non-default values of the scope

attribute of jsp:useBean: that is, request, session, and application.

Storing data that the JSP page will use only in this request.

First, the Servlets would create and store data as follows:

ValueObject value = new ValueObject(...);

request.setAttribute("key", value);

Next, the Servlets would forward the request to a JSP page that uses the

following to retrieve the data.

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="request" />

Note that request attributes have nothing to do with request parameters or

request headers. The request attributes are independent of the information

coming from the client; they are just application-specific entries in a hash

table that is attached to the request object. This table simply stores data in a

place that can be accessed by both the current Servlets and JSP page, but

not by any other resource or request.

Storing data that the JSP page will use in this request and in later

requests from the same client. First, the Servlets would create and

store data as follows:

ValueObject value = new ValueObject(...);

HttpSession session = request.getSession();

session.setAttribute("key", value);

Next, the Servlets would forward to a JSP page that uses the following

to retrieve the data:

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="session" />

Storing data that the JSP page will use in this request and in later

requests from any client. First, the Servlets would create and store

data as follows:

ValueObject value = new ValueObject(...);

getServletContext().setAttribute("key", value);

Page 288: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 275

Next, the Servlets would forward to a JSP page that uses the following

to retrieve the data:

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="application" />

The Servlets code is normally synchronized to prevent the data

changing between the Servlets and the JSP page.

Forwarding Requests to JSP Pages

You forward requests with the forward method of RequestDispatcher. You

obtain a RequestDispatcher by calling the getRequestDispatcher method of

ServletRequest, supplying a relative address. You are permitted to specify

addresses in the WEB-INF directory; clients are not allowed to directly

access files in WEB-INF, but the server is allowed to transfer control there.

Using locations in WEB-INF prevents clients from inadvertently accessing

JSP pages directly, without first going through the Servlets that create the

JSP data.

Note: If your JSP pages only make sense in the context of Servlets-

generated data, place the pages under the WEB-INF directory. That way,

Servlets can forward requests to the pages, but clients cannot access them

directly.

Once you have a Request Dispatcher, you use forward to transfer control to

the associated address. You supply the HttpServletRequest and

HttpServletResponse as arguments. Note that the forward method of

RequestDispatcher is quite different from the sendRedirect method of

HttpServletRequest. With forward, there is no extra response/request pair

as with sendRedirect. Thus, the URL displayed to the client does not

change when you use forward.

As an example, Listing 14.1 shows a portion of a Servlet that forwards the

request to one of three different JSP pages, depending on the value of the

operation request parameter.

Page 289: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 276

Listing 14.1: Request Forwarding Example

Forwarding to Static Resources

In most cases, you forward requests to JSP pages or other Servlets. In

some cases, however, you might want to send requests to static HTML

pages. In an e-commerce site, for example, requests indicating that the user

does not have a valid account name might be forwarded to an account

application page that uses HTML forms to HTML page, is perfectly legal and

requires no special syntax; just supply the address of the HTML page as the

argument to getRequestDispatcher.

However, since forwarded requests use the same request method as the

original request, POST requests cannot be forwarded to normal HTML

pages. The solution to this problem is to simply rename the HTML page to

have a .jsp extension. Renaming somefile.html to somefile.jsp does not

change its output for GET requests, but somefile.html cannot handle POST

requests, whereas somefile.jsp gives an identical response for both GET

and POST.

Redirecting Instead of Forwarding

The standard MVC approach is to use the forward method of

RequestDispatcher to transfer control from the Servlets to the JSP page.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String operation = request.getParameter("operation"); if (operation == null) { operation = "unknown"; } String address; if (operation.equals("order")) { address = "/WEB-INF/Order.jsp"; } else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp"; } else { address = "/WEB-INF/UnknownOperation.jsp"; } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); }

Page 290: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 277

However, when you are using session-based data sharing, it is sometimes

preferable to use response.sendRedirect.

Here is a summary of the behavior of forward.

Control is transferred entirely on the server. No network traffic is

involved.

The user does not see the address of the destination JSP page and

pages can be placed in WEB-INF to prevent the user from accessing

them without going through the Servlets that sets up the data. This is

beneficial if the JSP page makes sense only in the context of Servlet

generated data.

Here is a summary of sendRedirect.

Control is transferred by sending the client a 302 status code and a

Location response header. Transfer requires an additional network

round trip.

The user sees the address of the destination page and can bookmark it

and access it independently. This is beneficial if the JSP is designed to

use default values when data is missing. For example, this approach

would be used when redisplaying an incomplete HTML form or

summarizing the contents of a shopping cart. In both cases, previously

created data would be extracted from the user’s session, so the JSP

page makes sense even for requests that do not involve the Servlets.

Extracting Data from Beans

Once the request arrives at the JSP page, the JSP page uses jsp:useBean

and jsp:getProperty to extract the data.

The JSP page never creates the objects. The Servlet, not the JSP

page, should create all the data objects. So, to guarantee that the JSP

page will not create objects, you should use

<jsp:useBean ... type="package.Class" />

instead of

<jsp:useBean ... class="package.Class" />.

The JSP page should not modify the objects. So, you should use

jsp:getProperty but not jsp:setProperty.

Page 291: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 278

The scope you specify should match the storage location used by the

Servlet. For example, the following three forms would be used for request-,

session-, and application-based sharing, respectively.

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="request" />

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="session" />

<jsp:useBean id="key" type="somePackage.SomeBeanClass"

scope="application" />

Self Assessment Questions

3. In MVC there is a separation between the business logic and data

access layers from the _________ layer.

4. The standard MVC approach is to use the forward method of ________

to transfer control from the Servlets to the JSP page.

14.4 Summarizing MVC Code

This section summarizes the code that would be used for request-based,

session-based, and application-based MVC approaches.

Request-Based Data Sharing

With request-based sharing, the Servlet stores the beans in the HttpServlet-

Request, where they are accessible only to the destination JSP page.

Servlet

ValueObject value = new ValueObject(...);

request.setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="request" />

<jsp:getProperty name="key" property="someProperty" />

Page 292: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 279

Session-Based Data Sharing

With session-based sharing, the Servlet stores the beans in the

HttpSession, where they are accessible to the same client in the destination

JSP page or in other pages.

Servlet

ValueObject value = new ValueObject(...);

HttpSession session = request.getSession();

session.setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="session" />

<jsp:getProperty name="key" property="someProperty" />

Application-Based Data Sharing

With application-based sharing, the Servlet stores the beans in the Servlet-

Context, where they are accessible to any Servlet or JSP page in the Web

application. To guarantee that the JSP page extracts the same data that the

Servlet inserted, you should synchronize your code as below.

Servlet

synchronized(this) {

ValueObject value = new ValueObject(...);

getServletContext().setAttribute("key", value);

RequestDispatcher dispatcher =

request.getRequestDispatcher("/WEB-INF/SomePage.jsp");

dispatcher.forward(request, response);

}

JSP Page

<jsp:useBean id="key" type="somePackage.ValueObject"

scope="application" />

<jsp:getProperty name="key" property="someProperty" />

Page 293: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 280

14.5 Interpreting Relative URLs in the Destination Page

Although a Servlets can forward the request to an arbitrary location on the

same server, the process is quite different from that of using the

sendRedirect method of HttpServletResponse. First, sendRedirect requires

the client to reconnect to the new resource, whereas the forward method of

RequestDispatcher is handled completely on the server. Second,

sendRedirect does not automatically preserve all of the request data;

forward does. Third, sendRedirect results in a different final URL, whereas

with forward, the URL of the original Servlets is maintained.

This final point means that if the destination page uses relative URLs for

images or style sheets, it needs to make them relative to the Servlets URL

or the server root, not to the destination page’s actual location.

For example, consider the following style sheet entry:

<LINK REL=STYLESHEET

HREF="my-styles.css"

TYPE="text/css">

If the JSP page containing this entry is accessed by means of a forwarded

request, my-styles.css will be interpreted relative to the URL of the

originating Servlets, not relative to the JSP page itself, almost certainly

resulting in an error. The simplest solution to this problem is to give the full

server path to the style sheet file, as follows.

<LINK REL=STYLESHEET

HREF="/path/my-styles.css"

TYPE="text/css">

The same approach is required for addresses used in <IMG SRC=...>

and <A HREF=...>.

Self Assessment Questions

5. The sendRedirect method results in a different final URL, whereas with

forward method, the URL of the original Servlets is maintained

(True/False).

6. To guarantee that the JSP page extracts the same data that the Servlet

inserted, Synchronization code should be used. (True/False).

Page 294: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 281

14.6 MVC Applications

In this section, we apply the MVC approach to an application that displays

bank account balances. The controller Servlet (Listing 14.2) reads a

customer ID and passes that to some data-access code that returns a Bank

Customer value bean (Listing 14.3).

Listing 14.2: ShowBalance.java

Listing 14.3 BankCustomer.java

package coreservlets;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/** Servlet that reads a customer ID and displays

* information on the account balance of the customer

* who has that ID.

*/

public class ShowBalance extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

BankCustomer customer =

BankCustomer.getCustomer(request.getParameter("id"));

String address;

if (customer == null) {

address = "/WEB-INF/bank-account/UnknownCustomer.jsp";

} else if (customer.getBalance() < 0) {

address = "/WEB-INF/bank-account/NegativeBalance.jsp";

request.setAttribute("badCustomer", customer);

} else if (customer.getBalance() < 10000) {

address = "/WEB-INF/bank-account/NormalBalance.jsp";

request.setAttribute("regularCustomer", customer);

} else {

address = "/WEB-INF/bank-account/HighBalance.jsp";

request.setAttribute("eliteCustomer", customer);

}

RequestDispatcher dispatcher =

request.getRequestDispatcher(address);

dispatcher.forward(request, response);

}

}

Page 295: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 282

Listing 14.3: BankCustomer.jsp

The Servlets then stores the bean in the HttpServletRequest object where it

will be accessible from destination JSP pages but nowhere else. If the

account balance of the resulting customer is negative, the Servlets forwards

to a page designed for delinquent customers (Listing 14.4, Figure 14.2).

package coreservlets; import java.util.*; /** Bean to represent a bank customer. */ public class BankCustomer { private String id, firstName, lastName; private double balance; public BankCustomer(String id, String firstName, String lastName, double balance) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.balance = balance; } public String getId() { return(id); } public String getFirstName() { return(firstName); } public String getLastName() { return(lastName); } public double getBalance() { return(balance); } public double getBalanceNoSign() { return(Math.abs(balance)); } public void setBalance(double balance) { this.balance = balance; } // Makes a small table of banking customers. private static HashMap customers; static { customers = new HashMap(); customers.put("id001", new BankCustomer("id001", "John", "Hacker",-3456.78)); customers.put("id002",new BankCustomer("id002","Jane","Hacker",1234.56)); customers.put("id003", new BankCustomer("id003","Juan","Hacker",987654.32)); } /** Finds the customer with the given ID. * Returns null if there is no match. */ public static BankCustomer getCustomer(String id) { return((BankCustomer)customers.get(id)); } }

Page 296: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 283

Listing 14.4: NegativeBalance.jsp

Fig. 14.2: The Show Customer Servlet with an ID corresponding to a

customer with a negative balance.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>You Owe Us Money!</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> We Know Where You Live!</TABLE> <P> <IMG SRC="/bank-support/Club.gif" ALIGN="LEFT"> <jsp:useBean id="badCustomer" type="coreservlets.BankCustomer" scope="request" /> Watch out, <jsp:getProperty name="badCustomer" property="firstName" />, we know where you live. <P> Pay us the $<jsp:getProperty name="badCustomer" property="balanceNoSign" /> you owe us before it is too late! </BODY></HTML>

Page 297: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 284

If the customer has a positive balance of less than $10,000, the Servlets

transfers to the standard balancedisplay page (Listing 14.5, Figure 14.3).

Listing 14.5: NormalBalance.jsp

Fig. 14.3: The ShowCustomer Servlet with an ID corresponding to a customer

with a normal balance.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Your Balance</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Your Balance</TABLE> <P> <IMG SRC="/bank-support/Money.gif" ALIGN="RIGHT"> <jsp:useBean id="regularCustomer" type="coreservlets.BankCustomer" scope="request" />

<UL> <LI>First name: <jsp:getProperty name="regularCustomer" property="firstName" /> <LI>Last name: <jsp:getProperty name="regularCustomer" property="lastName" /> <LI>ID: <jsp:getProperty name="regularCustomer" property="id" /> <LI>Balance: $<jsp:getProperty name="regularCustomer" property="balance" /> </UL></BODY></HTML>

Page 298: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 285

if the customer has a balance of $10,000 or more, the Servlets forwards the

request to a page reserved for elite customers (Listing 14.6, Figure 14.4).

Listing 14.6: HighBalance.jsp

Fig. 14.4: The ShowCustomer Servlet with an ID corresponding to a customer

with a high balance.

<HTML> <HEAD> <TITLE>Your Balance</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Your Balance</TABLE> <P> <CENTER><IMG SRC="/bank-support/Sailing.gif"></CENTER> <BR CLEAR="ALL"> <jsp:useBean id="eliteCustomer" type="coreservlets.BankCustomer" scope="request" />

It is an honor to serve you, <jsp:getProperty name="eliteCustomer" property="firstName" /> <jsp:getProperty name="eliteCustomer" property="lastName" />!

<P> Since you are one of our most valued customers, we would like to offer you the opportunity to spend a mere fraction of your $<jsp:getProperty name="eliteCustomer" property="balance" />

on a boat worthy of your status. Please visit our boat store for more information. </BODY></HTML>

Page 299: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 286

Finally, if the customer ID is unrecognized, an error page is displayed

(Listing 14.7, Figure 14.5).

Listing 14.7: UnknownCustomer.jsp

Fig. 14.5: The ShowCustomer Servlet with an unknown customer ID.

14.7 Forwarding Requests from JSP Pages

The most common request-forwarding scenario is one in which the request

first goes to a Servlet and the Servlet forwards the request to a JSP page.

The reason a Servlet usually handles the original request is that checking

request parameters and setting up beans requires a lot of programming, and

it is more convenient to do this programming in a Servlet than in a JSP

document. The reason that the destination page is usually a JSP document

is that JSP simplifies the process of creating the HTML content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Unknown Customer</TITLE> <LINK REL=STYLESHEET HREF="/bank-support/JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> Unknown Customer</TABLE> <P> Unrecognized customer ID. </BODY></HTML>

Page 300: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 287

However, just because this is the usual approach doesn’t mean that it is the

only way of doing things. It is certainly possible for the destination page to

be a Servlet. Similarly, it is quite possible for a JSP page to forward

requests elsewhere. For example, a request might go to a JSP page that

normally presents results of a certain type and that forwards the request

elsewhere only when it receives unexpected values.

Sending requests to Servlets instead of JSP pages requires no changes

whatsoever in the use of the RequestDispatcher. However, there is special

syntactic support for forwarding requests from JSP pages. In JSP, the

jsp:forward action is simpler and easier to use than wrapping

RequestDispatcher code in a scriptlet.

This action takes the following form:

<jsp:forward page="Relative URL" />

The page attribute is allowed to contain JSP expressions so that the

destination can be computed at request time. For example, the following

code sends about half the visitors to http://host/examples/page1.jsp and the

others to http://host/examples/page2.jsp.

<% String destination;

if (Math.random() > 0.5) {

destination = "/examples/page1.jsp";

} else {

destination = "/examples/page2.jsp";

}

%>

<jsp:forward page="<%= destination %>" />

The jsp:forward action, like jsp:include, can make use of jsp:param elements

to supply extra request parameters to the destination page.

Self Assessment Question

7. Sending requests to Servlets instead of JSP pages requires changes in

the use of the RequestDispatcher. (True/False).

Page 301: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 288

14.9 Summary

Need for MVC

As you move from simple applications to complex applications there is a

need to use both Servlets and Java Server Pages. This approach is known

as the Model View Controller (MVC) or Model 2 architecture

Implementing MVC with Request Dispatcher

The most important point about MVC is the idea of separating the business

logic and data access layers from the presentation layer.

Summarizing MVC Code

This section summarizes the code that would be used for request-based,

session-based, and application-based MVC approaches

Interpreting Relative URLs in the Destination Page

Servlets can forward the request to an arbitrary location on the same server,

the process is described in three steps. First, sendRedirect requires the

client to reconnect to the new resource, whereas the forward method of

Request Dispatcher is handled completely on the server. Second,

sendRedirect does not automatically preserve all of the request data;

forward does. Third, sendRedirect results in a different final URL.

Forwarding Requests from JSP Pages

The most common request-forwarding scenario is one in which the request

first goes to a Servlet and the Servlet forwards the request to a JSP page. A

Servlet usually handles the original request is that checking request

parameters and setting up beans requires a lot of programming, and it is

more convenient to do this programming in a Servlet than in a JSP

document.

14.10 Terminal Questions

1. What is Model 2 architecture?

2. What is the necessity to write Servlets to Handle Requests?

3. Describe Interpreting Relative URLs in the Destination Page.

4. Explain the concept of Forwarding Requests from JSP Pages.

Page 302: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 289

14.11 Answers

Self Assessment Questions

1. Model View Controller (MVC) or Model 2 architecture,

2. True

3. Presentation

4. RequestDispatcher

5. True

6. True

7. False

Terminal Questions

1. As you move from simple applications to complex applications there is a

need to use both Servlets and Java Server Pages. This approach is

known as the Model View Controller (MVC) or Model 2 architecture

(Refer Section 14.1).

2. Since, with MVC, a Servlet responds to the initial request, the normal

approaches are used to read request parameters and request headers,

respectively. Servlets use the normal techniques to read the request

information and generate the data, they do not use the normal

techniques to output the results. (Refer Section 14.3).

3. Servlets can forward the request to an arbitrary location on the same

server, the process is described in three steps. First, sendRedirect

requires the client to reconnect to the new resource, whereas the

forward method of RequestDispatcher is handled completely on the

server. Second, sendRedirect does not automatically preserve all of the

request data; forward does. Third, sendRedirect results in a different

final URL.

4. The most common request-forwarding scenario is one in which the

request first goes to a Servlet and the Servlet forwards the request to a

JSP page. The reason a Servlet usually handles the original request is

that checking request parameters and setting up beans requires a lot of

programming, and it is more convenient to do this programming in a

Servlet than in a JSP document. The reason that the destination page is

usually a JSP document is that JSP simplifies the process of creating

the HTML content. (Refer Section 14.7).

Page 303: BT 0083 Server Side Programming Theory Contentsbscit2012.weebly.com/uploads/1/2/8/0/12803720/bt0083.pdf · Unit 1: Understanding Java Enterprise Edition Platform This unit discusses

Server Side Programming – Theory Unit 14

Sikkim Manipal University Page No.: 290

Acknowledgements, References and Suggested Readings:

1) Armstrong, E., Ball, J. et al. The J2EE™ 1.4 Tutorial.

2) Bergsten, H. (2000). Java Server Pages, First Edition. O'Reilly.

3) Farley, J. Java Distributed Computing. O'Reilly.

4) Harold, E. and Means, W.S. XML in a Nutshell. O'Reilly.

5) Hunter, J. and Crawford, W. (1998). Java Servlet Programming, First

edition. O'Reilly.

6) McLaughlin, B. Java and XML. O'Reilly.

7) Neimeyer, P. and Knudsen, J. Learning Java (formerly Exploring Java).

O'Reilly.

Web Sites:

1) Go through Sun Java™ System Application Server Platform Edition 8

Developer’s Guide at http://docs.sun.com/db/doc/817-6087 for

information about developer features of the Application Server.

2) Go through Sun Java™ System Application Server Platform Edition 8

Administration Guide at http://docs.sun.com/db/doc/817-6088 for

information about administering the Application Server.

3) Oracle, JDeveloper http://www.oracle.com/java/

A development environment for Java-based database applications with

support for JSP-based user interfaces.

4) VisualAge for Java (IBM), http://www-4.ibm.com/software/ad/vajava/

An IDE with support for servlet and JSP debugging as well as a wizard

for generation of template code. Available for Windows and Linux.

5) Tomcat (Apache Software Foundation), http://jakarta.apache.org

Tomcat is the official reference implementation for the Servlet and JSP

specifications, developed as an open source product in the Apache

Jakarta project.