0% found this document useful (0 votes)
68 views124 pages

Servlet API Overview and Lifecycle

This document provides an overview of servlets and the servlet API. It discusses what servlets are, how they differ from CGI, the servlet life cycle, and key servlet packages and interfaces. Servlets are Java classes that extend the functionality of web servers by dynamically generating web pages. They allow for more efficient request processing compared to CGI and enable session tracking and sharing of data between requests. The servlet API defines interfaces and classes for implementing servlets, including the Servlet interface, GenericServlet, and HttpServlet classes.

Uploaded by

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

Servlet API Overview and Lifecycle

This document provides an overview of servlets and the servlet API. It discusses what servlets are, how they differ from CGI, the servlet life cycle, and key servlet packages and interfaces. Servlets are Java classes that extend the functionality of web servers by dynamically generating web pages. They allow for more efficient request processing compared to CGI and enable session tracking and sharing of data between requests. The servlet API defines interfaces and classes for implementing servlets, including the Servlet interface, GenericServlet, and HttpServlet classes.

Uploaded by

godhanipriyank8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Advanced java Programming

GTU #3160707

Unit-3
Servlet API and
Overview

Prof. Jayesh D. Vagadiya


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9537133260
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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 2


What is Servlet?
 Servlet is java class which extends the functionality of web server by dynamically
generating web pages.
 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 request, process the request and
sends back the response. Server
Client Http Response

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 3


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-side programming language, but there were many disadvantages of this technology.

Changes with respect to time

1. To retrive server’s current


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 4


Why we need Servlet?
 Nowadays everything is available on Internet.
 Starting from e-banking, e-commerce everything is available through internet. We call all
these applications as Web applications.
Hey Server, I want to display given
name in my web page Sorry, I can’t do
that Dynamic
computation

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

Clien Server
Dynamic Response
t
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 5
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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 6


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 7


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/

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 8


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 9


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
Contains interface and abstract class for
Class

HttpServlet servlet that understands HTTP protocol.


extended by Package: javax.servlet.http

MyServlet User defined Servlet class.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 10


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 11


Servlet Life Cycle: init()
 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.
 Servlet instance is created
 The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.
 Init() method is invoked
 The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet.
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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 12


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.
Syntax
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{

}
 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 13


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
 database connections,
 halt background threads,
 write cookie lists or hit counts to disk, and
 perform other such cleanup activities.
 After the destroy() method is called, the servlet object is marked for garbage collection.
Syntax
public void destroy()
{
// Finalization code...
}

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 14


Servlet Life Cycle

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 15


doGet() v/s doPost()
 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 …
}

 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 doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code …
}

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 16


doGet() vs doPost()
doGet() doPost()
In this method, parameters are appended to the URL In doPost(), parameters are sent in separate line in
and sent along with header information the body
Maximum size of data that can be sent using doGet() There is no maximum size for data
is 240 bytes
Parameters are not encrypted Parameters are encrypted here
Application: Application:
Used when small amount of insensitive data like a Used when comparatively large amount of sensitive
query has to be sent as a request. data has to be sent.
It is default method. E.g. submitting sign_in or login form.
doGet() is faster comparatively doPost() is slower compared to doGet() since
doPost() does not write the content length

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 17


