Server side programming with Java Servlet:

yoinkscreechedInternet and Web Development

Nov 13, 2013 (3 years and 11 months ago)

58 views

Server side programming with Java Servlet:


What is Java Servlet

Servlets are server side components that provide a powerful mechanism
for developing server side programs. Servlets

provide component
-
based,
platform
-
independent methods for building Web
-
based applications,
without the performance limitations of CGI programs. Unlike
proprietary server extension mechanisms (such as the Netscape Server
API or Apache modules), servlets ar
e server as well as platform
-
independent. This leaves you free to select a "best of breed" strategy for
your servers, platforms, and tools.

Using servlets web developers can
create fast and efficient server side application which can run on any
servlet ena
bled web server. Servlets run entirely inside the Java Virtual
Machine. Since the Servlet runs at server side so it does not checks the
browser for compatibility. Servlets can access the entire family of Java
APIs, including the JDBC API to access enterpri
se databases. Servlets
can also access a library of HTTP
-
specific calls, receive all the benefits
of the mature java language including portability, performance,
reusability, and crash protection. Today servlets are the popular choice
for building interact
ive web applications. Third
-
party servlet containers
are available for Apache Web Server, Microsoft IIS, and others. Servlet
containers are usually the components of web and application servers,
such as BEA WebLogic Application Server, IBM WebSphere, Sun J
ava
System Web Server, Sun Java System Application Server and others.

Servlets are not designed for a specific protocols. It is different thing that
they are most commonly used with the HTTP protocols Servlets uses the
classes in the java packages javax.se
rvlet and javax.servlet.http. Servlets
provides a way of creating the sophisticated server side extensions in a
server as they follow the standard framework and use the highly portable
java language.

HTTP Servlet typically used to:



Priovide dynamic content

like getting the results of a database
query and returning to the client.



Process and/or store the data submitted by the HTML.



Manage information about the state of a stateless HTTP. e.g. an
online shopping car manages request for multiple concurrent
cust
omers.

Introduction to Server Side Programming








All of us (or most of us) would have started programming in Java with
the ever famous ?Hello World!? program. If you can recollect, we saved
this file with a .java extension and later compiled the program using
javac and then executed the class file with j
ava. Apart from introducing
you to the language basics, the point to be noted about this program is
that ? ?It is a client side program?. This means that you write, compile
and also execute the program on a client machine (e.g. Your PC). No
doubt, this is
the easiest and fastest way to write, compile and execute
programs. But, it has little practical significance when it comes to real
world programming.

1.

Why Server Side Programming?


Though it is technically feasible to implement almost any business
logic using client side programs, logically or functionally it carries
no ground when it comes to enterprise applications (e.g. banking,
air ticketing, e
-
shopping etc.). To further explain,

going by the
client
side programming logic; a bank having 10,000 customers
would mean that each customer should have a copy of the
program(s) in his or her PC which translates to 10,000 programs!
In addition, there are issues like security, resource pooli
ng,
concurrent access and manipulations to the database which simply
cannot be handled by client side programs. The answer to most of
the issues cited above is ? ?Server Side Programming?. Figure
-
1
illustrates Server side architecture in the simplest terms
.



2.

Advantages of Server Side Programs


The list below highlights some of the important advantages of
Server Side programs.

i.

All programs reside in one machine called the Server. Any
number of remote machines (called clients) can access the
server programs
.

ii.

New functionalities to existing programs can be added at the
server side which the clients? can advantage without having
to change anything from their side.

iii.

Migrating to newer versions, architectures, design patterns,
adding patches, switching to new dat
abases can be done at
the server side without having to bother about clients?
hardware or software capabilities.

iv.

Issues relating to enterprise applications like resource
management, concurrency, session management, security and
performance are managed by s
ervice side applications.

v.

They are portable and possess the capability to generate
dynamic and user
-
based content (e.g. displaying transaction
information of credit card or debit card depending on user?s
choice).


3.

Types of Server Side Programs

i.

Active Serve
r Pages (ASP)

ii.

Java Servlets

iii.

Java Server Pages (JSPs)

iv.

Enterprise

Java Beans (EJBs)

v.

PHP

To summarize, the objective of server side programs is to centrally
manage all programs relating to a particular application (e.g.
Banking, Insurance, e
-
shopping, etc). Clients with bare minimum
requirement (e.g. Pentium II, Windows XP Professional, MS
Int
ernet Explorer and an internet connection) can experience the
power and performance of a Server (e.g. IBM Mainframe, Unix
Server, etc) from a remote location without having to compromise
on security or speed. More importantly, server programs are not
only
portable but also possess the capability to generate dynamic
responses based on user?s request.




Introduction to Java Servlets








Java Servlets

are server side Java programs that require either a Web
Server or an Application Server for execution. Examples for Web
Servers include Apache?s Tomcat Server and Macromedia?s JRun. Web
Servers include IBM?s Weblogic and BEA?s Websphere server.
Examples f
or other Server programs include Java Server Pages (JSPs)
and Enterprise Java Beans (EJBs). In the forthcoming sections, we will
get acquainted with Servlet fundamentals and other associated
information required for creating and executing Java Servlets.

