Final1x - More from

soilkinkajouInternet and Web Development

Feb 2, 2013 (5 years and 5 months ago)



It’s nothing but a designing or layout language.

HTML stands for Hyper Text Markup Language

HTML is not a programming language, it is a markup language

HTML uses markup tags to describe web pages.

It is a type of computer language that is primarily used for files that are posted on the internet and
viewed by web browsers.

Browser can understand only one language that one is HTML.

We can create static
pages with extension either .HTML or .HTM.

The HTML contains TAGS and attributes of that tags.

With the help of HTML language we can develop static pages.


Hypertext Transfer Protocol is the set of rules for transferring files (text, graphic images, sound, video,
and other multimedia files) on the World Wide Web.

Server and clients can talk with each other using HTTP.

HTTP defines how messages are formatte
d and transmitted, and what actions Web servers and
browsers should take in response to various commands.

When WebServer sends data on the browser it sends using HTTP.


is Web server?

A web server is a program running on

the server that listens for incoming requests and services
those requests as they come in.

A web server is a computer that responds to requests from a client Typical requests: provide a web
page, upload or download a file, send email

A web server is
also the software that responds to these requests; a client could be the browser or
other software making these requests Typically, your little computer is the client, and someone
else’s big computer is the server. However, any computer can be a server It
is not unusual to have
server software

and client
software running on the same computer

By default the role of a web server is to serve static pages using the http protocol

Web servers can be made dynamic by adding additional processing capability to the



is Apache?

The Apache HTTP Server, commonly referred to as Apache is
web server

software notable for
playing a key role in the initial growth of the
World Wide Web

What is Apache Tomcat Jakarta Tomcat or simply Tomcat

A Web container is essentially the component of a Web server that interacts with
the servlets.

The Web container is
responsible for managing the lifecycle of servlets,
mapping a URL to a particular servlet and ensuring that the URL
requester has the correct access rights.

When your web server application gets request for a servlet the server
hands the request not to th
e servlet itself, but to the Container in
which the servlet is deployed.

It gives the response to the HTTP request.

Apache Tomcat is open source software that implements Java Servlet and JavaServer Pages,
ing sites to run Java servlets
and Java
d dynamic content.

Basic task of WebContainer are:

Creates HTTP Request and Response for the Servlet, calls the appropriate servlet service method
(doGet or doPost) to service the client request.

Container also gives: Communication support(socket
creation), Servlet life cycle management
(Init(), Service() and Destroy()), Multithreading support, Declarative security(thru deployment
descriptor) and JSP support.

Basic of JSP and Servlet

The Servlet and JSP are web tier components that are running within a web
tier container.

The roles that web components play are basically


receiving client requests that are coming in the form of HTTP requests and then


perform dynamic contents generat
ion or performing

business logic by themselves


delegating it to the EJB tier components return responses to the clients.