Servlet Life Cycle: Servlet Code
MyServlet.Java
1 import java.io.*;
2 import javax.servlet.*;
3
4 public class MyServlet1 extends GenericServlet
5 {
6 public void init() throws ServletException
7 {//Initailization Code
8 }
9
10 public void service(ServletRequest request,ServletResponse response) throws
11 ServletException,IOException
12 {//Servlet code
13 }
14
15 public void destroy()
16 {//Finalization Code
17 }
18 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 18


Steps to run Servlet Program in Netbeans
 Step 1: Open Netbeans IDE, Select File -> New Project

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 19


Steps for Servlet Program
Step 2: Select Java Web -> Web Application, then click on Next

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 20


Steps for Servlet Program
 Step 3: Give a name to your project and click on Next,

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 21


Steps for Servlet Program
 Step 4: and then, Click Finish

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 22


Steps for Servlet Program
 Step 5: The complete directory structure required for the Servlet Application will be created
automatically by the IDE.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 23


Steps for Servlet Program
 Step 6: To create a Servlet, open Source Package, right click on default packages -> New -
> Servlet.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 24


Steps for Servlet Program
 Step 7: Give a Name to your Servlet class file

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 25


Steps for Servlet Program

It will add servlet


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 26


Step 8: Write servlet code: MyServlet.java
MyServet1.java
1 import java.io.*;
2
import javax.servlet.*;
3
4 import javax.servlet.http.*;
5 public class MyServlet1 extends HttpServlet
6 { String msg="";
7
8 PrintWriter out;
9 public void init() throws ServletException
10 { msg="hello world: my first servlet program"; }
11
12 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
13 {
14 response.setContentType("text/html");
15
out=response.getWriter();
16
17 out.println(msg);
18 }
19
public void destroy()
20
21 { out.close();
22 }
23 }
24

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 27


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.
 text/html
 text/plain
 text/css
 text/richtext
 application/msword
 application/jar
 application/pdf
 images/jpeg images/png images/gif
 audio/mp3
 video/mp4
 MIME is a standard set to Internet to notify the format of the file contents.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 28


Steps for Servlet Program
 Step 9: open web.xml

It is used to
Configuration
map Servlet toof servlet
using <servlet>
specific URL Map the servlet to a URL. This can be done
using <servlet-mapping> element.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 29


Steps for Servlet Program
 Step 11: Run your application, right click on your Project and select Run

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 30


Java Servlet

1
2

5
3

Ref: https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 31
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, parameter names
ServletRespons and values, header informations,
e attributes
It contains various methods that enable
a servlet to respond to the client
requests. A servlet can send the
response either as character or binary
data.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 32


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)

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 33


GenericServlet vs HttpServlet
GenericServlet HttpServlet
javax.servlet.GenericServlet javax.servlet.http.HttpServlet
It defines a generic, protocol-independent It defines a HTTP protocol specific servlet.
servlet.
GenericServlet is a super class of HttpServlet HttpServlet is a sub class of GenericServlet
class. class.
Can handle all types of protocols only HTTP specific protocols.
It supports only one abstract It support doGet(), doPost() etc.
method:service()

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 34


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.
 <servlet-name>: name used to access java servlet
 <servlet-class>: class name of java servlet
 <init-param>: for initialization parameter

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 35


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"> Document Type Definition


<web-app>

<servlet> Configures a web application.


<servlet-name>MyServlet</servlet-name>
Name used to access
<servlet-class>MyServlet</servlet-class>
Java Servlet
<init-param>

<param-name>name</param-name> Name of servlet .java


<param-value>cxcy</param-value> class
</init-param>

</servlet>
Used to pass parameters to a servlet from the web.xml file.
<servlet-mapping>
map the servlet to a
<servlet-name>MyServlet</servlet-name> URL or URL pattern
<url-pattern>/MyServlet</url-pattern>

</servlet-mapping> Controls behavior of


</web-app>
Servlet

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 36


Program to call servlet from html file
 Write a java Servlet program to call servlet from html hyperlink.
2.html
1 <html>
2 <head>
3 <title> HyperLinkDemo </title>
4 </head>
5 <body>
6 <a href ="/ServletDemo2/HyperLinkDemo">HyperLinkDemo.java </a>
7 </body>
8 </html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 37


Servlet Program: HyperLinkDemo.java
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
11 response) throws ServletException,IOException
12 { response.setContentType("text/html");
13 out=response.getWriter();
14 out.println("<h1>"+msg+"</h1>");
15 }
16 public void destroy()
17 { out.close();
18 }
19 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 38


doGet()
1.html
1 <html>
2 <head>
3 <title> DoGetDemo </title>
4 </head>
5 <body>
6 <form action="/ServletDemo2/DoGetDemo">
7 Enter Email:<input type="text" name="email">
8 <p><input type="submit"></p>
9 </form>
10 </body>
11 </html>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 39


