0% found this document useful (0 votes)
43 views7 pages

01 Servlet Introduction

1. The Common Gateway Interface (CGI) allows external programs to interface with web servers to generate dynamic content. However, CGI has performance limitations due to launching a new process for each request. 2. Java servlets provide a platform-independent way to add dynamic content to web applications using the Java programming language. Servlets are managed by a web container and can handle multiple requests concurrently through multithreading. 3. The servlet specification defines lifecycle methods like init(), service(), and destroy() that allow servlets to initialize, service requests, and shutdown gracefully. This makes servlets faster than CGI for dynamic web applications.

Uploaded by

nehaagrawal2210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views7 pages

01 Servlet Introduction

1. The Common Gateway Interface (CGI) allows external programs to interface with web servers to generate dynamic content. However, CGI has performance limitations due to launching a new process for each request. 2. Java servlets provide a platform-independent way to add dynamic content to web applications using the Java programming language. Servlets are managed by a web container and can handle multiple requests concurrently through multithreading. 3. The servlet specification defines lifecycle methods like init(), service(), and destroy() that allow servlets to initialize, service requests, and shutdown gracefully. This makes servlets faster than CGI for dynamic web applications.

Uploaded by

nehaagrawal2210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Deccansoft Software Services Java EE / Servlet Introduction

--------------------------------------------------------------------------------------------------------------------------------------------------------
Common Gateway Interface:
A web server is a piece of software which can accept HTTP request and provide HTTP response. Since the communication
protocol is HTTP, a web server is also called as HTTP Server. Although the major content type provided to the clients is
HTML, web server can provide any type of documents in response. The application used as HTTP client is a browser
(technically called as user agent).

The content which never changes irrespective of time or the current user is set to be static by nature. For web to be realistic,
the content has to be dynamic. Dynamic content has to be generated for which some code has to be executed at the server side.
For example a site which provides weather reports, stock market reports, web based search engines, web based email services,
on-line shopping, online banking etc. are examples of dynamic content scenarios.

The Common Gateway Interface (CGI) is a standard for interfacing external applications with information servers, such as
HTTP or Web servers. A plain HTML document that the Web server retrieves is static by nature, i.e. its contents do not
change. A CGI program, on the other hand, is executed when a web request arrives, hence it can generate content dynamically
and provide the same as part of response.

In the CGI approach, the request will carry name of the program. The web server will then launch such program which is
responsible for dynamic content generation. Such content reaches the client as part of the response. In case of CGI, the
information coming from the client as part of the request [for e.g. information provided by the user in the GUI fields] and
information about the server will be passed to the CGI program in the form of environmental variables.

CGI as a standard specifies which variable will be used for holding which value.

The language to be chosen for writing the CGI application must support certain pre-requisites, like:
1. Command Line Arguments facility
2. Environmental Variable facility
3. Support for Standard Streams

Compiled languages like C or C++ can be chosen for implementing such applications. We get the advantage of good
performance but with the following drawbacks as well:
1. The applications are not platform independent. Hence the investment is not safe.
2. There is no standard security model for such applications.
3. No proper string support due to the limited facilities in the string library.

To overcome the drawbacks of compiled languages, interpreted languages slowly started getting popularity. Among such
languages, PERL is the most popular. The language was invented specifically for generating reports and it suited the web
application development very well. PERL is an interpreted language and hence is more portable than compiled languages. It
has excellent string support. PERL programs are relatively more secure since system calls can easily be prevented.

On the whole, the CGI approach itself has performance limitations since a process is launched for each request. Such approach
would degrade the performance due to the overheads attached with the process concept.

As an alternative to CGI, there are good performing options but are proprietary solutions since these solutions are specific to a
particular server. For example:
ISAPI [Internet Server API ] works only with IIS
NSAPI [Netscape Server API] works only with NES
mod perl [Module for PERL]works only with Apache web server
1
Deccansoft Software Services Java EE / Servlet Introduction
--------------------------------------------------------------------------------------------------------------------------------------------------------
Java Servlets is a specification for developing web applications in Java language. Since Servlets are a specification and not a
product, the application would be independent of the implementation i.e. it can be deployed across any complaint server.

A Web Application is a collection of Web Resources [HTML docs, Image files etc], Web Components [Servlet and JSPs] and
an application configuration file which is an XML file known as deployment descriptor [WEB-INF/web.xml]. All these things
are organized in a directory structure as mentioned in the specification and can be deployed across any complaint server.

Servlets and JSPs are referred as Web Components due to the following reasons:

They are developed by the following a specification (this is what distinguishes a Component from a regular Object). These
components are managed within the web server kind of environment and can handle web requests i.e. HTTP protocol related
environment. The purpose of web components is to handle the web request and provide a response by dynamically generating
the content.

From the developer point of view, a Servlet is an instance of a class which directly or indirectly implements the
javax.servlet.Servlet interface.

