[go: up one dir, main page]

0% found this document useful (0 votes)
60 views18 pages

Unit III Servlets

This document provides an overview of servlet technology, including what servlets are, their advantages over CGI, common interfaces and classes in the Servlet API, and the basic lifecycle of a servlet. Servlets are Java programs that run on a web server and are used to generate dynamic web content. They provide a more robust and scalable alternative to CGI for server-side programming. Key interfaces in the Servlet API include Servlet, HttpServlet, ServletRequest, and ServletResponse. The lifecycle of a servlet involves initialization via the init() method, processing requests via service() and doGet/doPost methods, and destruction via the destroy() method.

Uploaded by

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

Unit III Servlets

This document provides an overview of servlet technology, including what servlets are, their advantages over CGI, common interfaces and classes in the Servlet API, and the basic lifecycle of a servlet. Servlets are Java programs that run on a web server and are used to generate dynamic web content. They provide a more robust and scalable alternative to CGI for server-side programming. Key interfaces in the Servlet API include Servlet, HttpServlet, ServletRequest, and ServletResponse. The lifecycle of a servlet involves initialization via the init() method, processing requests via service() and doGet/doPost methods, and destruction via the destroy() method.

Uploaded by

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

SERVLETS

Servlet technology is used to create a web application. It resides at server side and


generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-
side programming language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to
the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the
response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits over
the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as
follows:
1. Better performance: because it creates a thread for each request, not
process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
4. Secure: because it uses java language.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages,
which are a standard part of the Java's enterprise edition, an expanded version of
the Java class library that supports large-scale development projects.
HTTP (Hyper Text Transfer Protocol)
• The Hypertext Transfer Protocol (HTTP) is application-level protocol for
collaborative, distributed, hypermedia information systems. It is the data
communication protocol used to establish communication between client
and server.
• HTTP is TCP/IP based communication protocol, which is used to deliver
the data like image files, query results, HTML files etc on the World Wide
Web (WWW) with the default port is TCP 80. It provides the standardized
way for computers to communicate with each other.
The Basic Features of HTTP (Hyper Text Transfer Protocol):

• HTTP is media independent: It specifies that any type of media content


can be sent by HTTP as long as both the server and the client can handle the
data content.
• HTTP is connectionless: It is a connectionless approach in which HTTP
client i.e., a browser initiates the HTTP request and after the request is sent
the client disconnects from server and waits for the response.
• HTTP is stateless: The client and server are aware of each other during a
current request only. Afterwards, both of them forget each other. Due to the
stateless nature of protocol, neither the client nor the server can retain the
information about different request across the web pages.
Servlets Architecture

• Read the explicit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers).
This includes cookies, media types
• Process the data and generate the results. This process may require
talking to a database.

Life Cycle of a Servlet (Servlet Life Cycle)

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created,
and not called for any user requests afterwards. So, it is used for one-time
initializations, just as with the init method of applets.
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 servlet, 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 servlet.
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.
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, IOException {
}
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.
The doGet() and doPost() are most frequently used methods with in each service
request. Here is 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.
public 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.
This 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...
}
Difference between doGet() and doPost()
doGet() doPost
It is a default method for any http request It is not a default

It is designed to send limited amount of data It is designed to send unlimited amount of


to the server along with the request data to the server along with the request

The form page generated query string is The form page generated query string is not
visible in the browser address bar. visible in the browser address bar.

It is suitable for decryption operation It is suitable for encryption operation

It is not suitable for file uploading operation It is suitable for file uploading operation

Methods of HttpServlet class(http request type)

There are many methods in HttpServlet class. They are as follows:


1.GET
The GET method is used to retrieve information from the given server using a
given URI. Requests using GET should only retrieve data and should have no other
effect on the data.
2.HEAD
Same as GET, but transfers the status line and header section only.
3.POST
A POST request is used to send data to the server, for example, customer
information, file upload, etc. using HTML forms.
4.PUT
Replaces all current representations of the target resource with the uploaded
content.
DELETE
Removes all current representations of the target resource given by a URI.
CONNECT
Establishes a tunnel to the server identified by a given URI.
OPTIONS
Describes the communication options for the target resource
TRACE
Performs a message loop-back test along the path to the target resource.

HTTP Servlets

The HttpServlet class is an extension of GenericServlet class that includes