doGet()
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 }
9 public void doGet(HttpServletRequest request,HttpServletResponse response)throws
10 ServletException,IOException
11 {
12 String email=request.getParameter("email");
13 response.setContentType("text/html");
14 out =response.getWriter();
15 out.println("my email:"+email); String getParameter(String
16 } name)
17 public void destroy() Returns the value of a request
18 { out.close(); parameter as a String
19 }
20 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 40


doPost()
 Write a Servlet program to enter two numbers and find maximum among them.
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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 41


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

Using
doPost()
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 42
ServletConfig Interface
 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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 43


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>
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 44
Servlet Config: MyServlet.java
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 {
9 msg = config.getInitParameter("name");
10 } <param-value>
11 public void doGet(HttpServletRequest request , HttpServletResponse response) throws
12 ServletException,IOException
13 { response.setContentType("text/html");
14 out = response.getWriter();
15 out.println("<h1>"+ msg +"</h1>");
16 }
17 public void destroy()
18 { out.close();
19 }
20 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 45


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.
<web-app>
...
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
...
<servlet> used to define
... initialization parameter
</servlet>
in the application scope.

</web-app>
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 46
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>
Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 47
ServletContextDemo.java
ServletContextDemo.jav
a
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class ServletContextDemo extends HttpServlet
5 {
6 public void doGet(HttpServletRequest req,HttpServletResponse res) throws
7 ServletException,IOException
8 { res.setContentType("text/html");
9 PrintWriter out=res.getWriter();
10 //creating ServletContext object
11 ServletContext context=getServletContext();
12 //Getting the value of the initialization parameter and printing it
13 String college=context.getInitParameter("name");
14 out.println("College name is="+college);
15 out.close();
16 }
17 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 48


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 during Object of ServletContext will be created at the time
initialization process of the servlet of web application deployment
Scope: As long as a servlet is executing, Scope: As long as web application is executing,
ServletConfig object will be available, it will be ServletContext object will be available, and it will be
destroyed once the servlet execution is completed. destroyed once the application is removed from the
server.
We should give request explicitly, in order to create ServletContext object will be available even before
ServletConfig object for the first time giving the first request
In web.xml – <init-param> tag will be appear under In web.xml – <context-param> tag will be appear
<servlet-class> tag under <web-app> tag

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 49


HttpServletRequest: Methods
String getContextPath() Returns the portion of the request URI that indicates the context of the request.
Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains.
String getHeader(String name) Returns the value of the specified request header as a String.
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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 50


HttpServletRequest: Methods
String getContextPath() Returns the portion of the request URI that indicates the context of the request.

getContextPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getContextPath():" +request.getContextPath()+"</p>");
4 }

Output
request.getContextPath():/ServletTemp

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 51


HttpServletRequest: Methods
Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains.

getHeaderNames
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 Enumeration h=request.getHeaderNames();
4 while(h.hasMoreElements())
5 {
6 String paramName = (String)h.nextElement();
7 out.print("<p>" + paramName + "\t");
8 String paramValue = request.getHeader(paramName);
9 out.println( paramValue + "</p>\n");
10 }
11 }

Output
host localhost:8080
user-agent Mozilla/5.0 (Windows NT 6.2; WOW64;rv:50.0) Gecko/20100101 Firefox/50.0
accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language en-US,en;q=0.5
accept-encoding gzip, deflate
connection keep-alive
upgrade-insecure-requests 1

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 52


HttpServletRequest: Methods
String getHeader(String name) Returns the value of the specified request header as a String.

getHeader
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 out.println("<p>request.getHeader(): " +request.getHeader("host")+"</p>");
4 out.println("<p>request.getHeader(): " +request.getHeader("referer")+"</p>");
5 }

Output
request.getHeader():host=localhost:8080
request.getHeader():referer=http://localhost:8080/ServletTemp/servletmeth.html

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 53


HttpServletRequest: Methods
String getQueryString() Returns the query string that is contained in the request URL after the path.

getQueryString
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 out.println("<p>request.getQueryString():" +request.getQueryString()+"</p>");
4
5 }

Output
requrest.getQueryString(): no1=1&no2=2

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 54


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

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

Output
request.getServletPath(): /ServletMeth

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 55


HttpServletRequest: Methods
String getMethod() Returns the name of the HTTP method with which this request was made, for example
GET or POST

getServletPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getMethod():"+request.getMethod()+"</p>");
4 }

Output
request.getMethod(): GET

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 56


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.

void forward(ServletRequest request, Forwards a request from a servlet to another resource


ServletResponse response) (servlet, JSP file, or HTML file) on the server.
throws ServletException, IOException

void include(ServletRequest request, Includes the content of a resource (Servlet, JSP page,
ServletResponse response) or HTML file) in the response.
throws ServletException, IOException

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 57


RequestDispatcher: forward()
Step2:
Servlet forward(req, res)
ues
t Servlet 2
:R
eq 1
p1
Ste

Step 3:
Response Response is
generated

Web Client
Step 4: R
e sponse i
s sent ba
ck to brows Response
er

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 58


RequestDispatcher: include()
Step2: include(req, res)
Servlet
e st Servlet 2
:R
eq u 1
p1 Step3:
Ste
Response of Servlet 2
is included in the
Response of Servlet 1 Response

Web Client

Fina
l
sent Response Response
b
fro n a c k t o t h e i s
Serv
l e t 1 c l i e nt

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 59


How to get the object of RequestDispatcher?
The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher.

Syntax
1 RequestDispatcher getRequestDispatcher(String resource)

Name of Servlet specified in <url-pattern>


Example
1 RequestDispatcher rd=request.getRequestDispatcher("servlet2");

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 60


RequestDispatcher: forward() and include()
Forward()
1 RequestDispatcher rd = request.getRequestDispatcher("servlet2");
2 rd.forward(request, response);

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

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 61


RequestDispatcher: Servlet Program

Validate Servlet
[CallServlet.java]

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 62


RequestDispatcher: 1.html
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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 63


RequestDispatcher: Validate Servlet
callServlet.java
1 public class CallServlet extends HttpServlet
2 {
3 public void doPost(HttpServletRequest request, HttpServletResponse response)
4 throws ServletException,IOException
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 if(login.equals("java") && pwd.equals("servlet"))
11 { rd=request.getRequestDispatcher("FwdDemo");
12 rd.forward(request, response);}//if
13 else
14 { out.println("<p><h1>Incorrect Login Id/Password </h1></p>");
15 rd=request.getRequestDispatcher("/1.html");
16 rd.include(request, response);
17 }
18 }
19 //dopost
20 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 64


RequestDispatcher: fwdDemo.java
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 }
13

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 65


RequestDispatcher: web.xml
web.xml
1 <web-app>
2 <servlet>
3 <servlet-name>FwdDemo</servlet-name>
4 <servlet-class>FwdDemo</servlet-class>
5 </servlet>
6 <servlet>
7 <servlet-name>CallServlet</servlet-name>
8 <servlet-class>CallServlet</servlet-class>
9 </servlet>
10
11 <servlet-mapping>
12 <servlet-name>FwdDemo</servlet-name>
13 <url-pattern>/FwdDemo</url-pattern>
14 </servlet-mapping>
15 <servlet-mapping>
16 <servlet-name>CallServlet</servlet-name>
17 <url-pattern>/CallServlet</url-pattern>
18 </servlet-mapping>
19 </web-app>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 66


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
1 void sendRedirect(String location) throws IOException

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 67


sendRedirect(): Example
Example
1 public class Redirect extends HttpServlet
2 {
3 public void doGet( HttpServletRequest request, HttpServletResponse response)
4 throws ServletException,IOException
5 { response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 String login=request.getParameter("login");
8 String pwd=request.getParameter("pwd");
9 if(login.equals("java") && pwd.equals("servlet"))
10 {
11 response.sendRedirect("/Dispatcher/Welcome");
12 }
13 else
14 {
15 response.sendRedirect("/Dispatcher/redirect.html");
16 }
17 } //doGet
18 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 68


forward() vs sendRedirect()
forward() sendRedirect()
The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response objects to It always sends a new request.
another servlet.
It can work within the server only. It can be used within and outside the server.
original URL not change. Here browser knows that it's making a new request,
so original URL changes.
Example: request.getRequestD Example:
ispacher("servlet2").forward(request,response); response.sendRedirect("servlet2");

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 69


Session Management in Servlets
 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.
 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)

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 70


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 71


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
1 <input type="hidden" name="session_id" value="054">

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 72


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”);

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 73


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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 74