Servlets require a special kind of runtime environment in which they can be managed. Such environment was initially called as
Servlet Engine but the modern name is Web Container. A Web Container provides runtime environment where our web
applications are recognized and the web components can be managed. Web Container usually comes embedded in a Web
Server. For example: Tomcat, Jetty and WebLogic server are few such servers

Servlet is a managed component i.e. we never instantiate or destroy servlet manually. It is the web container which will do that
for us. The interaction between the container and servlet will be through pre-defined methods mentioned in Servlet interface
hence every Servlet must implement such interface.

Every servlet in the application will have a unique identification which is called as URL pattern. The URL Pattern is
associated with a Servlet in the deployment descriptor. The container decides which servlet should handle the request by
studying the URL pattern of the HTTP Request.

When a request arrives for the servlet and if an instance of such recognized servlet does not yet exist, then a new instance is
created. This instance is given a chance to initialize for which the container invokes a designated method [init method] for
such purpose. When such method returns without any exception then the servlet is said to be in a ready state.

The servlet is then asked to handle the request for which the container invokes a designated method [service method]. This
method contains the code which is the purpose of writing the servlet. After the response is provided, the container would retain
the servlet instance rather than destroying it. It would be used for handling requests in future. Reusing the same instance
results in saving both time and memory and is crucial for good performing environments. Such approach makes Servlets much
faster in performance when compared to CGI where a new process is launched for each request. The container can distinguish
between different requests by using the Multi-Threading feature of the language.

Whenever the container decides to destroy the servlet, there would be a notification through a designated method [destroy
method] and then servlet instance can be garbage collected. A servlet might get destroyed under following circumstances:

1. If the container desperately falls short of memory, it might destroy least recently used Servlets.
2. When the application itself is un-deployed.
3. When we shutdown the server in a proper documented manner.
2
Deccansoft Software Services Java EE / Servlet Introduction
--------------------------------------------------------------------------------------------------------------------------------------------------------
HTTP is an application level protocol. It specifies the request and response message formats to be exchanged over a TCP/IP
connection. HTTP protocol has different ways of formatting requests, which are called as request methods. The following are
the request methods available in HTTP protocol.

GET [default], POST, HEAD, PUT, DELETE, TRACE

In case the request method is not specified, then the default request method used by the browser is GET.
From within a browser environment, we can explicitly use GET and POST only.

An HTTP request is made up of:


A) Request Line
B) Headers
C) Request Body (in case of POST)

The HTTP Request line is made up of the request method, the requested file name and the protocol name/version. For e.g.

GET /resource HTTP/1.1


Header-Name: Header-Value
Header-Name: Header-Value

Request headers contain the information to be the sent along with the request irrespective of the resource to be requested.
Request Headers carry information like the kind of browser being used, the type of image formats supported by the browser,
the compression techniques supported by the browser etc.

The information provided by the user will be appended to the file name separated by “?” (Question Mark).
Such information is called as Query String. Request Method GET should not be used if Query String contains large amount
of data. [since Environment variables at the server side are restricted in size]

For large amount of information to be sent, we should prefer the request method POST

In case of POST, the data to be is sent along with the request is present in request body. The separator between request headers
and Posted body is two new line characters (\r\n\r\n). The information about the Content-Type and the length of the request
body will be present in request headers. The posted content is available at the standard input stream of the application and
there is no restriction on the amount of data.

POST /resource HTTP/1.1


Header-Name: Header-Value
CONTENT-TYPE: MIME of the request body
CONTENT-LENGTH: size in bytes

Servlet Lifecycle Methods:

public void init(ServletConfig config) throws ServletException


This method will be invoked as soon as the servlet class is instantiated. The method generally contains initialization kind of
code which we generally put in constructor of a class. In managed component environment, instantiation always happens
through default constructor. Hence there would be special dedicated methods to perform initialization activity. ServletConfig
is the means of getting init parameters which are provided in the configuration file. If the Servlet is not able to initialize itself
properly, it can raise ServletException. After the init returns, the servlet is said to be in ready state.

public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
The Servlet will be asked to handle requests through this method. In the life-cycle of a servlet instance, this method may get
called many times. ServletRequest is a means of obtaining information which has come along with the request. The response
object can be used for setting the response headers and obtaining an output stream, through which we sent the response.

public void destroy()


This will be invoked just before the servlet instance is about to be destroyed.

public ServletConfig getServletConfig()