methods for handling HTTP specific data. HttpServlet defines a number of
methods, such as doGet(), and doPost(), to handle particular types of HTTP
requests (GET, POST, etc.). These methods are called by the default
implementation of the service() method. service() is defined in GenericServlet
class.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Have you seen this before?
</TITLE></HEAD>”);
out.println(“<BODY><H1>Hello World!</H1></BODY></HTML>”);
}
• The doGet() method is called whenever anyone requests a URL that points
to this servlet. The servlet is installed in the servlets directory and its URL is
http://site:8080/servlet/HelloWorldServlet.
• The doGet() method is actually called by the default service() method of
HttpServlet. The service() method is called by the web server when a request
is made of HelloWorldServlet; the method determines what kind of HTTP
request is being made and dispatches the request to the appropriate doXXX()
method (in this case, doGet()). doGet() is passed two objects,
HttpServletRequest ,and HttpServletResponse, that contain information
about the request and provide a mechanism for the servlet to provide a
response, respectively.
HTTP – Requests

An HTTP client sends an HTTP request to a server in the form of a request


message which includes following format:
• A Request-line
• Zero or more header (General|Request|Entity) fields followed by CRLF
• An empty line (i.e., a line with nothing preceding the CRLF) indicating the
end of the header fields
• Optionally a message-body
Request-Line
The Request-Line begins with a method token, followed by the Request-URI
and the protocol version, and ending with CRLF. The elements are separated by
space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF

Request Header Fields


The request-header fields allow the client to pass additional information about the
request, and about the client itself, to the server. These fields act as request
modifiers.
• Accept-Charset
• Accept-Encoding
• Accept-Language
• Authorization
• Expect
• From
• Host
• If-Match
• If-Modified-Since
• If-None-Match
• If-Range
• If-Unmodified-Since
• Max-Forwards
• Proxy-Authorization
• Range
• Referer
• TE
• User-Agent

Examples of Request Message


GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.abc.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
HTTP – Responses
After receiving and interpreting a request message, a server responds with an
HTTP response message:
• A Status-line
• Zero or more header fields followed by CRLF
• An empty line indicating the end of the header fields
• Optionally a message-body
Status-Line
A Status-Line consists of the protocol version followed by a numeric status code
and its associated textual phrase. The elements are separated by space SP
characters.
status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
HTTP Version
HTTP-Version = HTTP/1.1
Status Code
he Status-Code element is a 3-digit integer where first digit of the Status-Code
defines the class of response and the last two digits do not have any
categorization role.
1xx: Informational
It means the request was received and the process is continuing.
• 2xx: Success
It means the action was successfully received, understood, and accepted.
• 3xx: Redirection
It means further action must be taken in order to complete the request.
• 4xx: Client Error
It means the request contains incorrect syntax or cannot be fulfilled.
• 5xx: Server Error
It means the server failed to fulfill an apparently valid request.
esponse and the last two digits do not have any categorization role.
Response Header Fields
The response-header fields allow the server to pass additional information about
the response which cannot be placed in the Status- Line. These header fields
give information about the server and about further access to the resource
identified by the Request-URI.
• Accept-Ranges
• Age
• ETag
• Location
• Proxy-Authenticate
• Retry-After
• Server
• Vary
• WWW-Authenticate

Examples of Response Message

HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT Content-Length: 88
Content-Type: text/html
Connection: Closed

Error handling
The servlet API gives 2 ways to deal with errors.We can manuallu send error
essage back to the client or we can throw a ServletException.the easiest way to
handle an error is simply to write an error message to the servlets output
stream.This is the appropriate technique to use when the error is part of a normal
operations,such as when a user forget to fill in the required form field.

When the error is standard HTTP error,we should use sendError()method of


HttpServletResponse to tell the server to send a standard error satus
code.HttpServletResponse defines integer constands for all the majour HTTP
status code.

For eg:-

If a servlet cannot find a file the user has requested,it can send a 404(“file not
found ”)error message.in this case we can replace the typical setContentType() and
getWriter()calls with like this

res.sendError(HttpServletResponse.SC_NOT_FOUND,”its dark.i could not find


anything”).

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;
public class FileServlet extends HttpServlet

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException

File r= new File(req.getParameter(“filename”);

FileReader fr= new FileReader(r);;

BufferedReader br= new BufferedReader(fr);;

try

if (!r.isFile())

resp.sendError(resp.SC_NOT_FOUND);

return;

} catch (FileNotFoundException e)

resp.sendError(resp.SC_NOT_FOUND);

return;

resp.setContentType(“text/html”);

PrintWriter out = resp.getWriter();

String text;

while ((text = br.readLine()) != null)

out.println(text);
br.close();} }

Status Codes

When an error is a standard HTTP error, use the sendError() method of


HttpServletResponse to tell the server to send a standard error status code.
HttpServletResponse defines integer constants for all the major HTTP status codes.
Following table lists the most common status codes.

constant Code Default Meaning