Session Management: Hidden form field
Valid.java
1 public class Valid extends HttpServlet
2 { public void doPost(HttpServletRequest request, HttpServletResponse
3 response) throws ServletException,IOException
4 {
5 response.setContentType("text/html");
6 PrintWriter out=response.getWriter(); Hidden
7 RequestDispatcher rd;
8 String login=request.getParameter("login");
Field
9 String pwd=request.getParameter("pwd");
10 String session=request.getParameter("session_id");
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 }
23 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 75


Session Management: Hidden form field
Welcome.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class Welcome 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 session=request.getParameter("session_id");
10 String username=request.getParameter("login");
11 out.println("<h1>"+"id:"+session+"</h1>");
12 out.println("<h3>"+"Welcome "+username+"</h3>");
13 }
14 }
15

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 76


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.

 Advantage of Hidden Form Field


 Easy to implement
 It will always work whether cookie is disabled or not.

 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
Prof. Jayesh D. Vagadiya
view hidden field
# 3160707  Unit 3 – Servlet API and Overview 77
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 is


name/value pair is separated from another
separated using an
parameter using the ampersand(&)
equal (=) sign

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 78


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 79


Session Management: URL Rewriting
Url2.java
1 import javax.servlet.*;
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 }
15

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 80


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 ‘?’.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 81


Session Management: Cookies
 A cookie is a small piece of information that is persisted between the multiple client requests.
 A cookie has a
 Name
 Single value
 Optional attributes such as
 comment
 path
 domain qualifiers
 a maximum age
 version number

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 82


Session Management: Cookies
By default, each
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 +
browser.
Cookie

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 83


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 84


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
1 Cookie c= new Cookie("session_id","054");

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 85


Session Management: Cookies : Methods
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(String newValue) Assigns a new value to this Cookie.
String getValue() Gets the current value of this Cookie.

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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 86


Session Management: Cookies
 How to create Cookie?
Example
1 //creating cookie object
2 Cookie c= new Cookie("session_id","054");
3 //adding cookie in the response
4 response.addCookie(c);

 How to retrieve Cookies?


Example
1 Cookie c[]=request.getCookies();
2 for(int i=0;i<c.length;i++)
3 {
4 out.print(c[i].getName()+””+c[i].getValue());
5 //printing name&value of cookie
6 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 87


Session Management: Cookies
 How to delete Cookie?
 Read an already existing cookie and store it in Cookie object.
 Set cookie age as zero using setMaxAge() method to delete an existing cookie
 Add this cookie back into response header.

Example
1 //deleting value of cookie
2 Cookie c = new Cookie("user","");
3 //changing the maximum age to 0 seconds
4 c.setMaxAge(0);
5 //adding cookie in the response
6 response.addCookie(c);

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 88


Session Management: Cookies
Cookie.html

Cookie1.java

Add Cookie

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 89


Session Management: Cookies
cookie.html
1 <html>
2 <head>
3 <title>cookie</title>
4 </head>
5 <body>
6 <form action="/Session/Cookie1" >
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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 90


Session Management: Cookies
cookie1.java
1 public class Cookie1 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 {
10 Cookie c = new Cookie("c1",login);//create cookie
11 response.addCookie(c);//adds cookie with response
12 out.println("Cookie named:"+c.getName()+" added");
13 String path="/Session/Cookie2";
14 out.println("<p><a href="+path+">next page</a></p>");
15 }
16 else { //Redirect page to cookie.html}
17 } }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 91


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 92


Session Management: Cookies
cookie3.java
1 public class Cookie3 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 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 }
15

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 93


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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 94


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:
 Bind objects
 View and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 95


Session Management : HttpSession

Server

Web Container

Request
Client1 id=054 Session1
id= 054
Servle
t
Session2
Request id= 055
Client2
id=055

Working of HttpSession

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 96


Session Management :HttpSession
 Package: javax.servlet.http.HttpSession
 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.
 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 request or, if there is no
