Unit III Servlets
Unit III Servlets
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):
• 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.
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
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 not suitable for file uploading operation It is suitable for file uploading operation
HTTP Servlets
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
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.
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
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FileServlet extends HttpServlet
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”);
String text;
out.println(text);
br.close();} }
Status Codes
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.
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.
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Method Description
HttpSession getSession(boolean create) Gets the session associated with the request
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Cookies in Servlet
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
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.
Method Description