1.

Ba
sic Servlet Structure





As seen earlier, Java servlets are server side programs or to be
more specific; web applications that run on servers that comply
HTTP protocol. The javax.servlet and javax.servlet.http packages
provide the necessary interfaces and

classes to work with servlets.
Servlets generally extend the HttpServlet class and override the
doGet or the doPost methods. In addition, other methods such as
init, service and destroy also called as life cycle methods might be
used which will be discuss
ed in the following section. The skeleton
of a servlet is given in Figure





2.

A Servlet?s Life Cycle

The first time a servlet is invoked, it is the init method which is
called. And remember that this is called only once during the
lifetime of a servlet. S
o, you can put all your initialization code
here. This method next calls the service method. The service
method in turn calls the doGet or doPost methods (whichever the
user has overridden). Finally, the servlet calls the destroy method.
It is in a sense e
quivalent to the finally method. You can reset or
close references / connections done earlier in the servlet?s methods
(e.g. init, service or doGet /doPost). After this method is called, the
servlet ceases to exist for all practical purposes. However, plea
se
note that it is not mandatory to override all these methods. More
often than not, it is the doGet or doPost method used with one or
more of the other life cycle methods.



3.

A Servlet Program









Output Screens


To appreciate the execution of the
servlet life cycle methods, keep
refreshing the browser (F5 in Windows). In the background, what
actually happens is ? with each refresh, the doGet method is called
which increments i?s value and displays the current value. Find
below the screen shots (Fig
ures 5 through 7) captured at random
intervals. The procedure to run the servlets using a Web Server
will be demonstrated in the next section (1.3.).










HTTP Servlet Basics 2. 2:

This chapter provides a quick introduction to some of the things an
HTTP servlet

can do. For example, an HTTP servlet can generate an HTML page,
either when

the servlet is accessed explicitly by name, by following a hypertext link,
or as the

result of a fo
rm submission. An HTTP servlet can also be embedded
inside an

HTML page, where it functions as a server
-
side include. Servlets can be
chained

together to produce complex effects

one common use of this technique
is for

filtering content. Finally, snippets o
f servlet code can be embedded
directly in

HTML pages using a new technique called JavaServer Pages.

Although the code for each of the examples in this chapter is available
for download

(as described in the Preface), we would suggest that for these first
e
xamples

you deny yourself the convenience of the Internet and type in the
examples. It

should help the concepts seep into your brain.

Don’t be alarmed if we seem to skim lightly over some topics in this
chapter. Servlets

are powerful and, at times, complic
ated. The point here is to give you a

general overview of how things work, before jumping in and
overwhelming you

with all of the details. By the end of this book, we promise that you’ll be
able to

write servlets that do everything but make tea.

HTTP Basic
s

Before we can even show you a simple HTTP servlet, we need to make
sure that

you have a basic understanding of how the protocol behind the Web,
HTTP,

works. If you’re an experienced CGI programmer (or if you’ve done any
serious

server
-
side web
programming), you can safely skip this section. Better
yet, you

might skim it to refresh your memory about the finer points of the GET
and POST

methods. If you are new to the world of server
-
side web programming,
however,

you should read this material care
fully, as the rest of the book is going to
assume

that you understand HTTP. For a more thorough discussion of HTTP
and its

methods, see
Web Client Programming
by Clinton Wong (O’Reilly).

Requests, Responses, and Headers

HTTP is a simple, stateless protocol
. A client, such as a web browser,
makes a

request, the web server responds, and the transaction is done. When the
client

sends a request, the first thing it specifies is an HTTP command, called a
method
,

that tells the server the type of action it wants p
erformed. This first line
of the

request also specifies the address of a document (a URL) and the version
of the

HTTP protocol it is using. For example:

GET /intro.html HTTP/1.0

This request uses the GET method to ask for the document named
intro.html
,

usi
ng HTTP Version 1.0. After sending the request, the client can send
optional

header information to tell the server extra information about the request,
such as

what software the client is running and what content types it
understands. This

information does
n’t directly pertain to what was requested, but it could
be used by

the server in generating its response. Here are some sample request
headers:

User
-
Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)

Accept: image/gif, image/jpeg, text/*, */*

The User
-
Agent header provides information about the client software,
while the

Accept header specifies the media (MIME) types that the client prefers
to accept.

(We’ll talk more about request headers in the context of servlets in
Chapter 4,

Retrieving Information
.
) After the headers, the client sends a blank line,
to indicate

the end of the header section. The client can also send additional data, if
appropriate

for the method being used, as it is with the POST method that we’ll
discuss

shortly. If the request
doesn’t send any data, it ends with an empty line.

After the client sends the request, the server processes it and sends back
a

response. The first line of the response is a status line that specifies the
version of

the HTTP protocol the server is using, a

status code, and a description of
the

status code. For example:

HTTP/1.0 200 OK

This status line includes a status code of 200, which indicates that the
request was

successful, hence the description “OK”. Another common status code is
404, with

the descri
ption “Not Found”

as you can guess, this means that the
requested