getSession(boolean create) current session and create is true then it will returns a new session.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 97


Session Management : HttpSession
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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 98


Session Management : HttpSession
How to create the session?
1 HttpSession hs=request.getSession();
2 hs.setAttribute("s_id", "diet054");

How to retrieve a session?


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

How to invalidate a session?


1 hs.invalidate();

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 99


Session Management : HttpSession

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

HSession2.java
[Retrieve Session]

HSession4.java
[Logout]

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 100
Session Management : HttpSession
Httpsession.html
1 <html>
2 <head>
3 <title>HttpSession</title>
4 </head>
5 <body>
6 <form action="/Session/HSession1" method="Get">
7 <p>Login ID:<input type="text" name="login"></p>
8 <p><input type="submit" value="Sign In"></p>
9 </form>
10 </body>
11 </html>
12

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 101
Session Management : HttpSession
HSession1.java
1 response.setContentType("text/html");
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
13 </h1></p>");
14 rd=request.getRequestDispatcher("/httpsession.html");
15 rd.include(request, response);
16 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 102
Session Management : HttpSession
HSession2.java
1 public class HSession2 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 HttpSession hs=request.getSession(false);
8 String n=(String)hs.getAttribute("s_id");
9 out.print("Hello "+n);
10 out.print("<p><a hef='HSession3’>Logout</a></p>");
11 }
12 }
13

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 103
Session Management : HttpSession
HSession3.java
1 public class HSession3 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 HttpSession hs=request.getSession(false);
8 hs.invalidate();// Session Invalidated
9 try
10 {
11 String n=(String)hs.getAttribute("s_id");
12 }
13 catch(Exception ne)
14 {
15 out.println("Session Invalidated");
16 }
17 out.println("<form action='/Session/httpsession.html'>");
18 out.println("<p><input type='submit’ value=‘Login'></p></form>");
19 }
20 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 104
Session Timeout
 The session timeout in a web application can be configured in two ways
 Timeout in the deployment descriptor (web.xml)
 Timeout with setMaxInactiveInterval()

Timeout in the deployment descriptor (web.xml)


1 <web-app>
2 <session-config>
3 <session-timeout> 10 </session-timeout>
4 </session-config>
5 </web-app> Here specified
time is in
minutes
Timeout with setMaxInactiveInterval()
1 HttpSession session = request.getSession();
2 session.setMaxInactiveInterval(10*60);

Here specified
time is in seconds

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 105
Filter API
Web Container

Filter

request Filter request


Servlet Program
Filter response response

WebClient

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 106
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.
 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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 107
Filter API
 The javax.servlet package contains the three interfaces of Filter API.
 Filter
 FilterChain
 FilterConfig

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 108
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 request to any
(HttpServletRequest request, resource, to which the filter is mapped.It is used to perform filtering
HttpServletResponse response, FilterChain tasks.
chain)
void destroy() This is invoked only once when filter is taken out of the service.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 109
Filter Interface
Methods
1 public void init(FilterConfig config) throws ServletException {…}
2
3 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
4
5 throws IOException,ServletException
6 {
7 //filter logic…
8 }
9
10 public void destroy() {…}

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 110
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 resource.
(HttpServletRequest request,
HttpServletResponse response)

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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 111
Filter Example
Web Container

Filter1.java

FilteredServlet.java

request Filter request


Servlet Program
Filter response response