Message
SC_OK 200 OK The client's request
succeeded, and the
server's response
contains the requested
data. This is the default
status code.
SC_NO_CONTENT 204 No Content The request succeeded,
but there is no new
response body to
return. A servlet may
find this code useful
when it accepts data
from a form, but wants
the browser view to
stay at the form. It
avoids the "Document
contains no data" error
message.
SC_MOVED_PERMA 301 Moved The requested resource
N ENTLY Permanently has permanently
moved to a new
location. Any future
reference should use
the new locationgiven
by the Location header.
Most browsers
automatically access
the new location
SC_MOVED_TEMPOR 302 Moved The requested resource
ARILY Temporarily has temporarilymoved
to another location, but
futurereferences should
still use the original
URL to access the
resource. The
temporary new location
is given by the
Location header. Most
browsers automatically
access the new location
SC_ UNAUTHORIZED 401 Unauthorized The request lacked
proper
authorization.Used in
conjunction with the
WWW−Authenticate
and Authorization
headers
SC_NOT_FOUND 404 Not Found The requested resource
is not available
SC_INTERNAL_SERV 500 Internal Server An error occurred
ER_ERROR Error inside the server that
prevented it from
fulfilling the request
SC_NOT_ 501 Not The server does not
IMPLEMENTED Implemented support the
functionality needed to
fulfill the request
SC_SERVICE_ 503 Service The server is
UNAVAILABLE Unavailable temporarilyunavailable,
but service should be
restored in the future. If
the server knows when
it will be available
again, a Retry−After
header may alsobe
supplied.

Servlet Chaining
If a client request is processed by group of servlets, then that servlets are known as
servlet chaining or if the group of servlets process a single client request then those
servlets are known as servlet chaining.
In order to process a client request by many number of servlets then we have two
models, they are forward model and include model.
Forward model:
In this model when we forward a request to a group of servlets, finally we get the
result of destination servlet as a response but not the result of intermediate servlets.

Include model:
If a single client request is passed to a servlet and that servlet makes use of other
group of servlets to process a request by including the group of servlets into a
single servlet.

In the above diagram client request goes to servlet s1 and s1 internally includes s2,
s3 and s4 servlets and finally result of all these servlets given to the client by a
source servlet s1.
Note: One servlet can include any number of servlets where as one servlet can
forward to only one servlet at a time.

Custom Servlet Initialization

When a server loads a servlet for the first time, it calls the
servlet's init( ) method and does not make any service calls until init() has
finished. In the default implementation, init( ) simply handles some basic
housekeeping, but a servlet can override the method to perform whatever one-time
tasks are required. This often means doing some sort of I/O-intensive resource
creation, such as opening a database connection. You can also use
the init( ) method to create threads that perform various ongoing tasks. For
instance, a servlet that monitors the status of machines on a network might create a
separate thread to periodically ping each machine.

The default init(ServletConfig) implementation is not a do-nothing


method, so you should remember to always call
the super.init(ServetConfig) method. If you override the parameterless
version, you don't have to invoke the superclass's methodthe server calls the
parameterized version, which calls the parameterless method. You can access
the ServletConfig object using the getServletConfig() method.

The server passes the init( ) method a ServletConfig object, which can


include specific servlet configuration parameters .ServletConfig encapsulates
the servlet initialization parameters, which are accessed via
the getInitParameter( ) and getInitParameterNames( ) methods. 
GenericServlet and HttpServlet both implement
the ServletConfig interface, so these methods are always available in a servlet
and they access the servlet's ServletConfig to retrieve these parameters.

Session Tracking in Servlets


Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the
new request. So we need Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Advantages of Http Sessions in Servlet


 Any kind of object can be stored into a session, be it a text, database, dataset
etc.
 Usage of sessions is not dependent on the client’s browser.
 Sessions are secure and transparent

Disadvantages of Http session


 Performance overhead due to session object being stored on server
 Overhead due to serialization and de-serialization of data

Methods in HttpServlet Interface

Method Description

HttpSession getSession() Gets the HttpSession object. If the


request doesn’t have a session associated
with it, a new session is created

HttpSession getSession(boolean create) Gets the session associated with the request

getId() Returns the unique session id

getCreationTime() It returns the time when this session was


created

getLastAccessedTime() It returns the time when this session was last


acc essed

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet


{
  
    public void doGet(HttpServletRequest request, HttpServletResponse
response)
    {
        try {
            response.setContentType("text/html");
         PrintWriter out = response.getWriter();
  
            String n = request.getParameter("userName");
            out.print("Welcome " + n);
  
            HttpSession session = request.getSession();
  
            session.setAttribute("uname", n);
            out.print("<a href='servlet2'>visit</a>");  
            out.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple


client requests.

A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.

Working of Cookie
By default, each request is considered as a new request. In cookies technique, we
add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the
browser.
Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Methods of Cookie class

Method Description

setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

getName() Returns the name of the cookie. The name cannot be


changed after creation.

getValue() Returns the value of the cookie.

setName(String name) changes the name of the cookie.

setValue(String value) changes the value of the cookie.

You might also like