document was not found. Chapter 5,
Sending HTML Information
,
discusses

common status codes and how you can use them in servlets, while
Appendix C,

HTTP Status Codes
, provides a complete list

of HTTP status codes.

After the status line, the server sends response headers that tell the client
things

like what software the server is running and the content type of the
server’s

response. For example:

Date: Saturday, 23
-
May
-
98 03:25:12 GMT

Server:
JavaWebServer/1.1.1

MIME
-
version: 1.0

Content
-
type: text/html

Content
-
length: 1029

Last
-
modified: Thursday, 7
-
May
-
98 12:15:35 GMT

The Server header provides information about the server software, while
the

Content
-
type header specifies the MIME type of the

data included with
the

response. (We’ll also talk more about response headers in Chapter 5.)
The server

sends a blank line after the headers, to conclude the header section. If the
request

was successful, the requested data is then sent as part of the res
ponse.
Otherwise,

the response may contain human
-
readable data that explains why the
server

couldn’t fulfill the request.

GET and POST

When a client connects to a server and makes an HTTP request, the
request can

be of several different types, called
methods. The most frequently used
methods

are GET and POST. Put simply, the GET method is designed for getting
information

(a document, a chart, or the results from a database query), while the
POST

method is designed for posting information (a credit card

number, some
new

chart data, or information that is to be stored in a database). To use a
bulletin

board analogy, GET is for reading and POST is for tacking up new
material.

The GET method, although it’s designed for reading information, can
include as

pa
rt of the request some of its own information that better describes
what to get


such as an x, y scale for a dynamically created chart. This information is
passed as a

sequence of characters appended to the request URL in what’s called a
query string
.

Plac
ing the extra information in the URL in this way allows the page to
be bookmarked

or emailed like any other. Because GET requests theoretically shouldn’t

need to send large amounts of information, some servers limit the length
of URLs

and query strings to
about 240 characters.

The POST method uses a different technique to send information to the
server

because in some cases it may need to send megabytes of information. A
POST

request passes all its data, of unlimited length, directly over the socket
connect
ion

as part of its HTTP request body. The exchange is invisible to the client.
The URL

doesn’t change at all. Consequently, POST requests cannot be
bookmarked or

emailed or, in some cases, even reloaded. That’s by design

information
sent to

the server, suc
h as your credit card number, should be sent only once.

In practice, the use of GET and POST has strayed from the original
intent. It’s

common for long parameterized requests for information to use POST
instead of

GET to work around problems with
overly
-
long URLs. It’s also
common for simple

forms that upload information to use GET because, well

why not, it
works!

Generally, this isn’t much of a problem. Just remember that GET
requests,

because they can be bookmarked so easily, should not be allowe
d to
cause damage

for which the client could be held responsible. In other words, GET
requests

should not be used to place an order, update a database, or take an
explicit client

action in any way.

Other Methods

In addition to GET and POST, there are sever
al other lesser
-
used HTTP
methods.

There’s the HEAD method, which is sent by a client when it wants to
see only the

headers of the response, to determine the document’s size, modification
time, or

general availability. There’s also PUT, to place documents
directly on
the server,

and DELETE, to do just the opposite. These last two aren’t widely
supported due

to complicated policy issues. The TRACE method is used as a
debugging aid

it

returns to the client the exact contents of its request. Finally, the
OPTIO
NS

method can be used to ask the server which methods it supports or what
options

are available for a particular resource on the server.

The Servlet API

Now that you have a basic understanding of HTTP, we can move on and
talk about

the Servlet API that you
’ll be using to create HTTP servlets, or any kind
of servlets,

for that matter. Servlets use classes and interfaces from two packages:
javax.

servlet and javax.servlet.http. The javax.servlet package contains

classes to support generic, protocol
-
independen
t servlets. These classes
are

extended by the classes in the javax.servlet.http package to add
HTTPspecific

functionality. The top
-
level package name is javax instead of the
familiar

java, to indicate that the Servlet API is a standard extension.

Every ser
vlet must implement the javax.servlet.Servlet interface. Most
servlets

implement it by extending one of two special classes: javax. servlet.

GenericServlet or javax.servlet.http.HttpServlet. A protocol
-
independent

servlet should subclass GenericServlet
, while an HTTP servlet should

subclass HttpServlet, which is itself a subclass of GenericServlet with
added

HTTP
-
specific functionality.

Unlike a regular Java program, and just like an applet, a servlet does not
have a

main() method. Instead, certain meth
ods of a servlet are invoked by the
server in

the process of handling requests. Each time the server dispatches a
request to a

servlet, it invokes the servlet’s service() method.

A generic servlet should override its service() method to handle requests
as

appropriate for the servlet. The service() method accepts two
parameters: a

request object and a response object. The request object tells the servlet
about the

request, while the response object is used to return a response. Figure 2
-
1 shows

how a generic

servlet handles requests.


Figure 2
-
1. A generic servlet handling a request


In contrast, an HTTP servlet usually does not override the service()
method.

Instead, it overrides doGet() to handle GET requests and doPost() to
handle

POST requests. An HTTP s
ervlet can override either or both of these
methods,