WebClient

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 112
Filter Example: index.html
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>
9

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 113
Filter Example
Web.xml
1 <web-app>
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>
10
11 <filter>
12 <filter-name>f1</filter-name>
13 <filter-class>Filter1</filter-class>
14 </filter>
15 <filter-mapping>
16 <filter-name>f1</filter-name>
17 <url-pattern>/FilteredServlet</url-pattern>
18 </filter-mapping>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 114
Filter Example: Filter1.java
Filter1.java
1 public class Filter1 implements Filter
2 {
3 public void init(FilterConfig arg0) throws ServletException {//overridden init() method}
4
5 public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain)
6 throws IOException,
7 ServletException
8 {
9 PrintWriter out=resp.getWriter();
10 out.print("filter is invoked before");//exe. with request
11 chain.doFilter(req, resp);//send request to nextresource
12 out.print("filter is invoked after");//exe. with response
13 }
14 public void destroy() {//overridden destroy() method}
}

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 115
Filter Example: FilteredServlet.java
FilterServlet.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 {
7 public void doGet(HttpServletRequest request, HttpServletResponse response)
8 throws ServletException, IOException
9 {
10 response.setContentType("text/html");
11 PrintWriter out = response.getWriter();
12 out.println("<br>welcome to servlet<br>");
13 }
14 }

Filter1.java [executed with request]


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

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 116
Filter Example-2
Web Container

Filter1.java Filter2.java

FilteredServlet.java

Servlet Program

WebClient

Authenticate User Check config parameter

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 117
Filter Example-2
index.html
1 <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>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 118
Filter Example-2
Web.xml Web.xml
1 <web-app> 19 <filter>
2 <servlet> 20 <filter-name>f2</filter-name>
3 <servlet-name>FilteredServlet</servlet-name> 21 <filter-class>Filter2</filter-class>
4 <servlet-class>FilteredServlet</servlet-class> 22 <init-param>
5 </servlet> 23 <param-name>permit</param-name>
6 <servlet-mapping> 24 <param-value>yes</param-value>
7 <servlet-name>FilteredServlet</servlet-name> 25 </init-param>
8 <url-pattern>/FilteredServlet</url-pattern> 26 </filter>
9 </servlet-mapping> 27 <filter-mapping>
10 28 <filter-name>f2</filter-name>
11 <filter> 29 <url-pattern>/FilteredServlet</url-pattern>
12 <filter-name>f1</filter-name> 30 </filter-mapping>
13 <filter-class>Filter1</filter-class> 31 </web-app>
14 </filter>
15 <filter-mapping>
16 <filter-name>f1</filter-name>
17 <url-pattern>/FilteredServlet</url-pattern>
18 </filter-mapping>

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 119
Filter Example-2
Filter1.java
1 public class Filter1 implements Filter{
2
3 public void init(FilterConfig config) {}
4
5 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
6 throws IOException, ServletException
7 {
8 PrintWriter out=resp.getWriter();
9 out.print("<p>filter1 is invoked before</p>");
10 if(req.getParameter("login").equals("java") && req.getParameter("pwd").equals("servlet"))
11 {
12 chain.doFilter(req, resp);//send request to next resource
13 }//if
14 else
15 {
16 out.print("<p>invalid login/password</p>");
17 }//else
18 out.print("<p>filter1 is invoked after</p>");
19 }
20 public void destroy() {}
21 }

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 120
Filter Example-2
Filter1.java
1 public class Filter2 implements Filter{
2
3 String permission;
4 public void init(FilterConfig config) throws ServletException
5 { permission=config.getInitParameter("permit");
6 }
7
8 public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException,
9 ServletException
10 { PrintWriter out=resp.getWriter();
11 out.print("<p>filter2 is invoked before</p>");
12 if(permission.equals("yes"))
13 { chain.doFilter(req, resp);}//if
14 else
15 {
16 out.println("Permission Denied");
17 }//else
18 out.print("<p>filter2 is invoked after</p>");
19 }
20 public void destroy() {}}

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 121
Filter Example-2
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 }
10

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 122
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.

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 123
Servlet with JDBC
ServletWithJDBC.java
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();
11 //Program continued in next slide ...
12 try{
13 Class.forName("com.mysql.jdbc.Driver");
14 Connection con=DriverManager.getConnection ("jdbc:mysql://localhost:3306/ajava","root","");
15 Statement st=con.createStatement();
16 ResultSet rs=st.executeQuery("select * from cxcy");
17 while(rs.next())
18 { out.println("<p>"+rs.getInt(1));
19 out.println(rs.getString(2));
20 out.println(rs.getString(3)+"</p>");
21 }
22 }catch(Exception e)
23 {out.println("<p>inside exception"+e.toString()+"</p>");}
24 }//doGet()
25 }//Class

Prof. Jayesh D. Vagadiya # 3160707  Unit 3 – Servlet API and Overview 124

You might also like