This method is the means of obtaining ServletConfig object (the same object which was the parameter of init method.

public String getServletInfo()


This method should return the description of the servlet.

3
Deccansoft Software Services Java EE / Servlet Introduction
--------------------------------------------------------------------------------------------------------------------------------------------------------
javax.servlet.GenericServlet is a built-in class which already implements the Servlet Interface. It is an abstract class since it
does not define the service() method. It is not specific to any protocol and hence the name generic. GenericServlet can be
inherited and only service() method is required to be defined. Since the protocol is not yet understood, we have to implement
the protocol handler before the request can be handled.

javax.servlet.http.HttpServlet is a sub-class of GenericServlet. It implements the service() which is specified in the Servlet
interface. This method invokes another service method which is specifically written for HTTP Protocol.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException

HttpServletRequest is a sub-interface of ServletRequest. It exposes all methods of ServletRequest plus some additional
methods which are specific to the HTTP protocol. Same is the case for HttpServletResponse.

The HTTP specific service method will invoke one of the following methods based on the request method used by the client.

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException,IOException

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException

doGet() will be invoked if the request method is GET and doPost() is for POST kind of request.

For writing Servlets in web applications, we write a sub class of HttpServlet and override doGet() or doPost() or both.

Note:
Apart from implementing Servlet interface, GenericServlet has the following characteristics:

1. It implements ServletConfig Interface


2. It provides a simple alternate to the init() method of Servlet interface
public void init() throws ServletException
--------------------------------------------------------------------------------------------------------------------------------------------------------
We should create a separate folder for every web application which we develop. The structure of this folder would be as per
the standard mentioned in the servlet specification. The contents of the web application directory including sub directories will
be accessible to the clients except the contents of a special sub folder called WEB-INF. The WEB-INF folder is the
information folder for the container and hence the contents will not be accessible to the clients.

In WEB-INF folder, there should be file called web.xml. It is the application configuration file which is also called as
Deployment Descriptor.

Web App Folder


|
| a.html
| sub
| | b.html
|
| WEB-INF
| web.xml
| classes
| | *.class
| lib
| *.jar

All the classes which are specific to the current application must be placed under classes’ folder of WEB.INF. If classes are
packaged in a jar file, then the jar file must be placed under lib folder. The classes of the Web application are searched in the
following manner:

In the classes folder


If the class is not found in classes, then the class will be searched in the jar files of the lib folder.

The whole app dir can be made available to the server or we can put the contents in a jar file having an extension called WAR
and make the war file available to the server as part of deployment process.
4
Deccansoft Software Services Java EE / Servlet Introduction
------------------------------------------------------FirstServlet.java---------------------------------------------------------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet


{
public void init() throws ServletException
{
System.out.println(“FirstServlet: init()”);
}

public void destroy()


{
System.out.println(“FirstServlet: destroy()”);
}

protected void doGet(HttpServletRequest request,HttpServletResponse response)


throws IOException,ServletException
{
processRequest(request,response);
}

protected void doPost(HttpServletRequest request,HttpServletResponse response)


throws IOException,ServletException
{
processRequest(request,response);
}

protected void processRequest(HttpServletRequest request,HttpServletResponse response)


throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>My First Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Welcome to the World of Servlets");
out.println("<br><br>");
out.println("REQUEST_METHOD : " + request.getMethod() );
out.println("<br><br>");
out.println("Current Server time is<br>" + new java.util.Date().toString());
out.println("</h1>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}

5
Deccansoft Software Services Java EE / Servlet Introduction
---------------------------------------------- / WEB-INF / web.xml----------------------------------------------------
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

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

<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>
------------------------------------------------- index.html--------------------------------------------------------
<html>
<body>
<h1>Welcome to myapp </h1>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------
myapp
|
|----> index.html
|
|----> WEB-INF
|-----> web.xml
|-----> classes
| |------> FirstServlet.class
|
|-----> src
|------> FirstServlet.java

6
Deccansoft Software Services Java EE / Servlet Introduction
------------------------------------------------WelcomeServlet.java---------------------------------------------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet


{
protected void doGet (HttpServletRequest request,HttpServletResponse response )
throws ServletException , IOException
{
this.processRequest ( request , response ) ;
}

protected void doPost(HttpServletRequest request,HttpServletResponse response )


throws ServletException , IOException
{
this.processRequest ( request , response ) ;
}

protected void processRequest(HttpServletRequest request,HttpServletResponse response )


throws ServletException , IOException
{
response.setContentType ( "text/html" ) ;
PrintWriter out = response.getWriter () ;
String myname = request.getParameter ( "myname" ) ;
String message;
if (myname == null || myname.length () == 0 )
message = "Required information is missing...<a href='index.html'>try again</a>" ;
else
message = "Welcome : " + mynameValue ;
out.println ( "<html>" ) ;
out.println ( "<body>" ) ;
out.println ( "<h1>" ) ;
out.println ( message ) ;
out.println ( "</h1>" ) ;
out.println ( "</body>" ) ;
out.println ( "</html>" ) ;
out.flush();
}
}
-------------------------------------------------------index.html----------------------------------------------------------
<html>
<body bgcolor="pink">
Welcome to myapp <br>
<a href="welcome?myname=Abc">click here</a> <br><br>
<form action="welcome" method="POST">
Enter your name: <input type="text" name="myname" value="">
<input type="submit"name="submit" value="Proceed">
</form>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------
http://localhost:8080/myapp/welcome?myname=Xyz

You might also like