depending on the type of requests it needs to handle. The service()
method of

HttpServlet handles the setup and dispatching to all the do
XXX
()
methods,

which is why it usually should not be overridden. F
igure 2
-
2 shows how
an HTTP

servlet handles GET and POST requests.


Figure 2
-
2. An HTTP servlet handling GET and POST requests


An HTTP servlet can override the doPut() and doDelete() methods to
handle

PUT and DELETE requests, respectively. However, HTTP
servlets
generally don’t

touch doHead(), doTrace(), or doOptions(). For these, the default
implementations

are almost always sufficient.

The remainder in the javax.servlet and javax.servlet.http packages are

largely support classes. For example, the Servle
tRequest and
ServletResponse

classes in javax.servlet provide access to generic server requests and

responses, while HttpServletRequest and HttpServletResponse in javax.

servlet.http provide access to HTTP requests and responses. The javax.

servlet.http pa
ckage also contains an HttpSession class that provides
built
-
in

session tracking functionality and a Cookie class that allows you to
quickly set up

and process HTTP cookies.










Life cycle of Servlet








The life cycle of a servlet

can be categorized into four parts:

1.

Loading and Inatantiation:

The servlet container loads the
servlet during startup or when the first request is made. The
loading of the servlet depends on the attribute <load
-
on
-
startup> of
web.xml file. If the attribut
e <load
-
on
-
startup> has a positive value
then the servlet is load with loading of the container otherwise it
load when the first request comes for service. After loading of the
servlet, the container creates the instances of the servlet.

2.

Initialization:

Af
ter creating the instances, the servlet container
calls the init() method and passes the servlet initialization
parameters to the init() method. The init() must be called by the
servlet container before the servlet can service any request. The
initializati
on parameters persist untill the servlet is destroyed. The
init() method is called only once throughout the life cycle of the
servlet.


The servlet will be available for service if it is loaded successfully
otherwise the servlet container unloads the servl
et.

3.

Servicing the Request:

After successfully completing the
initialization process, the servlet will be available for service.
Servlet creates seperate threads for each request. The sevlet
container calls the service() method for servicing any request. Th
e
service() method determines the kind of request and calls the
appropriate method (doGet() or doPost()) for handling the request
and sends response to the client using the methods of the response
object.

4.

Destroying the Servlet:

If the servlet is no longer

needed for
servicing any request, the servlet container calls the destroy()
method . Like the init() method this method is also called only
once throughout the life cycle of the servlet. Calling the destroy()
method indicates to the servlet container not
to sent the any request
for service and the servlet


releases all the resources associated
with it. Java Virtual Machine claims for the memory associated
with the resources for garbage collection.




Life Cycle of a Servlet

Methods of Servlets








A Generic servlet contains the following five methods:

init()


public void init(ServletConfig config) throws ServletException

The

init() method

is called only once by the servlet container
throughout the life of a servlet. By this init() method the servlet

get to
know that it has been placed into service.


The servlet cannot be put into the service if




The init() method does not return within a fix time set by the web
server.





It throws a ServletException

Parameters
-

The init() method takes

a

ServletConfig

object that
contains the initialization parameters and servlet's configuration and
throws a

ServletException

if an exception has occurred.


service()


public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOExc
eption


Once the servlet starts getting the requests, the service() method is called
by the servlet container to respond. The servlet services the client's
request with the help of two objects. These two
objects
javax.servlet.ServletRequest

and


javax.servlet.ServletRespon
se

are passed by the servlet container.




The status code of the response always should be set for a servlet that
throws or sends an error.


Parameters
-


The service() method takes

the ServletRequest

object that
contains the cl
ient's request and the object

ServletResponse

contains the
servlet's response. The service() method throws
ServletException and
IOExceptions

exception.



getServletConfig()


public ServletConfig getServletConfig()


This method contains parameters for initia
lization and startup of the
servlet and returns a

ServletConfig object.

This object is then passed to
the init method. When this interface is implemented then it stores
the
ServletConfig object

in order to return it. It is done by the generic class
which im
plements this inetrface.

Returns
-


the ServletConfig object

getServletInfo()


public String getServletInfo()


The information about the servlet is returned by this method like
version, author etc. This method returns a string which should be in the
form o
f plain text and not any kind of markup.



Returns
-

a string that contains the information about the servlet

destroy()


public void destroy()


This method is called when we need to close the servlet. That is before
removing a servlet instance from service
, the servlet container calls the
destroy() method. Once the servlet container calls the destroy() method,
no service methods will be then called . That is after the exit of all the
threads running in the servlet, the destroy() method is called. Hence, the

servlet gets a chance to clean up all the resources like memory, threads
etc which are being held.



configuration and context:

Servlet Context

ServletContext

is a interface which helps us to communicate with the
servlet container. There is only one
ServletContext for the entire web
application and the components of the web application can share it. The
information in the ServletContext will be common to all the
components. Remember that each servlet will have its
own
ServletConfig
. The ServetContext i
s created by the container when
the web application is deployed and after that only the context is
available to each servlet in the web application.

Web application initialization:

1.

