Sei sulla pagina 1di 205

2160707

Advanced Java

Unit-3
Servlet API and
Overview

Prof. Swati R. Sharma


swati.sharma@darshan.ac.in
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

Reference Book:
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric
Buest Wiley Publication
Chapter 6,7,8

ADVANCED
Unit-3
Unit-3 Servlet
ADVANCED JAVA
Servlet API
API--and
JAVA 2160707
and Overview
2160707
Overview Darshan
Darshan
Darshan Institute
Darshan Institute
Institute of
of of
Institute Engineering
of Engineering
Engineering && Technology
Engineering && Technology
Technology
Technology
What is Servlet?
“ Servlet is java class
which
extends the functionality of web server
by
dynamically generating web pages.”

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 3 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet: Basic Terms
 Before looking into Servlet, we will see some important keywords
about web application.
Web Client: We will call browsers (IE, Chrome, Mozilla
etc.) as a Client, which helps in communicating with the
server
Http Request

 Server and Client (browser) will


communicate with each other with
the help of HTTP protocol.
Web Server is the one which takes the
Client client request, process the request and
Server
sends back the response.

Http Response

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 4 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Introduction
 Servlet technology is used to create Dynamic web application
 Servlet technology is robust and scalable .
 Before Servlet, CGI (Common Gateway Interface) scripting
language was popular as a server-sideChanges
programming
with respectlanguage,
to time but
there were many disadvantages of this technology.

1. To retrive server’s current


DATE and Time
2. News paper clippings
3. Online Shopping
e.g. Virtual Dressing Room
..
.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 5 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Why we need Servlet?
 Nowadays everything is available on Internet.
 Starting from e-banking, e-commerce everything is available
through Hey
internet. We
Server, I want call given
to display all these applications as Web
applications.
name in my web page Sorry, I can’t do
that Dynamic
computation

Hi, I am Servlet.
But I have
Let me anyou
help
application named
to display given
SERVLET, which
name in your web
can
page.process your
request

Client Dynamic Response Server

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 6 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Scripting Language

7
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 7 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Scripting Language
Server-Side Client-Side
Scripting Language Scripting Language