The main difference between servlets and JSPs is that servlets are Java classes and JSPs are not (they are
embedded in HTML pages

This difference also specifies where you want to use servlets and where you want to use JSPs:

If you generate all of your html pages dynamically and will have complex logic, you will probably use

If dynamic content is very low compared t
o the static content in your web page, then you will probably
use JSPs.

What is JSP?

The interesting thing is that, despite the huge apparent difference, behind the scenes they are the

In fact, a JSP document is just another way of writing a
servlet. JSP pages get translated into
servlets, the servlets get compiled, and it is the servlets that run at request time.

JSP is focused on simplifying the creation and maintenance of the HTML.

Servlets are best at invoking the business logic and per
forming complicated operations.

A quick rule of thumb is that servlets are best for tasks oriented toward processing, whereas JSP is
best for tasks oriented toward presentation.

SP is a webpage scripting language that can generate dynamic content while

Servlets are Java
programs that are already compiled which also creates dynamic web content

Servlets run faster compared to JSP

JSP can be compiled into Java Servlets

It’s easie
r to code in JSP than in Java.

JSP and Java Servlets are usually used i
n conjunction nowadays

What is Servlet?

The complete servlet specification was created by Sun Microsystems, with version 1.0 finalized in
June 1997 right now 3.0 is going on in the market.

A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request
response programming model.

A technical description of Servlet is it is a Java object that is based on Servlet framewor
k and
extends the functionality of a web server

basically being responsible for creating dynamic contents.

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

Servlets are Java technology's answer to C
GI programming.

They are programs that run on a Web server and build Web pages.

Servlet can be thought of as server
side applet.

Servlets are loaded and
executed by

a web server in the same manner that

applets are loaded and
executed by a web browser.

Servlets accepts request s from a client (via web server) performs some task and return the

Servlets are Java programs that run on Web or application servers, acting as a middle layer
between requests coming from Web browsers or other HTTP clients

and databases or applications
on the HTTP

Using servlets web developers can create fast and efficient server side application which can run on
any servlet enabled web server.

Servlets run entirely inside the Java Virtual Machine.

Servlets c
an access the entire family of Java APIs, including the JDBC API to access enterprise

Although servlets can respond to any type of request, they are commonly used to extend the
applications hosted by Web servers.

For such applications, Java Serv
let technology defines HTTP
specific servlet classes.

javax.servlet and javax.servlet.http

packages provide interfaces and classes for writing

All servlets must implement the
Servlet interface,

which defines 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


It is regular Java code.

There are new APIs, but no new syntax.

It has unfamiliar import statements.

The servlet and JSP APIs are not part of the Java 2 Platform, Standard Edition (J2SE); they are a
separate specification

It extends a standard class (

Servlets provide a rich infrastructure for dealing with HTTP.

It overrides the doGet method.

Servlets have different methods to respond to different types of HTTP commands

Roles of Servlet

Read the explicit data sent by the client.

Data entered by end user in the HTML form or from applet or a customHTTP client program.

Read the implicit HTTP request data sent by the browser.

Above figure shows a single arrow going from the client to the Web server, but there are really two
es of data: the explicit data that the end user enters in a form and the behind
HTTP information.

The HTTP information includes cookies, information aboutmedia types and compression schemes
the browser understands, and so forth.

Generate the

This process may require talking to a database, executing an RMI or EJB call, invoking a Web
service, or computing the response directly.

Your real data may be in a relational database.

Fine. But your database probably doesn’t speak HTTP or return results in HTML, so the Web
browser can’t talk directly to the database.

Even if it could, for security reasons, you probably would not want it to.

The same argument applies to most other ap

You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the
application, and embed the results inside a document.

4. Send the explicit data (i.e., the document) to the client.

This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF
images), or even a compressed format like .zip that is layered on top of some other underlying

But, HTML is by far the most common format, so an important servlet/JSP task is to wrap th
results inside of HTML.

5. Send the implicit HTTP response data.

Single arrow going from the Web middle layer (the servlet or JSP page) to the client.

But, there are really two varieties of data sent: the document itself and the behind


Again, both varieties are critical to effective development.

Sending HTTP response data involves telling the browser or other client what type of document is
being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Why Build Web Pages Dynamically?

There are a number of reasons wh
y Web pages need to be built on

The Web page is based on data sent by the client.

For instance, the results page from search engines and order confirmation pages at online stores
are specific to particular user requests.

You don’t know what to

display until you read the data that the user submits.

Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit
(i.e., HTTP request headers).

Either kind of input can be used to build the output page.

Web page is derived from data that changes frequently.

If the page changes for every request, then you certainly need to build the response at request
time. If it changes only periodically, however, you could do it two ways: you could periodically
a new Web page on the server , or you could wait and only build the page when the user
requests it.

The right approach depends on the situation, but sometimes it is more convenient to do the latter:
wait for the user request.

For example, a weather rep
ort or news headlines site might build the pages dynamically, perhaps
returning a previously built page if that page is still up to date.

The Web page uses information from corporate databases or other server
side sources.

If the information is in a data
base, you need server
side processing even if the client is using
dynamic Web content such as an applet.

Imagine using an applet by itself for a search engine site use only.

Going from the client to the Web tier to the database (a three
tier approach) in
stead of from an
applet directly to a database (a two
tier approach) provides increased flexibility and security with
little or no performance penalty.

After all, the database call is usually the rate
limiting step, so going through the Web server does
ot slow things down.

In fact, a three
tier approach is often faster because the middle tier can perform caching and
connection pooling.

In principle, servlets are not restricted to Web or application servers that handle HTTP requests but
can be used for

other types of servers as well. For example, servlets could be embedded in FTP or
mail servers to extend their functionality.

CGI VS Servlet

Common Gateway Interface

CGI are usually executables that are native to the server’s operating system, though
servlets can
also be compiled to the native OS it can be compiled to Java bytecode which is then run on a JVM

CGI programs are platform dependent while servlets are platform independent

CGI programs run as separate processes on the computer while servlet
s run on the JVM

CGI can directly process scripts while it needs to be translated and compiled to before it can be run
as a servlet

CGI is a process based(Heavy weight) and Servlet is a Thread based (Light weight).


CGI creates a process for ever

So, this

is a time taking process whereas
servlet executes by using

Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data,
reading and setting HTTP headers, handling cookies, tracking sessi
ons, and many other such high
level utilities. In CGI, you have to do much of this yourself

Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not
without using a server
specific API.

Basic servlet structure

Basic servlet that handles GET requests.

A browser generates this request when the user enters a URL on the address line, follows a link
from a Web page, or submits an HTML form that either does not specify a METHOD or specifies

Servlets ca
n also easily handle

requests, which are generated when someone submits an
HTML form that specifies



Data is part of the URL in get method.

Post method data is sent as request
message body.

Choosing GET as the "method" will
append all
of the data to the URL and it will show up in
the URL bar of your browser.

A POST on the other hand will
(typically) send the information through
a socket back to the webserver and it
won't show up in the URL bar

Data is cached in the browsers

URL history if
you use get method

post method Data cannot be cached.

In get method you can send only text

post method you can send text as well
as possible to send files and even
binary data such as serialized Java

The amount of information

you can send back
using a GET is restricted as URLs can only be
1024 characters.

Larger data can be send in the post
method as compared to the GET


his message comes to the backend
program in
the form of the standard
input which you can parse and use for
your processing.

doGet() method

doPost() method

Basic servlet


import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorld extends
HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("Hello World");



to First basic HTML program of Servlet

Step 1: Write down below coding in simple editor




import javax.servlet.*;


import javax.servlet.http.*;


public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,


HttpServletResponse response)


