UNIT 3: SERVLET
TITLE OF PAPER: ADVANCED JAVA
UNIT 3: SERVLET
3.1 Introduction
Servlets are small programs that execute on server side of a web connection. A
servlet runs inside a JVM on a server. They are secure, portable & easy to use
replacement for CGI[Common Gateway Interface].
Servlet is a dynamically loaded module that services request from web server &
execute within java virtual machine. Because the servlet is running on the server
side it does not depend on browser compatibility.
“Servlets are programs that runs on the web server or application server & acts as a
middle layer between a request coming from a web browser or other HTTP clients
& databases or applications on the HTTP server”
A java servlet is a java object that response to HTTP request. It runs inside a servlet
container. A servlet is a part of java web application. A servlet container may run
multiple web applications at the same time each having multiple servlets running
inside.
1
UNIT 3: SERVLET
Execution of Servlets basically involves six basic steps:
A. The clients send the request to the webserver.
B. The web server receives the request.
C. The web server passes the request to the corresponding servlet.
D. The servlet processes the request and generates the response in the form of
output.
E. The servlet sends the response back to the webserver.
F. The web server sends the response back to the client and the client browser
displays it on the screen.
Servlet technology is used to create a web application (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.
3.2 Web Application
A web application is an application accessible from the web. A web application is
composed of web components like Servlet, JSP, Filter, etc. and other elements such as
HTML, CSS, and JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.
3.2 CGI
CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request, it
starts a new process.
2
UNIT 3: SERVLET
Disadvantages of CGI
A. If the number of clients increases, it takes more time for sending the
response.
B. For each request, it starts a process, and the web server is limited to start
processes.
C. For each request, it starts a process, and the web server is limited to start
processes.
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
3
UNIT 3: SERVLET
the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low.
A. Better performance: because it creates a thread for each request, not
process.
B. Portability: because it uses Java language.
C. Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
D. Secure: because it uses java language.
3.3 Difference between Servlet and CGI
Servlet CGI
It is thread based i.e., for every new It is process based i.e., for every new
request thread is created. request process is created.
In servlet sharing data is possible. Data sharing is not possible.
Servlet it is a portable. It is not portable.
It remains in the memory unit it is not It removes from the memory after the
explicitly destroyed. completion of process-based request.
It can use any of the web server. It can use the web server that supports it.
It links directly to the server. It doesn’t link the web server directly to
the server.
It can read & get HTTP server. It can neither read not set HTTP server.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
3.3 Types of Servlets
Servlet must implement the interface javax.servlet.Servlet. There are two main types of
servlets
Generic Servlet extends javax.servlet.GenericServlet. Generic servlet are protocol
independent it means that they contain no inherent support for http or any other
transport protocol.
4
UNIT 3: SERVLET
HTTP Servlet extend javax.servlet.HttpServlet these servlets have built in support
for HTTP protocol & much more useful in the browser environment All the
Servlets extend from HTTP Servlet rather than from generic servlet in order to take
advantages of this built in HTTP Support.
For both type of Servlet, we Can implement the Constructure method init() & the
destructor method destroy(). If we need to initialized or deallocate the resources.
Servlets are platform independent served side Component being rather in java To
write a Servlet there are 3 ways.
A. By implementing Servlet [Interface]
B. By extending Generic Servlet [ It is an abstract class]
C. By extending HttpServlet [ It is abstract class)
Generic Servlet HttpServlet
It is defined by javax.servlet package. It is defined by javax.servlethttp package.
It describes protocol independent servlet. It describes protocol dependent servlet.
It is must use service() as it is a callback(). Being service() is non abstract it can be
replaced by doGET(), doPOST() methods.
Direct sub-class of servlet interface Direct sub-class of generic servlet
Extend object & implement interfaces It extends generic servlet & implements
servlet, servlet config & serializable interface serializable
It is an immediate child class of servlet It is an immediate child class of generic
interface servlet class
Not Use Nowdays Use always
3.4 Servlets Lifecycle
The Servlet life cycle mainly goes through four stages,
A. Loading a Servlet.
B. Initializing the Servlet.
C. Request handling. D. Destroying the Servlet.
5
UNIT 3: SERVLET
Servlet class is loaded
The class loader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.
init method is invoked
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
service method is invoked
The web container calls the service method each time when request for the servlet
is received. If servlet is not initialized, it follows the first three steps as described
above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:
6
UNIT 3: SERVLET
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
destroy method is invoked
The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
public void destroy()
3.5 Session Tracking
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of a 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 to maintain the state of a user to recognize to particular
user.
HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
We use session tracking to recognize the user It is used to recognize the
particular user.
7
UNIT 3: SERVLET
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HTTPSession
3.6 Cookie Class
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.
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.
There are 2 types of cookies in servlets.
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.
2. 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.
8
UNIT 3: SERVLET
Advantage
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
3.7 Servlet – JDBC
Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver. Properties of
Servlets are as follows:
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from the webserver.
Prerequisites:
Basic Servlet knowledge.
JDBC connection in Java.
We can use any database to store the data, in this example, the PostgreSQL database
management system is used.
SQL Language – Insert, Delete, Update & Select statements.
Eclipse IDE and Tomcat server.
9
UNIT 3: SERVLET
3.8 Programs
1) Write a SERVLET program which counts how many times a user has visited a
web page. If user is visiting the page for the first time, display a welcome message. If
the user is revisiting the page, display the number of times visited.(Use Cookie)
VisitServlet.Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class VisitServlet extends HttpServlet
{
static int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
10
UNIT 3: SERVLET
if(j==1)
{
out.println("Welcome");
}
else
{
out.println("You visited "+i+" times");
}
i++;
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>VisitServlet</servlet-name>
<servlet-class>VisitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VisitServlet</servlet-name>
<url-pattern>/servlet/VisitServlet</url-pattern>
</servlet-mapping>
</web-app>
11
UNIT 3: SERVLET
2) Write a SERVLET program to change inactive time interval of session.
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Timeout extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
out.println("<BODY><H1>Session Timer</H1>");
// Display the previous timeout
out.println("The previous timeout was " +
session.getMaxInactiveInterval());
out.println("<BR>");
// Set the new timeout
session.setMaxInactiveInterval(2*60*60); // two hours
// Display the new timeout
out.println("The newly assigned timeout is " +
session.getMaxInactiveInterval());
12
UNIT 3: SERVLET
out.println("</BODY></HTML>");
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>Timeout</servlet-name>
<servlet-class>Timeout</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Timeout</servlet-name>
<url-pattern>/servlet/Timeout</url-pattern>
</servlet-mapping>
</web-app>
13
UNIT 3: SERVLET
3) Write a SERVLET program that provides information about a HTTP request
from a client, such as IP address and browser type. The servlet also provides
information about the server on which the servlet is running, such as the operating
system type, and the names of cur
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servletinfo extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html><body><h2>Information about Http Request</h2>");
pw.println("<br>Server Name: "+request.getServerName());
pw.println("<br>Server Port: "+request.getServerPort());
pw.println("<br>Server Addr: "+request.getRemoteAddr());
pw.println("</body></html>");
pw.close();
}
14
UNIT 3: SERVLET
4)Write a SERVLET program in java to accept details of student
(SeatNo,Stud_Name, Class, Total_Marks). Calculate percentage and grade obtained
and display details on page.
Studentinfo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="f1" method="Post" action="Servletdemo">
<fieldset>
<legend><b><i>Enter Student Details:</i></b></legend>
Enter Roll No: <input type="text" name="txtsno"><br><br>
Enter Name: <input type="text" name="txtnm"><br><br>
Enter Class: <input type="text" name="txtclass"><br><br>
<fieldset>
<legend><b><i>Enter Student Mark Details:</i></b></legend>
Subject 1: <input type="text" name="txtsub1"><br><br>
Subject 2: <input type="text" name="txtsub2"><br><br>
Subject 3: <input type="text" name="txtsub3"><br><br>
<input type="submit" name="Submit">
</fieldset>
</fieldset>
15
UNIT 3: SERVLET
</form>
</body>
</html>
Servletdemo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servletdemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int sno,s1,s2,s3,total;
String snm,sclass;
float per;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
sno=Integer.parseInt(request.getParameter("txtsno"));
snm=request.getParameter("txtnm");
sclass=request.getParameter("txtclass");
s1=Integer.parseInt(request.getParameter("txtsub1"));
s2=Integer.parseInt(request.getParameter("txtsub2"));
16
UNIT 3: SERVLET
s3=Integer.parseInt(request.getParameter("txtsub3"));
total=s1+s2+s3;
per=(total/3);
out.println("<html><body>");
out.println("<h2>Result of student</h2><br>");
out.println("<b><i>Roll No :</b></i>"+sno+"<br>");
out.println("<b><i>Name :</b></i>"+snm+"<br>");
out.println("<b><i>Class :</b></i>"+sclass+"<br>");
out.println("<b><i>Subject1 :</b></i>"+s1+"<br>");
out.println("<b><i>Subject2 :</b></i>"+s2+"<br>");
out.println("<b><i>Subject3 :</b></i>"+s3+"<br>");
out.println("<b><i>Total :</b></i>"+total+"<br>");
out.println("<b><i>Percentage :</b></i>"+per+"<br>");
if(per>50)
out.print("<h1><i>Pass Class</i></h1>");
else if(per<55 && per>50)
out.print("<h1><i>Second Class</i></h1>");
else if(per<60 && per>=55)
out.print("<h1><i>Higher Class</i></h1>");
out.close();
}
}
Copyright © 2023 Tejas.R.Shinde[SYB.B.A(C.A)]
All Rights Reserved.
17