PHP JavaScript
ASP.NET VBScript
(C# OR Visual Basic) HTML (Structure)
C++ CSS (Designing)
Java and JSP AJAX
Python jQuery etc.
Ruby on Rails etc.

Client-side scripting is an
Server-side scripting is often
important part of the Dynamic
used to provide a customized
HTML. Usually run on client’s
interface for the user.
browser.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 8 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
CGI (Common Gateway Interface)
 CGI was the 1st server-side scripting technique for creating
dynamic content.
 CGI is used to execute a program that resides in the server to
process data or access databases to produce the relevant dynamic
content.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 9 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
CGI (Common Gateway Interface)
 For each request CGI Server receives, It creates new Operating
System Process.

 If the number of requests from the client increases then more


time it will take to respond to the request.
 As programs executed by CGI Script are written in the native
languages such as C, C++, perl which are not portable.

Image Reference:http://www.c4learn.com/java/servlet/servlet-vs-cgi/

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 10 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Comparing Servlet with CGI
 CGI programs are used to execute programs written inside the
native language.
 While in Servlet, all the programs are compiled into the Java
bytecode, which is then run in the Java virtual machine.
 In Servlet, all the requests coming from the Client are processed
with the threads instead of the OS process.

Image Reference:http://www.c4learn.com/java/servlet/servlet-vs-cgi/

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 11 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Summary: CGI vs Servlet
CGI Servlet
CGI was not portable. Servlets are portable.
In CGI each request is handled by In Servlets each request is
heavy weight OS process. handled by lightweight Java
Thread.
Session tracking and caching of Session tracking and caching of
previous computations cannot be previous computations can be
performed. performed
CGI cannot handle cookies. Servlets can handle cookies.
CGI does not provide sharing Servlets can share data among
property. each other.
CGI is more expensive than Servlets is inexpensive than CGI.
Servlets

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 12 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle

13
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 13 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle

init() destroy()
Servlet
In Service

i. Servlet class is loaded.


ii. Servlet instance is
created.
iii. init() method is service()
invoked.

Servlet Container

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 14 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: init()
i. Servlet class is loaded
The classloader 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.

A Web application runs within a


ii. Servlet instance is created Web container of a Web server. Web
The web container creates the instance of acontainer
servlet afterprovides
loading theruntime
servlet
class. The servlet instance is created only onceenvironment.
in the servlet life cycle.

iii. 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.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 15 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: init()
Syntax:

public void init(ServletConfig config) 
throws ServletException  
{
//initialization…
A servlet configuration object used by a
} servlet container to pass information to a
servlet during initialization process.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 16 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Packages
Package javax.servlet
Servlet interface needs to be
Interface

implemented for creating any servlet.  It


Servlet provides 3 life cycle methods. 

Implemented by
It provides implementation of methods
GenericServlet of Servlet interfaces.
extended by
Class

Contains interface and abstract class for


HttpServlet servlet that understands HTTP protocol.
extended by Package: javax.servlet.http

MyServlet User defined Servlet class.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 17 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Service()
 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 response back to the client.
 Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 18 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Service()
Syntax:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException
{


}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 19 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Service()
 The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
 The doGet() and doPost() are most frequently used methods with
in each service request.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 20 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Destroy()
 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
i. database connections,
ii. halt background threads,
iii. write cookie lists or hit counts to disk, and
iv. perform other such cleanup activities.
 After the destroy() method is called, the servlet object is marked
for garbage collection.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 21 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Destroy()
public void destroy()
{
// Finalization code...
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 22 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet() v/s doPost()

23
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 23 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet()
A GET request results from request for a URL or from an HTML form,
should be handled by doGet() method.
Syntax:
public void doGet
(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code …
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 24 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doPost()
A POST request results from an HTML form that specifically lists POST
as the METHOD and it should be handled by doPost() method.
Syntax:
public void doPost
(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code …
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 25 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet() vs doPost()
 doGet() and doPost() are HTTP requests handled by servlet
classes.
 In doGet(), the parameters are appended to the URL and sent
along with the header information. 
 In doPost(), the parameters are sent separately.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 26 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet() vs doPost()
Application
 doGet() shall be used when small amount of data and insensitive
data like a query has to be sent as a request.
 doPost() shall be used when comparatively large amount of
sensitive data has to be sent.
E.g.
Sending data after filling up a form or sending login & password.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 27 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet() vs doPost()
 Example: doGet()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 28 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet() vs doPost()
doGet() doPost()
In this method, parameters are appended to In doPost(), parameters are sent in separate
the URL and sent along with header line in the body 
information
Maximum size of data that can be sent using There is no maximum size for data 
doGet() is 240 bytes
Parameters are not encrypted Parameters are encrypted  here
Application: Application:
Used when small amount of data and Used when comparatively large amount of
insensitive data like a query has to be sent as sensitive data has to be sent.
a request. E.g. submitting sign_in or login form.
It is default method.

doGet() is faster comparatively doPost() is slower compared to doGet() since


doPost() does not write the content length

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 29 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 30 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
GTU Questions
1. List and Explain various stages of Servlet life cycle. Sum’16
Explain role of web container.[7] Win’17
Win’18
2. Consider a scenario in which 4 users are accessing a Sum’16
servlet instance. Among which one user called destroy()
method. What happens to the rest 3 users?[1]
3. GenericServlet vs HttpServlet [3] Sum’16
Win’18
4. Servlets vs CGI [3] Sum’16

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 31 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Life Cycle: Servlet Code
import java.io.*;
import javax.servlet.*;
public class MyServlet1 extends GenericServlet
{
public void init() throws ServletException
{//Initailization Code
}
public void service(ServletRequest request,
ServletResponse response) throws
ServletException,IOException
{//Servlet code
}
public void destroy()
{//Finalization Code
}
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 32 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps to run Servlet Program in

Using Netbeans IDE

33
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 33 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps to run Servlet Program
 Step 1: Open Netbeans IDE, Select File -> New Project

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 34 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Step 2: Select Java Web -> Web Application, then click on Next

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 35 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
 Step 3: Give a name to your project and click on Next,

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 36 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
 Step 4: and then, Click Finish

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 37 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
 Step 5: The complete directory structure required for the Servlet
Application will be created automatically by the IDE.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 38 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Step 6: To create a Servlet, open Source Package, right click on default
packages -> New -> Servlet.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 39 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
 Step 7: Give a Name to your Servlet class file

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 40 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program

It will add servlet


Web.xml is the
information to
configuration file of
web.xml file
web applications in
java.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 41 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Step 8: Write servlet code: MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{ String msg="";
PrintWriter out;
public void init() throws ServletException
{ msg="hello world: my first servlet program"; }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
out=response.getWriter();
out.println(msg);
}
public void destroy()
{ out.close();
}
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 42 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
MIME:Multipurpose Internet Mail Extensions
 A MIME type nomenclature includes a type and subtype separated by a forward slash.
 It is a HTTP header that provides the description about what are you sending to the
browser.
1.text/html
2.text/plain
3.text/css
4.text/richtext
5.application/msword
6.application/jar
7.application/pdf
8.images/jpeg images/png images/gif
9.audio/mp3
10.video/mp4
MIME is a standard set to Internet to notify the format of the file contents.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 43 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Step 9: index.html

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 44 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Step 10: open web.xml

It is used to
Configuration
map Servlet to of servlet
using <servlet> Map the servlet to a URL. This can be done using
specific URL
<servlet-mapping> element.
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 45 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Step 11: Run your application, right click on your Project and select Run

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 46 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Steps for Servlet Program
Output:

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 47 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
javax.servlet Interface

48
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 48 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
javax.servlet Interface
It is used to get configuration
Javax.servlet
information from web.xml file. If the
configuration information is modified
ServletConfig from the web.xml file, we don't need
to change the servlet. 

ServletContext It provides an interface between the


container and servlet. It is global to
entire web application

ServletRequest It is used to provide the client request


information to a servlet such as
content type, content length,
ServletResponse parameter names and values, header
informations,
It contains attributes 
various methods that
enable a servlet to respond to the
client requests. A servlet can send the
response either as character or binary
data. 
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 49 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Types of Servlet
 Generic Servlet
• javax.servlet (package)
• extends javax.servlet.Servlet
• service method

service(ServletRequest req, ServletResponse res)

 Http Servlet
• javax.servlet.http (package)
• extends javax.servlet.HttpServlet
• doGet(), doPost()….

doGet(HttpServletRequest req,HttpServletResponse res)


doPost(HttpServletRequest req,HttpServletResponse res)

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 50 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Generic Servlet: Method Summary
void init(ServletConfig config) It is used to initialize the servlet. It is called once,
automatically, by the network service each time
it loads the servlet.
abstract void It provides service for the incoming request. It is
service (ServletRequest request, invoked at each time when user requests for a
ServletResponse response) servlet.
void destroy() It is invoked only once throughout the life cycle
and indicates that servlet is being destroyed.
ServletConfig getServletConfig() returns the object of ServletConfig.
ServletContext getServletContext() returns the object of ServletContext.
String returns the parameter value for the given
getInitParameter(String name) parameter name.
Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
String getServletName() returns the name of the servlet object.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 51 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServlet: Method Summary
protected void It receives the request from the service method,
service(HttpServletRequest req, and dispatches the request to the doXXX() method
HttpServletResponse res) depending on the incoming http request type.
protected void handles the GET request. It is invoked by the web
doGet(HttpServletRequest req, container.
HttpServletResponse res)
protected void handles the POST request. It is invoked by the web
doPost(HttpServletRequest req, container.
HttpServletResponse res)

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 52 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
GenericServlet vs HttpServlet
GenericServlet HttpServlet
javax.servlet.GenericServlet javax.servlet.http.HttpServlet
It defines a generic, protocol- It defines a HTTP protocol specific
independent servlet. servlet.
GenericServlet is a super class of HttpServlet is a sub class of
HttpServlet class. GenericServlet class.
Can handle all types of protocols only HTTP specific protocols.
It supports only one abstract It support doGet(), doPost() etc.
method:service()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 53 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Deployment Descriptor

web.xml

54
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 54 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Deployment Descriptor
 Located @ WEB-INF directory
 File known as web.xml
 It controls the behavior of Java Servlet
 What does it contain?
• XML Header
• DOCTYPE
• Web-app element
The Web-app element should contain a servlet element with 3 sub-
element.
1. <servlet-name>: name used to access java servlet
2. <servlet-class>: class name of java servlet
3. <init-param>: for initialization parameter

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 55 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Deployment Descriptor: web.xml
<?xml version="1.0" encoding="UTF-8"?> xml header
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet> Configures a web application. Document Type Definition
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class> Name used to access
<init-param> Java Servlet
<param-name>name</param-name>
<param-value>cxcy</param-value> Name of servlet .java
</init-param> class
</servlet>
<servlet-mapping> Used to pass parameters to a servlet from the web.xml file.
<servlet-name>MyServlet</servlet-name>
map the servlet to a
<url-pattern>/MyServlet</url-pattern> URL or URL pattern
</servlet-mapping>
</web-app> Controls behavior of
Servlet
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 56 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Program to call servlet from html file

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 57 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Program
Write a java Servlet program to call servlet from html hyperlink.
2.html
<html>
<head>
<title> HyperLinkDemo </title>
</head>
<body>
<a href =
"/ServletDemo2/HyperLinkDemo">HyperLinkDemo.java
</a>
</body>
</html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 58 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Program: HyperLinkDemo.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class HyperLinkDemo extends HttpServlet
5. { String msg="";
6. PrintWriter out;
7. public void init(ServletConfig config)throws ServletException
8. { msg="hello world! MY first Servlet Program...";
9. }
10. public void doGet(HttpServletRequest request,HttpServletResponse
response) throws ServletException,IOException
11. { response.setContentType("text/html");
12. out=response.getWriter();
13. out.println("<h1>"+msg+"</h1>");
14. }
15. public void destroy()
16. { out.close();
17. }}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 59 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Program: Output

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 60 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doGet()

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 61 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServlet : 1.html
<html>
<head>
<title> DoGetDemo </title>
</head>
<body>
<form action="/ServletDemo2/DoGetDemo">
Enter Email:<input type="text" name="email">
<p><input type="submit"></p>
</form>
</body>
</html>
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 62 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServlet: DoGetDemo.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class DoGetDemo extends HttpServlet
5. { PrintWriter out;
6. public void init(ServletConfig config)throws ServletException
7. { }
8. public void doGet(HttpServletRequest request,HttpServletResponse
response)
9. throws ServletException,IOException
10. {
11. String email=request.getParameter("email");
12. response.setContentType("text/html");
13. out =response.getWriter();
14. out.println("my email:"+email); String getParameter(String name)
15. } Returns the value of a request
16. public void destroy() parameter as a String
17. { out.close(); }
18. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 63 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Output

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 64 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
doPost()

Write a Servlet program to enter two


numbers and find maximum among
them.

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 65 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet program: doPost()

.html .java
[Servlet]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 66 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet program using doPost()
max.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Maximum number </title>
5. </head>
6. <body>
7. <form action="/ServletTemp/Max" method="POST" >
8. <p>Enter No-1:<input type="text"
name="no1"></p>
9. <p>Enter No-2:<input type="text"
name="no2"></p>
10. <p><input type="submit"></p>
11. </form>
12. </body>
13.</html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 67 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet program using doPost()
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class Max extends HttpServlet
5. { public void doPost(HttpServletRequest request, HttpServletResponse
response)throws ServletException,IOException
6. { int n1=0,n2=0;
7. response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. n1=Integer.parseInt(request.getParameter("no1"));
10. n2=Integer.parseInt(request.getParameter("no2"));
11. if(n1>n2)
12. out.println("n1="+n1+"is max number");
13. else if(n2>n1)
14. out.println("n2="+n2+"is max number");
15. else if(n1==n2)
16. out.println("n1= "+n1+"and n2= "+n2+"are equal numbers");
17. }
18.}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 68 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet program using doPost()
Executing max.html

Using doPost()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 69 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet program using doGet()

Using doGet()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 70 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
ServletConfig Interface

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 71 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Config
 It is used to get configuration information from web.xml file.
 If the configuration information is modified from the web.xml file,
we don't need to change the servlet. 
Method
String getInitParameter(String name) Returns the parameter value for the specified
parameter name.

Example
String str = config.getInitParameter("name")

web.xml
<init-param>
<param-name>name</param-name>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 72 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Config: web.xml
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>cxcy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 73 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Config: MyServlet.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class MyServlet extends HttpServlet
5. { String msg;
6. PrintWriter out;
7. public void init(ServletConfig config)throws ServletException
8. { msg = config.getInitParameter("name"); }
9. public void doGet(HttpServletRequest request ,
HttpServletResponse response) throws
10. ServletException,IOException
11. { response.setContentType("text/html");
12. out = response.getWriter();
13. out.println("<h1>"+ msg +"</h1>");
14. }
15. public void destroy()
16. { out.close(); }}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 74 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Config: Output

<param-value>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 75 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
ServletContext Interface

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 76 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
ServletContext Interface
 ServletContext is created by the web container at time of
deploying the project.
 It can be used to get configuration information from web.xml file.
 There is only one ServletContext object per web application.
 If any information is shared to many servlet, it is better to provide
it from the web.xml file using the <context-param> element.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 77 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Context Parameter Initialized inside web.xml
<web-app>  
 ...
  <context-param>  
    <param-name>parametername</param-name>  
    <param-value>parametervalue</param-value>  
  </context-param>  
 ...   
<servlet> used to define
... initialization parameter
in the application scope.
</servlet>
</web-app>  

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 78 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>ServletContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemo</servlet-name>
<url-pattern>/ServletContextDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>DIET</param-value>
</context-param>
</web-app>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 79 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
ServletContextDemo.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class ServletContextDemo extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse
res) throws ServletException,IOException
6. { res.setContentType("text/html");
7. PrintWriter out=res.getWriter();
8. //creating ServletContext object
9. ServletContext context=getServletContext();
10. //Getting the value of the initialization parameter and
printing it
11. String college=context.getInitParameter("name");
12. out.println("College name is="+college);
13. out.close();
14. }}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 80 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Output

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 81 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Config vs Servlet Context
Servlet Config Servlet Context
ServletConfig object is one per servlet class ServletContext object is global to entire web
application
Object of ServletConfig will be created Object of ServletContext will be created at
during initialization process of the servlet the time of web application deployment
Scope: As long as a servlet is executing, Scope: As long as web application is
ServletConfig object will be available, it will executing, ServletContext object will be
be destroyed once the servlet execution is available, and it will be destroyed once the
completed. application is removed from the server.

We should give request explicitly, in order to ServletContext object will be available even
create ServletConfig object for the first time before giving the first request
In web.xml – <init-param> tag will be appear In web.xml – <context-param> tag will be
under <servlet-class> tag appear under <web-app> tag

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 82 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Program
 Write a java program to accept one String from ServletConfig
object and another from ServletContext object and Concat both
the String. Display the String and String Length.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 83 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest

Methods

84
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 84 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String getContextPath() Returns the portion of the request URI that indicates the context
of the request.
Enumeration Returns an enumeration of all the header names this request
 getHeaderNames() contains.
String Returns the value of the specified request header as a String.
getHeader(String name)
String getQueryString() Returns the query string that is contained in the request URL
after the path. 
String getServletPath() Returns the part of this request's URL that calls the servlet. This
path starts with a "/" character and includes either the servlet
name or a path to the servlet
String getMethod() Returns the name of the HTTP method with which this request
was made, for example GET or POST

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 85 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String getContextPath() Returns the portion of the request URI that indicates the context
of the request.

Example

public void doGet(HttpServletRequest request,


HttpServletResponse response)
{
out.println("<p>request.getContextPath():"
+request.getContextPath()+"</p>");
}

Output
request.getContextPath():/ServletTemp

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 86 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
Enumeration Returns an enumeration of all the header names this request
 getHeaderNames() contains.

Example
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
Enumeration h=request.getHeaderNames();
while(h.hasMoreElements())
{
String paramName = (String)h.nextElement();
out.print("<p>" + paramName + "\t");
String paramValue = request.getHeader(paramName);
out.println( paramValue + "</p>\n");
}
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 87 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Output
1. host localhost:8080
2. user-agent Mozilla/5.0 (Windows NT 6.2; WOW64;
rv:50.0) Gecko/20100101 Firefox/50.0
3. accept text/html,application/xhtml+xml,
application/xml;q=0.9,*/*;q=0.8
4. accept-language en-US,en;q=0.5
5. accept-encoding gzip, deflate
6. connection keep-alive
7. upgrade-insecure-requests 1

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 88 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String Returns the value of the specified request header as a String.
getHeader(String name)

Example
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
out.println("<p>request.getHeader(): "
+request.getHeader("host")+"</p>");
out.println("<p>request.getHeader(): "
+request.getHeader("referer")+"</p>");
}
Output
request.getHeader():host=localhost:8080
request.getHeader():referer=http://localhost:8080
/ServletTemp/servletmeth.html

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 89 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String getQueryString() Returns the query string that is contained in the request URL
after the path. 

Example
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
out.println("<p>request.getQueryString():"
+request.getQueryString()+"</p>");

}
Output

request.getQueryString(): no1=1&no2=2

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 90 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String getServletPath() Returns the part of this request's URL that calls the servlet. This
path starts with a "/" character and includes either the servlet
name or a path to the servlet

Example
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
out.println("<p>request.getServletPath():"
+request.getServletPath()+"</p>");
}
Output

request.getServletPath(): /ServletMeth

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 91 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpServletRequest: Methods
String getMethod() Returns the name of the HTTP method with which this request
was made, for example GET or POST

Example
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
out.println("<p>request.getMethod():"
+request.getMethod()+"</p>");
}
Output
request.getMethod(): GET

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 92 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Collaboration

RequestDispatcher Interface

93
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 93 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
javax.servlet.RequestDispatcher Interface

 The RequestDispatcher interface provides the facility of


dispatching the request to another resource.
 Resource can be HTML, Servlet or JSP.
 This interface can also be used to include the content of another
resource.
 It is one of the way of servlet collaboration.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 94 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher :Method
void forward(ServletRequest request, Forwards a request from a servlet to
ServletResponse response) another resource (servlet, JSP file, or
throws ServletException, IOException HTML file) on the server.

void include(ServletRequest request, Includes the content of a resource


ServletResponse response) (Servlet, JSP page, or HTML file) in the
throws ServletException, IOException response.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 95 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: forward()
Step2:
forward(req, res)
uest Servlet 1 Servlet 2
eq
:R
t e p1
S

Step 3:
Response Response is
generated

Web Client
Step 4: R
esponse
is sent b
a ck to bro Response
wser

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 96 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: include()
Step2: include(req, res)

u e st Servlet 1 Servlet 2
: Req
p 1 Step3:
Ste
Response of Servlet 2
is included in the
Response of Servlet 1 Response

Web Client

Final
R
back esponse Response
to th is sen
Serv e
let 1 client fr t
on

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 97 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
How to get the object of RequestDispatcher?
The getRequestDispatcher() method of ServletRequest interface
returns the object of RequestDispatcher.
Syntax
RequestDispatcher getRequestDispatcher(String resource)

Name of Servlet specified in <url-pattern>


Example
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);//method may be include/forward 
 

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 98 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: forward()
Example: forward()

RequestDispatcher rd =
request.getRequestDispatcher("servlet2");
rd.forward(request, response);

RequestDispatcher rd =
request.getRequestDispatcher("/1.html");
rd.forward(request, response);

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 99 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: include()
Example: include()

RequestDispatcher rd=
request.getRequestDispatcher("servlet2");
rd.include(request, response);

RequestDispatcher rd=
request.getRequestDispatcher("/1.html");
rd.include(request, response);

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 100 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: Servlet Program

Validate Servlet
[CallServlet.java]

Yes IsValid No
?
[include: 1.html]
[forward: FwdDemo.java]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 101 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: 1.html
1. <html>
2. <head>
3. <title>1.html</title>
4. </head>
5. <body>
6. <form action="/Dispatcher/CallServlet"
method="POST">
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="text" name="pwd"></p>
9. <p><input type="submit" value="Sign In"></p>
10. </form>
11. </body>
12. </html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 102 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: Validate Servlet
1. public class CallServlet extends HttpServlet
2. { public void doPost(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. { response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. RequestDispatcher rd;
7. String login=request.getParameter("login");
8. String pwd=request.getParameter("pwd");
9. if(login.equals("java") && pwd.equals("servlet"))
10. { rd=request.getRequestDispatcher("FwdDemo");
11. rd.forward(request, response);}//if
12. else
13. { out.println("<p><h1>Incorrect Login Id/Password
</h1></p>");
14. rd=request.getRequestDispatcher("/1.html");
15. rd.include(request, response); }//else }//dopost }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 103 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: fwdDemo.java
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class FwdDemo extends HttpServlet{
5. public void doPost(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String username=request.getParameter("login");
10. out.println("<h1>"+"Welcome "+username+"</h1>");
11. }
12. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 104 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
RequestDispatcher: web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>FwdDemo</servlet-name>
4. <servlet-class>disp.FwdDemo</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>CallServlet</servlet-name>
8. <servlet-class>disp.CallServlet</servlet-class>
9. </servlet>

10. <servlet-mapping>
11. <servlet-name>FwdDemo</servlet-name>
12. <url-pattern>/FwdDemo</url-pattern>
13. </servlet-mapping>
14. <servlet-mapping>
15. <servlet-name>CallServlet</servlet-name>
16. <url-pattern>/CallServlet</url-pattern>
17. </servlet-mapping>
18.</web-app>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 105 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Collaboration

sendRedirect()
javax.servlet.http.HttpServletResponse

106
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 106 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
SendRedirect
 The sendRedirect() method of HttpServletResponse interface can
be used to redirect response to another resource, it may be servlet,
jsp or html file.
Syntax
void sendRedirect(String location)
throws IOException

Example
response.sendRedirect("http://www.darshan.ac.in");
response.sendRedirect("/1.html");//relative path  
response.sendRedirect("http://localhost:8080/1.html");  
//absolute path

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 107 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
sendRedirect(): Example
1. public class Redirect extends HttpServlet
2. { public void doGet( HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. { response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. String login=request.getParameter("login");
7. String pwd=request.getParameter("pwd");
8. if(login.equals("java") && pwd.equals("servlet"))
9. { response.sendRedirect("/Dispatcher/Welcome");
10. }
11. else
12. response.sendRedirect("/Dispatcher/redirect.html");
13. } //doGet
14. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 108 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
GTU Questions
1. Differentiate the following
i. forward() vs include() method of RequestDispatcher
ii. forward() vs sendRedirect()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 109 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Cookies and Session Management

Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 110 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management in Servlets
What is Session?

A session refers to the entire interaction between

a client and a server

from the time of the client’s first request,

which generally begins the session,

to the time of last request/response.


Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 111 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management in Servlets
Why we require Session?
 HTTP is a "stateless" protocol which means each time a client
retrieves a Web page, the client opens a separate connection to
the Web server and the server automatically does not keep any
record of previous client request.
 Session is required to keep track of users and their information.

1. Request (New)
2. Response
Client Server
3.Second Request (New)

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 112 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management
Example: Application of Session

When a User logs into your website, no matter on which web page
he visits after logging in, his credentials will be with the server, until
user logs out.
So this is managed by creating a session.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 113 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management
 Session Management is a mechanism used by the Web
container to store session information for a particular user. 
 There are four different techniques for session management. 
Session Management
Hidden form field

URL Rewriting

Cookies

HttpSession

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 114 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
 Hidden Form Field, a hidden (invisible) textfield is used for
maintaining the state of an user.
 In such case, we store the information in the hidden field and get
it from another servlet.
Example
<input type="hidden"
name="session_id"
value="054">

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 115 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
login.html Valid.java

request.getParameter(“name”);
Name:
request.getParameter(“password”);
Password:
request.getParameter(“session”);
`
Session_ID: 054
Submit Hidden Field

Welcome.java

request.getParameter(“session”);

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 116 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
login.html
1. <html>
2. <head>
3. <title>login</title>
4. </head>
5. <body>
6. <form action="/Session/Valid" method="POST">
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="text" name="pwd"></p>
9. <p><input type="hidden" name="session_id" value="054"></p>
10.<p><input type="submit" value="Sign In"></p>
11. </form>
12. </body>
13.</html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 117 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
1. public class Valid extends HttpServlet Valid.java

2. { public void doPost(HttpServletRequest request,


HttpServletResponse response)
3. throws ServletException,IOException
4. {
5. response.setContentType("text/html");
6. PrintWriter out=response.getWriter();
7. RequestDispatcher rd;
8. String login=request.getParameter("login");
9. String pwd=request.getParameter("pwd");
10. String session=request.getParameter("session_id");

Hidden
Field

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 118 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
Valid.java
11.if(login.equals("java") && pwd.equals("servlet"))
12.{
13. rd=request.getRequestDispatcher("Welcome");
14. rd.forward(request, response);
15.}//if
16.else
17.{
18. out.println("<p><h1>Incorrect LoginId/Password
</h1></p>");
19. rd=request.getRequestDispatcher("/login.html");
20. rd.include(request, response);
21. }//else
22.} }
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 119 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
import javax.servlet.*; Welcome.java
import javax.servlet.http.*;
import java.io.*;
public class Welcome extends HttpServlet
{ public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException
{ response.setContentType("text/html");
PrintWriter out=response.getWriter();
String session=request.getParameter("session_id");
String username=request.getParameter("login");
out.println("<h1>"+"id:"+session+"</h1>");
out.println("<h3>"+"Welcome "+username+"</h3>");
}
}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 120 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
Real application of hidden form field
 It is widely used in comment form of a website.

 In such case, we store page id or page name in the hidden field so


that each page can be uniquely identified.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 121 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
Advantage of Hidden Form Field
 Easy to implement

 It will always work whether cookie is disabled or not.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 122 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Hidden form field
Disadvantage of Hidden Form Field:
 It is maintained at server side.
 Extra form submission is required on each pages.
 Only textual information can be used.
 It does not support hyperlink submission.
 Security
• Hidden field will be visible with GET method
• User might view page source and can view hidden field

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 123 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
URL Rewriting

124
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 124 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: URL Rewriting
 In URL rewriting, a token or identifier is appended to the URL of the
next Servlet or the next resource.
 We can send parameter name/value pairs using the following format:
URL ? Name1 = value1 & name2 = value2 &…

A name and a value name/value pair is separated


is separated using from another parameter using
an equal (=) sign the ampersand(&)
 When the user clicks the hyperlink, the parameter name/value pairs
will be passed to the server.
 From a Servlet, we can use getParameter() method to obtain a
parameter value.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 125 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: URL Rewriting
1. import javax.servlet.*; Url1.java
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Url1 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { String url;
8. response.setContentType("text/html");
9. PrintWriter out=response.getWriter(); URL
10. //for URL rewriting Rewriting
11. url= "http://localhost:8080/Session
/Url2?s_id1=054&s_id2=055";
12. out.println("<a href="+url+">next page</a>");
13. } }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 126 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: URL Rewriting
1. import javax.servlet.*; Url2.java
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Url2 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { response.setContentType("text/html");
8. PrintWriter out=response.getWriter();
9. String session1=request.getParameter("s_id1");
10. String session2=request.getParameter("s_id2");
11. out.println("<h3>"+"id:"+session1+"</h3>");
12. out.println("<h3>"+"id:"+session2+"</h3>");
13. }
14.}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 127 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: URL Rewriting
Url1.java

Url2.java

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 128 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: URL Rewriting
Advantage of URL Rewriting
 It will always work whether cookie is disabled or not (browser
independent).
 Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


 It will work only with links.
 It can send only textual information.
 URL header size constraint.
 Security
• name/value field will be visible with URL followed by ‘?’.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 129 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Cookies

javax.servlet.http.Cookie

130
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 130 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
 A cookie is a small piece of information that is persisted between
the multiple client requests.
 A cookie has a
1. Name
2. Single value
3. Optional attributes such as
i. comment
ii. path
iii. domain qualifiers
iv. a maximum age
v. version number

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 131 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
By default, each
How Cookie works? request is considered
as a new request
1. Request

Server will add cookie with


response from the servlet

2. Response + Cookie

After that if request is sent by


Web Client the user, cookie is added with
request by default.
Thus, we recognize the user
Server
So cookie is as the old user.
stored in the
cache of the
3. Request + Cookie
browser.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 132 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Types of Cookie

Non-persistent cookie Persistent cookie

• It is valid for single • It is valid for multiple session .


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

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 133 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Cookie class
 javax.servlet.http.Cookie 
This class provides the functionality of using cookies.
It provides a lots of useful methods for cookies.
Constructor
Cookie(String name, String value) constructs a cookie with a specified
name and value.

Example
Cookie c= new Cookie("session_id","054");
//creating cookie object  

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 134 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Methods of Cookie class
void setMaxAge(int expiry) Sets the maximum age in seconds for this Cookie
int getMaxAge() Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie
will persist until browser shutdown.
String getName() Returns the name of the cookie. The name cannot be
changed after creation.
void setValue Assigns a new value to this Cookie.
(String newValue)
String getValue() Gets the current value of this Cookie.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 135 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Other Methods of HttpServletRequest & HttpServletResponse
void addCookie(Cookie cookie) Method of HttpServletResponse interface is used to
add cookie in response object.

Cookie[] getCookies() Returns an array containing all of the Cookie objects the


client sent with this request. This method returns null if
no cookies were sent.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 136 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
How to create Cookie?
Example

//creating cookie object
Cookie c= new Cookie("session_id","054");
//adding cookie in the response
response.addCookie(c);

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 137 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
How to retrieve Cookies?
Cookie c[]=request.getCookies();  
for(int i=0;i<c.length;i++)
{  
  out.print(c[i].getName()+””+
c[i].getValue());
//printing name&value of cookie  
}  

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 138 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
How to delete Cookie?
1. Read an already existing cookie and store it in Cookie
object.
2. Set cookie age as zero using setMaxAge() method to
delete an existing cookie
3. Add this cookie back into response header.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 139 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
How to delete Cookie?
//deleting value of cookie
Cookie c = new Cookie("user","");
//changing the maximum age to 0 seconds  
c.setMaxAge(0);

//adding cookie in the response  
response.addCookie(c);

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 140 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Cookie.html

Cookie1.java

Add Cookie

Cookie2.java
Cookie3.java
Retrieve Cookie
Retrieve All Cookies Add Another Cookie

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 141 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
<html> cookie.html

<head>
<title>cookie</title>
</head>
<body>
<form action="/Session/Cookie1" >
<p>Login ID:<input type="text" name="login"></p>
<p>Password:<input type="password" name="pwd"></p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 142 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
1. public class Cookie1 extends HttpServlet Cookie1.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. { response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. String login=request.getParameter("login");
7. String pwd=request.getParameter("pwd");
8. if(login.equals("java") && pwd.equals("servlet"))
9. { Cookie c = new Cookie("c1",login);//create cookie
10. response.addCookie(c);//adds cookie with response
11. out.println("Cookie named:"+c.getName()+" added");
12. String path="/Session/Cookie2";
13. out.println("<p><a href="+path+">next page</a></p>");
14. }
15. else { //Redirect page to cookie.html}
16. } }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 143 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Output: Cookie1.java [add Cookie]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 144 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
1. public class Cookie2 extends HttpServlet Cookie2.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException
3. { response.setContentType("text/html");
4. PrintWriter out=response.getWriter();
5. Cookie c[]=request.getCookies();
6. out.println("c.length="+c.length);
7. for(int i=0;i<c.length;i++)
8. { out.println("CookieName="+c[i].getName()+
9. "CookieValue="+c[i].getValue());}
10. //to add another cookie
11. Cookie c1 = new Cookie("c2","054");
12. response.addCookie(c1);
13. String path="/Session/Cookie3";
14. out.println("<a href="+path+">next page</a>");}}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 145 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Output: Cookie1.java [Retrive Cookie and add one more cookie]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 146 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
1. public class Cookie3 extends HttpServlet Cookie3.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. { response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. Cookie c[]=request.getCookies();
7. for(int i=0;i<c.length;i++)
8. { out.println("<p>");
9. out.println("CookieName="+c[i].getName()+
10. "CookieValue="+c[i].getValue());
11. out.println("</p>");
12. }
13. }
14. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 147 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Output: Cookie1.java [Retrive all the Cookies]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 148 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: Cookies
Advantage of Cookies
 Simplest technique of maintaining the state.

 Cookies are maintained at client side.

Disadvantage of Cookies
 It will not work if cookie is disabled from the browser.

 Only textual information can be set in Cookie object.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 149 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Interview Questions: Cookies
1. What Are Cookies?
2. Can I see/view the cookies I have on my computer?
3. What's in a Cookie? OR What does a Cookie contains?
4. Why are Cookies Used?
5. How Long Does a Cookie Last?
6. How Secure are Cookies?
7. What are Tracking Cookies?
8. What do the Cookies Do?

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 150 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
HttpSession

javax.servlet.http.HttpSession

151
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 151 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management: HttpSession
 Apart from the above mentioned three ways, servlet provides
HttpSession Interface which provides a way to identify a user
across more than one page request
 The container creates a session id for each user.
 The container uses this id to identify the particular user.
 An object of HttpSession can be used to perform two tasks:
1. Bind objects
2. View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 152 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Server

Web Container

Request
Client1 id=054 Session1
id= 054
Servlet
Session2
Request id= 055
Client2
id=055

Working of HttpSession

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 153 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management :HttpSession
 Package: javax.servlet.http.HttpSession
Interface
 The servlet container uses this interface to create a session
between an HTTP client and an HTTP server. 
 In this technique create a session object at server side for each
client.
 Session is available until the session time out, until the client log
out.
 The default session time is 30 minutes and can configure explicit
session time in web.xml file.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 154 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
The HttpServletRequest interface provides two methods to get the
object of HttpSession

HttpSession getSession() Returns the current session associated with this


request, or if the request does not have a session,
creates one.

HttpSession Returns the current HttpSession associated with this


getSession(boolean create) request or, if there is no current session and create is
true, returns a new session.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 155 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Methods of HttpSession interface
String getId() Returns a string containing the unique identifier value.
long getCreationTime() Returns the time when this session was created, measured in
milliseconds.
long getLastAccessedTime() Returns the last time the client sent a request associated with
this session, as the number of milliseconds.
void invalidate() Invalidates this session then unbinds any objects bound to it.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 156 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
How to create the session?
HttpSession hs=request.getSession();
hs.setAttribute("s_id", "diet054");

How to retrieve a session?


HttpSession hs=request.getSession(false);
String n=(String)hs.getAttribute("s_id");

How to invalidate a session?


hs.invalidate();

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 157 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession

Httpsession.html HSession1.java
[Login page] [Create Session]

HSession2.java
[Retrieve Session]

HSession3.java
HSession4.java
[Retrieve Session]
[Logout]
[Invalidate Session]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 158 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Httpsession.html
<html>
<head>
<title>HttpSession</title>
</head>
<body>
<form action="/Session/HSession1" method="Get">
<p>Login ID:<input type="text" name="login"></p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>
Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 159 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
1. response.setContentType("text/html"); HSession1.java
2. PrintWriter out=response.getWriter();
3. RequestDispatcher rd;
4. String login=request.getParameter("login");
5. if(login.equals("java") )
6. { HttpSession hs=request.getSession();
7. hs.setAttribute("s_id",login);//set HttpSession
8. out.println("Session Created");
9. out.print("<a href='HSession2'>Homepage</a>");
10. }
11. else
12. { out.println("<p><h1>Incorrect Login Id/Password
</h1></p>");
13. rd=request.getRequestDispatcher("/httpsession.html");
14. rd.include(request, response);}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 160 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Output: HttpSession1.java

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 161 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
1. public class HSession2 extends HttpServlet HSession2.java

2. { public void doGet(HttpServletRequest request,


HttpServletResponse response)
3. throws ServletException,IOException
4. {response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. HttpSession hs=request.getSession(false);
7. String n=(String)hs.getAttribute("s_id");
8. out.print("Hello "+n);
9. out.print("<p><a hef='HSession3'>visit</a></p>");

10.} }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 162 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Output: HttpSession2.java

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 163 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
1. public class HSession3 extends HttpServlet HSession3.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. {response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. HttpSession hs=request.getSession(false);
7. String n=(String)hs.getAttribute("s_id");
8. out.print("Hello again "+n);
9. out.println("<form action='/Session/HSession4'>");
10. out.println("<p><input type='submit'
11. value='End Session'></p></form>");
12. hs.invalidate();//Session Invalidated
13. }
14.}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 164 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Output: HttpSession3.java

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 165 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
1. public void doGet(HttpServletRequest request, HSession4.java
HttpServletResponse response)
2. throws ServletException,IOExceptio
{ response.setContentType("text/html");
3. PrintWriter out=response.getWriter();
4. HttpSession hs=request.getSession(false);
5. try
6. { String n=(String)hs.getAttribute("s_id");
7. } catch(NullPointerException ne)
8. {out.println("Session Invalidated");}
9. out.println("<form action='/Session/httpsession.html'>");
10. out.println("<p><input type='submit'
value='logout'></p></form>");
11.}//doGet

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 166 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Management : HttpSession
Output: HttpSession4.java

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 167 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Timeout

168
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 168 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Timeout
The session timeout in a web application can be configured in two
ways
1. Timeout in the deployment descriptor (web.xml)
2. Timeout with setMaxInactiveInterval()

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 169 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Timeout
1. Timeout in the deployment descriptor (web.xml)
<web-app>
<session-config>
<session-timeout> 10 </session-timeout>
</session-config> Here specified
time is in
</web-app> minutes

 Note that the value of the timeout is set in minutes, not in


seconds.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 170 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Session Timeout
2. Timeout with setMaxInactiveInterval()
The timeout of the current session only can be specified
programmatically via the API of
the javax.servlet.http.HttpSession

HttpSession session = request.getSession();


session.setMaxInactiveInterval(10*60);
Here specified
time is in
seconds

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 171 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter API

172
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 172 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter API
Web Container

Filter

request Filter request


Servlet Program
Filter response response

WebClient

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 173 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter
  Filter is used for pre-processing of requests and post-processing
of responses.
 Filters are configured in the deployment descriptor of a web
application.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 174 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter
Usage of Filter
 Recording all incoming requests
 Logs the IP addresses of the computers from which the requests
originate
 Conversion
 Data compression
 Encryption and Decryption
 Input validation etc.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 175 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 176 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter API
The javax.servlet package contains the three interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 177 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Interface
 For creating any filter, you must implement the Filter interface.
 Filter interface provides the life cycle methods for a filter.
Method
void init(FilterConfig config) init() method is invoked only once. It is used to initialize
the filter.
void doFilter doFilter() method is invoked every time when user
(HttpServletRequest request, request to any resource, to which the filter is
HttpServletResponse response, mapped.It is used to perform filtering tasks.
FilterChain chain)

void destroy() This is invoked only once when filter is taken out of the
service.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 178 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Interface
Example
public void init(FilterConfig config) 
throws ServletException {…}  
      
public void doFilter(ServletRequest req, 
ServletResponse resp,  
     FilterChain chain) 
throws IOException,ServletException 
{//filter logic…} 
 
public void destroy() {…} 
 

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 179 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
FilterChain interface
 The object of FilterChain is responsible to invoke the next filter or
resource in the chain.
 This object is passed in the doFilter method of Filter interface.
 The FilterChain interface contains only one method:
void doFilter It passes the control to the next filter or
(HttpServletRequest request, resource.
HttpServletResponse response)

Example
FilterChain chain;
chain.doFilter(req, resp);//send request to next resource 

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 180 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Config
 FilterConfig is created by the web container.
 This object can be used to get the configuration information from
the web.xml file.
Method
void init(FilterConfig config) init() method is invoked only once it is used to initialize
the filter.
String getInitParameter Returns the parameter value for the specified parameter
(String parameterName) name.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 181 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example
Web Container

Filter1.java

FilteredServlet.java

request Filter request


Servlet Program
Filter response response

WebClient

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 182 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example: index.html
1. <html>
2. <head>
3. <title>Filter</title>
4. </head>
5. <body>
6. <a href="FilteredServlet">click here</a>
7. </body>
8. </html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 183 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example1
1. <web-app> web.xml

2. <servlet>
3. <servlet-name>FilteredServlet</servlet-name>
4. <servlet-class>FilteredServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>FilteredServlet</servlet-name>
8. <url-pattern>/FilteredServlet</url-pattern>
9. </servlet-mapping>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 184 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example1
10.<filter> web.xml

11. <filter-name>f1</filter-name>
12. <filter-class>Filter1</filter-class>
13.</filter>
14.<filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/FilteredServlet</url-pattern>
17.</filter-mapping>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 185 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example1: Filter1.java
1. public class Filter1 implements Filter
2. {public void init(FilterConfig arg0) throws
ServletException {//overridden init() method}
3. public void doFilter(ServletRequest req,
4. ServletResponse resp,FilterChain chain)
throws IOException,
ServletException
5. { PrintWriter out=resp.getWriter();
6. out.print("filter is invoked before");//exe. with request
7. chain.doFilter(req, resp);//send request to nextresource
8. out.print("filter is invoked after");//exe. with response
9. }
10. public void destroy() {//overridden destroy() method}
11. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 186 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example1: FilteredServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class FilteredServlet extends HttpServlet
6. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
7. throws ServletException, IOException
8. {
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11. out.println("<br>welcome to servlet<br>");
12. }
13.}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 187 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example1: Output

Filter1.java [executed with request]


FilteredServlet.java [Servlet code]
Filter1.java [executed with response]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 188 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
Web Container

Filter1.java Filter2.java

FilteredServlet.java

Servlet Program

WebClient

Authenticate User Check config parameter

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 189 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
1. <html> index.html

2. <head>
3. <title>filter</title>
4. </head>
5. <body>
6. <form action="/Filter/FilteredServlet" >
7. <p>Login ID:<input type="text" name="login"></p>
8. <p>Password:<input type="password" name="pwd"></p>
9. <p><input type="submit" value="Sign In"></p>
10. </form>
11. </body>
12.</html>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 190 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
1. <web-app> web.xml

2. <servlet>
3. <servlet-name>FilteredServlet</servlet-name>
4. <servlet-class>FilteredServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>FilteredServlet</servlet-name>
8. <url-pattern>/FilteredServlet</url-pattern>
9. </servlet-mapping>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 191 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
10.<filter> web.xml

11. <filter-name>f1</filter-name>
12. <filter-class>Filter1</filter-class>
13.</filter>
14.<filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/FilteredServlet</url-pattern>
17.</filter-mapping>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 192 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
18.<filter> web.xml

19. <filter-name>f2</filter-name>
20. <filter-class>Filter2</filter-class>
21. <init-param>
22. <param-name>permit</param-name>
23. <param-value>yes</param-value>
24. </init-param>
25. </filter>
26. <filter-mapping>
27. <filter-name>f2</filter-name>
28. <url-pattern>/FilteredServlet</url-pattern>
29. </filter-mapping>
30.</web-app>

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 193 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
1. public class Filter1 implements Filter{ Filter1.java
2. public void init(FilterConfig config) {}
3. public void doFilter(ServletRequest req,
4. ServletResponse resp, FilterChain chain)
5. throws IOException, ServletException
6. { PrintWriter out=resp.getWriter();
7. out.print("<p>filter1 is invoked before</p>");
8. if(req.getParameter("login").equals("java") &&
9. req.getParameter("pwd").equals("servlet"))
10. { chain.doFilter(req, resp);//send request to next resource
11. }//if
12. else
13. {out.print("<p>invalid login/password</p>");}//else
14.
15. out.print("<p>filter1 is invoked after</p>");
16.}
17.public void destroy() {}}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 194 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
1. public class Filter2 implements Filter{ Filter2.java
2. String permission;
3. public void init(FilterConfig config) throws ServletException
4. { permission=config.getInitParameter("permit"); }
5. public void doFilter(ServletRequest req, ServletResponse resp,
6. FilterChain chain) throws IOException, ServletException
7. { PrintWriter out=resp.getWriter();
8. out.print("<p>filter2 is invoked before</p>");

9. if(permission.equals("yes"))
10. { chain.doFilter(req, resp);}//if
11. else
12. { out.println("Permission Denied"); }//else

13. out.print("<p>filter2 is invoked after</p>"); }


14. public void destroy() {}}

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 195 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2
FilteredServlet.java
1. public class FilteredServlet extends HttpServlet {
2. public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException, IOException
4. {
5. response.setContentType("text/html");
6. PrintWriter out = response.getWriter();
7. out.println("<p><h3>welcome to servlet</h3></p>");
8. }
9. }

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 196 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter Example2:output

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 197 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Filter
Advantage of Filter
 Filter is pluggable.
 One filter don't have dependency onto another resource.
 Less Maintenance Cost
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
So maintenance cost will be less.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 198 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet with JDBC

202
Unit-3
Unit-3 Servelt
Servelt API
API and
and Overview
Overview 202 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet with JDBC
1. import java.io.*;
2. import java.sql.*;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class JDBCServlet extends HttpServlet
6. {
7. public void doGet(HttpServletRequest request,
HttpServletResponse response)
8. throws ServletException,IOException
9. { response.setContentType("text/html");
10. PrintWriter out=response.getWriter();
//Program continued in next slide…
...

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 203 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet with JDBC
11. try{
12. Class.forName("com.mysql.jdbc.Driver");
13. Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ajava","root","");
14. Statement st=con.createStatement();
15. ResultSet rs=st.executeQuery("select * from cxcy");
16. while(rs.next())
17. { out.println("<p>"+rs.getInt(1));
18. out.println(rs.getString(2));
19. out.println(rs.getString(3)+"</p>");
20. }
21. }catch(Exception e)
22. {out.println("<p>inside exception"+e.toString()+"</p>");}
23. }//doGet()
24. }//Class

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 204 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
GTU Servlet Programs
1. Write a Java Servlet to demonstrate the use of Session Management. [Win’18]
[Sum’18]
[Win’16]
[Win’15]

2. Write small web application which takes marks of three subject and pass [Sum’16]
to servlet. Servlet forward to model class having method getClass() and
getPercentage(). Display class and percentage
3. Write servlet which displayed following information of client. [Sum’16]
I. Client Browser II. Client IP address III. Client Port No IV. Server Port No.
V. Local Port No VI. Method used by client for form submission
VII. Query String name and values

4. Write a Java Servlet to print BE Semester 7 Marksheet of entered [Sum’18]


enrollment number by user using JDBC. [Sum’15]
5. Write a servlet which accept two numbers using POST methods and [Win’14]
display the maximum of them.
6. Write a web application using servlet to compute an area of a circle. Get [Win’13]
the radius from the client. Write necessary web.xml file.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 207 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
GTU Servlet Theory Questions
1. Explain Servlet Life Cycle with example to demonstrate every state. [Sum’17]
Explain role of web container. Explain importance of context object. [Sum’16]
[Win’15]
[Sum’15]

2. What is filter? What is its use? List different filter interfaces with their [Win’18]
important methods. Explain the configuration of filter using deployment [Sum’18]
descriptor. [Win’16]
[Sum’15]

3. What is Request Dispatcher? What is the difference between Request [Win’16]


dispatcher’s forward() and include() method?
4. Explain difference between ServletConfig and ServletContext object. [Sum’18]
[Sum’17]

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 208 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Interview Questions
1. Who is responsible to create the object of servlet?
2. What is difference between Get and Post method?
3. When servlet object is created?
4. What is difference between PrintWriter and ServletOutputStream?
5. What is difference between GenericServlet and HttpServlet?
6.  Can you call a jsp from the servlet?
7. Difference between forward() method and sendRedirect() method ?
8. What is difference between ServletConfig and ServletContext?
9.  What happens if you add a main method to servlet?
10. What is MIME Type?
11. Why main() is not written in servlets programs?
12. How does the JVM execute a servlet compared with a regular Java class?
13. Consider a scenario in which 4 users are accessing a servlet instance. Among which
one user called destroy() method. What happens to the rest 3 users?
14. What is Connection Pooling?

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 209 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Servlet Interview Questions
15. Servlet is Java class. Then why there is no constructor in Servlet? Can we write the
constructor in Servlet? Justify your answer.

Unit-3
Unit-3 Servlet
Servlet API
API and
and Overview
Overview 210 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology

Potrebbero piacerti anche