throws IOException, ServletException






PrintWriter out = response.getWriter();






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






out.println("<h1>Hello World!</h1>");









Step 2: Complie it

Step 3: Class file is generated

Step 4: Start TomCAT

Step 5:

Step 6: Create
directory structure as given below in WebApps

Step 7: Cut D:

Step 8: Past it in Classes folder of Webapps

Step 9:

We need to change in
deployment descriptor (web.xml) file.

open it and add tags.

There could be various entries in this table already available, but never

Step 10: Now write down port no in WebBrowser open it and click on Tomcat manager

Step 11: Enter username and password

Step 12: Go to our folder

Step 13:
Write down program name

Explanation of Basic Structure of Servlet

Let's have a look at how the Servlet works.

Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost
every Servlet needs classes from
these packages).

1: import*;

2: import javax.servlet.*;

3: import javax.servlet.http.*;

The javax.servlet package and javax.servlet.http package contains a number of classes and interfaces that
describe and define the con
tracts between a servlet class running under the HTTP protocol and the
runtime environment provided for an instance of such a class by a conforming servlet container.

The Servlet class is declared in line

Our Servlet extends javax.servlet.http.HttpS
ervlet, the standard base class for HTTP Servlets.

4: public class HelloWorld extends HttpServlet

In lines 5 through 9 HttpServlet's doGet method is getting overridden.