First of all the web container reads the deployment descriptor file
and
then creates a name/value pair for each <context
-
param> tag.

2.

After creating the name/value pair it creates a new instance of
ServletContext.

3.

Its the responsibility of the Container to give the reference of the
ServletContext to the context init parameters.

4.

The servlet and jsp which are part of the same web application can
have the access of the ServletContext.

The Context init parameters are available to the entire web application
not just to the single servlet like servlet init parameters.

How can we do th
e mapping of the Context init parameters in web.xml

<servlet>



<servlet
-
name>Mapping</servlet
-
name>



<servlet
-
class>ContextMapping</servlet
-
class>

</servlet>


<context
-
param>



<param
-
name>Email</param
-
name>



<param
-
value>admin@roseindia.net</param
-
value>

</context
-
param>


In the servlet code we will write this as

ServletContext context = getServletContext();

pw.println(context.getInitParameter("Email")
;



ServletConfig:

In this example we are going to retreive the init paramater values which
we hav
e given in the

web.xml

file.

Whenever the container makes a servlet it always reads it deployment
descriptor file i.e. web.xml. Container creates name/value pairs for
the
ServletConfig

object.


Once the parameters are
in

ServletConfig

they will never be rea
d again by the Container.

The main job of the

ServletConfig

object is to give the init parameters.

To retrieve the init parameters in the program firstly we have made one
class named
GettingInitParameterNames
. The container calls the
servlet's

service()

met
hod then depending on the type of request, the
service method calls either the doGet() or the doPost(). By default it will
be doGet() method. Now inside the

doGet()

method
use

getWriter()

method of the

response

object which will return a
object of the Prin
tWriter class which helps us to print the content on the
browser.

To retrieve all the values of the init parameter use
method

getInitParameterNames()

which will return the Enumeration
of the init parameters.

The code of the program is given below:


import

java.io.*;

import

javax.servlet.*;

import

javax.servlet.http.*;

import

java.util.*;


public

class

InitServlet

extends

HttpServlet

{



public

void

doGet(HttpServletRequest

request,





HttpServletResponse

response)



throws

ServletException,

IOException

{



PrintWriter

pw

=

response.getWriter();



pw.print("Init

Parameters

are

:

");



Enumeration

enumeration

=

getServletConfig().getInitParameterNames
();



while
(enumeration.hasMoreElements()){



pw.print(enumeration.nextElement()

+

"

");



}



pw.println("
\
nT
he

email

address

is

"

+




getServletConfig().getInitParameter("AdminEmail"));



pw.println("The

address

is

"

+




getServletConfig().getInitParameter("Address"));



pw.println("The

phone

no

is

"

+




getServletConfig().getInitParameter("PhoneNo"));



}

}

web.xml file of this program:

<?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>


<init
-
param>


<param
-
name>Admin
Email</param
-
name>


<param
-
value>zulfiqar_mca@yahoo.co.in</param
-
value>


</init
-
param>


<init
-
param>


<param
-
name>Address</param
-
name>


<param
-
value>Okhla</param
-
value>


</init
-
param>


<init
-
param>


<param
-
name>PhoneNo</param
-
name>


<param
-
value>9911217074
</param
-
value>


</init
-
param>



<servlet
-
name>Zulfiqar</servlet
-
name>



<servlet
-
class
>InitServlet</servlet
-
class
>


</servlet>


<servlet
-
mapping>


<servlet
-
name>Zulfiqar</servlet
-
name>


<url
-
pattern>/InitServlet</url
-
pattern>


</servlet
-
mapping>

</web
-
app>


The output of the program is given below:




Request and Response objects
:

When an user clicks on a link on

web browser
, then browser formats
that request and send it to the

web server
. Web server recieve

the
request and finds the requested resource which can be a web page or
jpeg image. It formats the resource into response and send it to the web
browser. Then browser gets the HTML which it shows to the user.





Web Server always send instructions to th
e browser which are written in
HTML, the hyper text markup language. Every communication held
between Browser, and Server is through HTTP (hyper text transfer
protocol). Browser sends HTTP request, and server responds with HTTP
response.


Hyper Text Transf
er Protocol(HTTP) is a protocol used for
every

communication

held between the Web Browser and Web Server.
HTTP works over the top of Transmission Control Protocol(TCP) and
Internet protocol(IP).TCP/IP takes care of packing/unpacking of data
which mean it
takes care of all the networking stuff that HTTP does not
required to know.



What a

HTTP request

consists of




1.

Request contains the

URL

of the page, for which browser
requested.


2.

It contains

HTTP method name

which will tells the server which
method to be executed for that request.There are many HTTP
methods:

GET, POST, HEAD, TRACE, PUT, DELETE, OPTIONS,
CONNECT


3.

It contains the

arguments

of the method to be executed.



First, HTTP Request contains

Uniform
Resource Locator(URL)

for
resource.Every resource on the web has an unique address which is
called URL.



http://www.mywebsite.com:80/javaexpert/home.html?Resource=30


URL consists of different parts
-
:





http

is the protocol used for sending request.




www.
mywebsite.com

will be converted to the proper IP address of
server by the Domain name server(DNS).




80
in above URL is the

port number

which is optional in URL.




javaexpert

in above URL is the

path on the server

where the
actual page or resource resides.




home.html

in above URL is the

actual page

request came for on
the server.




Resource=30

is the

Query string parameter
in the above
URL.Everything after a question mark in URL is query string.




HTTP Request also contains name of the HTTP method which is
needed
for server to know which method is to be invoked.

GET and POST
methods

are used generally.





HTTP GET method appends all the parameters at the end of the
URL.




HTTP POST method includes all the parameters within the body of
the HTTP request.



All t
he parameters that are required in the HTTP methods are also
sent in the HTTP Request and also called query string parameters.

Resource=30

in the above URL is Query String Parameter.


What a

HTTP response

consists of



1.

Response contains the

Status code

which shows that request
is successful or not.


2.

It contains the

content
-
type

that what kind of data is coming
to web browser.


3.

The

actual content

sent by the server.



HTTP response contains the status code which tells the status of
HTTP request. It also c
ontains

Content
-
Type
information also
called MIME
-
Type which tells the Web Browser about the type of
data coming to the web browser.


The actual content means hyper text markup language(HTML)
page or jpeg image or jsp page or any other resource which
browse
r requested for.


Session and event handling:


HTTP is a "stateless" protocol which means each time a client retrieves
a Web page, the client opens a separate connection to the Web server
and the server automatically does not keep any record of previous c
lient
request.

Still there are following three ways to maintain session between web
client and web server:

Cookies:

A webserver

can assign a unique session ID as a cookie to each web
client and for subsequent requests from the client they can be recognized
using the recieved cookie.

This may not be an effective way because many time browser does not
support a cookie, so I would no
t recommend to use this procedure to
maintain the sessions.

Hidden Form Fields:

A web server can send a hidden HTML form field along with a unique
session ID as follows:

<input

type
=
"hidden"

name
=
"sessionid"

value
=
"12345"
>

This entry means that, when the form is submitted, the specified name
and value are automatically included in the GET or POST data. Each
time when web browser sends request back, then session_id value can be
used to keep the track of different web browsers
.

This could be an effective way of keeping track of the session but
clicking on a regular (<A HREF...>) hypertext link does not result in a
form submission, so hidden form fields also cannot support general
session tracking.

URL Rewriting:

You can append
some extra data on the end of each URL that identifies
the session, and the server can associate that session identifier with data
it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid=12345,
the session identifie
r is attached as sessionid=12345 which can be
accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and works for the
browsers when they don't support cookies but here drawback is that you
would have generate

every URL dynamically to assign a session ID
though page is simple static HTML page.

The HttpSession Object:

Apart from the above mentioned three ways, servlet provides
HttpSession Interface which provides a way to identify a user across
more than one pag
e request or visit to a Web site and to store
information about that user.

The servlet container uses this interface to create a session between an
HTTP client and an HTTP server. The session persists for a specified
time period, across more than one conne
ction or page request from the
user.

You would get HttpSession object by calling the public
method

getSession()

of HttpServletRequest, as below:

HttpSession

session
=

request
.
getSession
();

You need to call

request.getSession()

before you send any document
content to the client. Here is a summary of the important methods
available through HttpSession object:

S.N.

Method & Description

1

public Object getAttribute(String name)

This method returns the object bound with the specifie
d
name in this session, or null if no object is bound under
the name.

2

public Enumeration getAttributeNames()

This method returns an Enumeration of String objects
containing the names of all the objects bound to this
session.

3

public long
getCreationTime()

This method returns the time when this session was
created, measured in milliseconds since midnight January
1, 1970 GMT.

4

public String getId()

This method returns a string containing the unique
identifier assigned to this session.

5

p
ublic long getLastAccessedTime()

This method returns the last time the client sent a request
associated with this session, as the number of milliseconds
since midnight January 1, 1970 GMT.

6

public int getMaxInactiveInterval()

This method returns the maximum time interval, in
seconds, that the servlet container will keep this session
open between client accesses.

7

public void invalidate()

This method invalidates this session and unbinds any
objects bound to it.

8

public
boolean isNew(

This method returns true if the client does not yet know
about the session or if the client chooses not to join the
session.

9

public void removeAttribute(String name)

This method removes the object bound with the specified
name from this s
ession.

10

public void setAttribute(String name, Object value)


This method binds an object to this session, using the
name specified.

11

public void setMaxInactiveInterval(int interval)

This method specifies the time, in seconds, between client
requests

before the servlet container will invalidate this
session.

Session Tracking Example:

This example describes how to use the HttpSession

object to find out the
creation time and the last
-
accessed time for a session. We would
associate a new session with the request if one does not already exist.

// Import required java libraries

import

java
.
io
.*;

import

javax
.
servlet
.*;

import

javax
.
servlet
.
http
.*;

import

java
.
util
.*;



// Extend HttpServlet class

public

class

SessionTrack

extends

HttpServlet

{




public

void

doGet
(
HttpServletRequest

request
,


HttpServletResponse

response
)


throws

ServletException
,

IOException


{


// Create a session object if it is already not created.


HttpSession

session
=

request
.
getSession
(
true
);


// Get session creation time.


Date

createTime
=

new

Date
(
session
.
getCreationTime
());


// Get last access
time of this web page.


Date

lastAccessTime
=



new

Date
(
session
.
getLastAccessedTime
());



String

title
=

"Welcome Back to my website"
;


Integer

visitCount
=

new

Integer
(
0
);


String

visitCountKey
=

new

String
(
"
visitCount"
);


String

userIDKey
=

new

String
(
"userID"
);


String

userID
=

new

String
(
"ABCD"
);



// Check if this is new comer on your web page.


if

(
session
.
isNew
()){


title
=

"Welcome to my website"
;


session
.
setAttribute
(
userIDKey
,

userID
);


}

else

{


visitCount
=

(
Integer
)
session
.
getAttribute
(
visitCountKey
);


visitCount
=

visitCount
+

1
;


userID
=

(
String
)
session
.
getAttribute
(
userIDKey
);


}


session
.
setAttribute
(
visitCountKey
,

visitCount
);



// Set response content type


response
.
setContentType
(
"text/html"
);


PrintWriter

out

=

response
.
getWriter
();



String

docType
=


"<!doctype html public
\
"
-
//w3c//dtd html 4.0 "

+


"transitional//en
\
">
\
n"
;


out
.
println
(
docType
+


"<html>
\
n"

+


"<head><title>"

+

title
+

"</title></head>
\
n"

+


"<body bgcolor=
\
"#f0f0f0
\
">
\
n"

+


"<h1 align=
\
"center
\
">"

+

title
+

"</h1>
\
n"

+


"<h2 align=
\
"center
\
">Session Infomation</h2>
\
n"

+


"<table border=
\
"1
\
" align=
\
"center
\
">
\
n"

+


"<tr bgcolor=
\
"#949494
\
">
\
n"

+


" <th>Session info</th><th>value</th></tr>
\
n"

+


"<tr>
\
n"

+


" <td>id</td>
\
n"

+


" <td>"

+

session
.
getId
()

+

"</td></tr>
\
n"

+


"<tr>
\
n"

+


" <td>Creation Time</td>
\
n"

+


" <td>"

+

createTime
+



" </td></tr>
\
n"

+


"<tr>
\
n"

+


" <td>Time of Last Access</td>
\
n"

+


" <td>"

+

lastAccessTime
+



" </td></tr>
\
n"

+


"<tr>
\
n"

+


" <td>User ID</td>
\
n"

+


" <td>"

+

userID
+



" </td></tr>
\
n"

+


"<tr>
\
n"

+


" <td>Number of visits</td>
\
n"

+


" <td>"

+

visitCount
+

"</td></tr>
\
n"

+


"</table>
\
n"

+


"</
body></html>"
);


}

}

Compile above servlet

SessionTrack

and create appropriate entry in
web.xml file. Now running
http://localhost:8080/SessionTrack

would
display the following result when you would run for the first time:

Welcome to my website

Session
Infomation

Session info

value

id

0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time

Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last
Access

Tue Jun 08 17:26:40 GMT+04:00 2010

User ID

ABCD

Number of visits

0

Now try to run the same servlet

for second time, it would display
following result.

Welcome Back to my website

Session Infomation

info type

value

id

0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time

Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last
Access

Tue Jun 08 17:26:40 GMT+04:00
2010

User ID

ABCD

Number of visits

1

Deleting Session Data:

When you are done with a user's session data, you have several options:



Remove a particular attribute:

You can call

public void
removeAttribute(String name)

method to delete the value
associated with
a particular key.



Delete the whole session:

You can call

public void invalidate()

method
to discard an entire session.



Setting Session timeout:

You can call

public void
setMaxInactiveInterval(int interval)

method to set the timeout for a
se
ssion individually.



Log the user out:

The servers that support servlets 2.4, you can
call

logout

to log the client out of the Web server and invalidate all
sessions belonging to all the users.



web.xml Configuration:

If you are using Tomcat, apart from the
above
mentioned methods, you can configure session time out in web.xml file
as follows.


<session
-
config>


<session
-
timeout>
15
</session
-
timeout>


</session
-
config>

The timeout is expressed as minutes, and overrides the default timeout
which is 30 minu
tes in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout
period for that session in seconds. So if your session is configured in
web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.

Introduction to filters with writing

simple filter

Application:


Servlet Filters are Java classes that can be used in Servlet Programming
for the following purposes:



To intercept requests from a client before they access a resource at back
end.



To manipulate responses from server before they

are sent back to the
client.

There are are various types of filters suggested by the specifications:



Authentication Filters.



Data compression Filters.



Encryption Filters.



Filters that trigger resource access events.



Image Conversion Filters.



Logging and A
uditing Filters.



MIME
-
TYPE Chain Filters.



Tokenizing Filters .



XSL/T Filters That Transform XML Content.

Filters are deployed in the deployment descriptor file

web.xml

and then
map to either servlet names or URL patterns in your application's
deployment de
scriptor.

When the web container starts up your web application, it creates an
instance of each filter that you have declared in the deployment
descriptor. The filters execute in the order that they are declared in the
deployment descriptor.

Servlet

Filter Methods:

A filter is simply a Java class that implements the javax.servlet.Filter
interface. The javax.servlet.Filter interface defines three methods:

S.N.

Method & Description

1

public void doFilter (ServletRequest, ServletResponse,
FilterChain)

This method is called by the container each time a
request/response pair is passed through the chain due to a
client request for a resource at the end of the chain.

2

public void init(FilterConfig filterConfig)

This method is called by the web container
to indicate to a
filter that it is being placed into service.

3

public void destroy()

This method is called by the web container to indicate to a
filter that it is being taken out of service.

Servlet Filter Example:

Following is the Servlet Filter Exampl
e that would print the clients IP
address and current date time. This example would give you basic
understanding of Servlet Filter, but you can write more sophisticated
filter applications using the same concept:

// Import required java libraries

import

java
.
io
.*;

import

javax
.
servlet
.*;

import

javax
.
servlet
.
http
.*;

import

java
.
util
.*;


// Implements Filter class

public

class

LogFilter

implements

Filter

{


public

void

init
(
FilterConfig

config
)



throws

ServletException
{


// Get init parameter


String

testParam
=

config
.
getInitParameter
(
"test
-
param"
);




//Print the init parameter


System
.
out
.
println
(
"Test Param: "

+

testParam
);



}


public

void

doFilter
(
ServletRequest

request
,



ServletResponse

response
,


FilterChain

chain
)



throws

java
.
io
.
IOException
,

ServletException

{



// Get the IP address of client machine.


String

ipAddress
=

request
.
getRemoteAddr
();



// Log the IP address

and current timestamp.


System
.
out
.
println
(
"IP "
+

ipAddress
+

", Time "


+

new

Date
().
toString
());



// Pass request back down the filter chain


chain
.
doFilter
(
request
,
response
);


}


public

void

destroy
(

){


/* Called before the Filter instance is removed


from service by the web container*/


}

}

Compile

LogFilter.java

in usual way and put your class file in
<Tomcat
-
installation
-
directory>/webapps/ROOT/WEB
-
INF/classes.

Servlet

Filter Mapping in Web.xml:

Filters are defined and then mapped to a URL or Servlet, in much the
same way as Servlet is defined and then mapped to a URL pattern.
Create the following entry for filter tag in the deployment descriptor
file

web.xml

<filter>



<filter
-
name>
LogFilter
</filter
-
name>


<filter
-
class>
LogFilter
</filter
-
class>


<init
-
param>



<param
-
name>
test
-
param
</param
-
name>



<param
-
value>
Initialization Paramter
</param
-
value>


</init
-
param>

</filter>

<filter
-
mapping>


<filter
-
name>
LogFilter
</filter
-
name>


<url
-
pattern>
/*
</url
-
pattern>

</filter
-
mapping>

The above filter would apply to all the servlets because we
specified

/*

in our configuration. You can specicy a particular servlet
path if you want to apply filter on few servlets

only.

Now try to call any servlet in usual way and you would see generated
log in your web server log. You can use Log4J logger to log above log
in a separate file.

Using Multiple Filters:

Your web application may define several different filters with a s
pecific
purpose. Consider, you define two filters

AuthenFilter

and

LogFilter
.
Rest of the process would remain as explained above except you need to
create a different mapping as mentioned below:

<filter>


<filter
-
name>
LogFilter
</filter
-
name>


<filter
-
class>
LogFilter
</filter
-
class>


<init
-
param>



<param
-
name>
test
-
param
</param
-
name>



<param
-
value>
Initialization Paramter
</param
-
value>


</init
-
param>

</filter>


<filter>


<filter
-
name>
AuthenFilter
</filter
-
name>


<filter
-
class>
AuthenFilter
<
/filter
-
class>


<init
-
param>



<param
-
name>
test
-
param
</param
-
name>



<param
-
value>
Initialization Paramter
</param
-
value>


</init
-
param>

</filter>


<filter
-
mapping>


<filter
-
name>
LogFilter
</filter
-
name>


<url
-
pattern>
/*
</url
-
pattern>

</filter
-
mappi
ng>


<filter
-
mapping>


<filter
-
name>
AuthenFilter
</filter
-
name>


<url
-
pattern>
/*
</url
-
pattern>

</filter
-
mapping>

Filters Application Order:

The order of filter
-
mapping elements in web.xml determines the order in
which the web container applies the filter to the servlet. To reverse the
order of the filter, you just need to reverse the filter
-
mapping elements in
the web.xml file.

For example, ab
ove example would apply LogFilter first and then it
would apply AuthenFilter to any servlet but the following example
would reverse the order:

<filter
-
mapping>


<filter
-
name>
AuthenFilter
</filter
-
name>


<url
-
pattern>
/*
</url
-
pattern>

</filter
-
mapping>


<
filter
-
mapping>


<filter
-
name>
LogFilter
</filter
-
name>


<url
-
pattern>
/*
</url
-
pattern>

</filter
-
mapping>