5: public void doGet(HttpServletRequest request,


ervletResponse response)


throws IOException, ServletException




9: }

In line 6 we use a method of the HttpServletResponse object to set the content type of the response that
we are going to send.

In line 7

efines a general exception a servlet can thro
w when it encounters difficulty and

define a general exception

InputOuput field not found

All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body

to the response.

Sub part

1: res

In line 2 we request a PrintWriter object to write text to the response message.

2: PrintWriter out = res

In lines 3 to 10 we use the PrintWriter to
write the text of type text/html (as specified through the content

To display the output on the browser we use the println() method of the PrintWriter class.



4: ....



How Servlet

You write a servlet and compile it, and then place it in the appropriate directory.

When the Servlet Container starts, it will preload your servlet in memory if specified in the web.xml
configuration file.

If your servlet is not already loaded (not listed in the web.xml configuration file), its instance will be
created as soon as a request for it is received by the Servlet Container.

The first time it is loaded, the container calls your servlet's init() me

Now that your servlet is ready, it waits for requests.

The container will call your service() method each time a request is received for your servlet.

The HttpServlet class
already has this method, so you don't have to write one, but you can ov
erride it.

The service() method then passes the request on to the appropriate method such as the doGet() method
if it is a GET request, or the doPost() method if it is a POST request.

The doXXX() methods are the ones you need to override and where you
will spend most of your effort.



take two arguments: an

and an


lets you get at all of the incoming data; the class has methods by which you can
find out about information such as form (query) data, HTTP request headers, and the client's hostname.


lets you specify outgoing information such as

HTTP status codes (200, 404,
etc.) and response headers (
, etc.).

Most importantly,

lets you obtain a

that you use to send document
content back to the client.

The servlet processes the request (c
ode you write in doGet()), returning a response to the container.

The container sends the text of the response back to the browser.

Servlet Life Cycle

The life cycle of a servlet is controlled by servlet
container in which the servlet has
been deployed. When a
HTTP request is mapped to a servlet,

the container performs the following steps.

If an instance of the servlet does not exist, the Web container

Loads the servlet class.

Creates an instance of the servlet class.

Initializes the servle
t instance by calling the init() method .

Invokes the service method, passing HttpServletRequest and

HttpServletResponse objects
as parameters.

When shutting down, calls each servlet’s
destroy( )


Servlets Container


A servlet is managed by a
servlet container

(referred to as
Servlet Engine


The servlet container is a compiled, executable program. The container is the
between the Web server and the servlets
in the container. The container loads, initializes, and
executes the serv
lets. When a request arrives, the container maps the request to a servlet


The container is designed to perform well while serving large numbers of requests. A container can
hold any number of active servlets. The container creates and manages threads as ne
cessary to
handle incoming requests.
The container handles multiple requests concurrently
, and more
than one thread may enter an object at a time.


Servlet containers are also referred to as
web containers

web engines

Architecture Diagram:

The following figure depicts a typical servlet life
cycle scenario.

First the HTTP requests coming to the server are delegated to the servlet container.

The servlet container loads the servlet before invoking the


Then the servlet contain
er handles multiple requests by spawning multiple threads, each thread
executing the service() method of a single instance of the servlet.

Each request runs in a separate thread.

The container runs multiple threads to process
multiple requests to a single result.

And every client request generates a new pair of request and response objects.

A servlet life cycle can be defined as the entire process from its creation till the destruction.

following are the paths followed by a servlet


The servlet is initialized by calling the
init ()

method. init is where you put one
time setup code.
By this init() method the servlet get to know that it has been placed into service.


The servlet calls

method to process a client's request. Each user request results in a
thread that calls the service method of the previously created instance. Multiple concurrent
requests normally result in multiple threads calling service sim
ultaneously, although your servlet
can implement a special interface (SingleThreadModel) that stipulates that
only a single thread is permitted to run at any one time. The service method
then calls doGet, doPost, or another doXxx method, depending on the t
of HTTP request it received.


Finally, if the server decides to unload a servlet, it first calls the servlet's
destroy method.

The servlet is terminated by calling the



Finally, servlet is garbage collected by the garbage collector of
the JVM.

Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once.

It is called when the servlet is first created, and
not called again for each
user request.

So, it is used for one
time initializations.

The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.

When a user invokes a servle
t, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet
or doPost as appropriate.

The init() method simply creates or loads some data that will be used
throughout the life of the ser

The init method definition looks like this:

public void init() throws ServletException


// Initialization code...


The service() method :

The service() method is the main method to perform the actual task.

The servlet container (i.e. web

server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.

The servlet services the client's request with the help of two objects. These two objects



are passed by the servlet

Each time the server receives a request for a servlet, the server spawns a new thread
and calls service.

The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOExcep


The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate.

So you have nothing to do with service() method but you override either doGet() or doPost()
depending on
what type of request you receive from the client.

Servlets generally extend the HttpServlet class and override the doGet or the doPost methods

The doGet() and doPost() are most frequently used methods within each service request.

Here are the signature

of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {

// Servlet code


The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should
be handled by doPost() method.

void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

// Servlet code


The destroy() method :

The destroy() method is called only once at the end of the life cycle of a servlet.

method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection.

The destroy method definition looks like this:

public void destroy() {

// Finalization code...


Life Cycle Example ,

To appreciate the
execution of the servlet life cycle methods,
keep refreshing the browser (F5 in Windows).


import javax.servlet.*;

import javax.servlet.http.*;

public class LifeC extends HttpServlet {

int i;

public void init() throws ServletException




public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException



PrintWriter out = response.getWriter();



out.println("<h1>in i =0 </h1>");





out.println("<h1>in i =10 </h1>");





out.println("<h1>in i <" + i + "</h1>



public void destroy()





Display Date


import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DispDt extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException



PrintWriter out = response.getWriter();

Date today = new Date();

out.println("<html>"+"<body><h1>Today Date is</h1>");

out.println("<b>"+ today+"</b></body>"+ "</html>");



Parameterized Servlet


import javax.servlet.*;

import javax.servlet.http.*;

public class Hello2 extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException



r out = response.getWriter();

String title = "Using GET Method to Read Form Data";

String docType =

"<!doctype html public
//w3c//dtd html 4.0 " +


out.println(docType +

n" +

"<head><title>" + title + "</title></head>
n" +

"<body bgcolor=
n" +

"<h1 align=
">" + title + "</h1>
n" +

n" +

" <li><b>First Name</b>: "

+ request.getParameter("first_name") + "
n" +

" <li><b>Last Name</b>: "

+ request.getParameter("last_name") + "
n" +

n" +




HTML file


action="http://localhost:8081/shyamsir/Hello2" method="get">

First Name: <input type="text" name="first_name">

<br />

Last Name: <input type="text" name="last_name" />

<input type="submit" value="Submit" />




Print the
Header Information


import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class Hello4 extends HttpServlet


public void doGet(HttpServletRequest request,HttpServletResponse response)

throws Servlet
Exception, IOException



PrintWriter out = response.getWriter();

String title = "Servlet Example: Showing Request Headers";


n" +

"<H1 ALIGN=CENTER>" + title + "</H1>
n" +

"<B>Request Method: </B>" +

request.getMethod() + "<BR>
n" +

"<B>Request URI: </B>" +

request.getRequestURI() + "<BR>
n" +

"<B>Request Protocol: </B>" +

request.getProtocol() + "<BR><BR>
n" +

n" +

n" +

"<TH>Header Name<TH>Header Value");

numeration headerNames = request.getHeaderNames();



String headerName = (String)headerNames.nextElement();

out.println("<TR><TD>" + headerName);

out.println(" <TD>" + request.getHeader