0% found this document useful (0 votes)
56 views

Unit-3 (Part-I) - Servlet API and Overview

This document provides an overview of the Servlet API unit of an Advanced Java course. It discusses key topics like what a servlet is, the servlet life cycle, and comparisons between servlets and CGI. Specifically, it notes that servlets are Java classes that extend the functionality of web servers by dynamically generating web pages. The servlet life cycle involves loading the servlet class, creating an instance, calling the init() method, processing requests via the service() method, and finally destroying the servlet in the destroy() method. It also outlines advantages of servlets over CGI like being portable, handling requests via threads instead of processes, and enabling session tracking.

Uploaded by

hariom patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Unit-3 (Part-I) - Servlet API and Overview

This document provides an overview of the Servlet API unit of an Advanced Java course. It discusses key topics like what a servlet is, the servlet life cycle, and comparisons between servlets and CGI. Specifically, it notes that servlets are Java classes that extend the functionality of web servers by dynamically generating web pages. The servlet life cycle involves loading the servlet class, creating an instance, calling the init() method, processing requests via the service() method, and finally destroying the servlet in the destroy() method. It also outlines advantages of servlets over CGI like being portable, handling requests via threads instead of processes, and enabling session tracking.

Uploaded by

hariom patel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 111

2160707

Advanced Java

Unit-3 (Part-I)
Servlet API and
Overview

Prof. Swati R. Sharma


[email protected]
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

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

Unit-3 Servlet API and Overview 3 Darshan Institute of Engineering & 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 Servlet API and Overview 4 Darshan Institute of Engineering & 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 Servlet API and Overview 5 Darshan Institute of Engineering & 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 Server
Dynamic Response

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

7
Unit-3 Servelt API and Overview 7 Darshan Institute of Engineering & 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 Servlet API and Overview 8 Darshan Institute of Engineering & 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 Servlet API and Overview 9 Darshan Institute of Engineering & 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 Servlet API and Overview 10 Darshan Institute of Engineering & 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 Servlet API and Overview 11 Darshan Institute of Engineering & 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 Servlet API and Overview 12 Darshan Institute of Engineering & Technology
Servlet Life Cycle

13
Unit-3 Servelt API and Overview 13 Darshan Institute of Engineering & 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 Servlet API and Overview 14 Darshan Institute of Engineering & 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 Servlet API and Overview 15 Darshan Institute of Engineering & 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 Servlet API and Overview 16 Darshan Institute of Engineering & 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
Contains interface and abstract class for
Class

HttpServlet servlet that understands HTTP protocol.


extended by Package: javax.servlet.http

MyServlet User defined Servlet class.

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


}

Unit-3 Servlet API and Overview 19 Darshan Institute of Engineering & 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 Servlet API and Overview 20 Darshan Institute of Engineering & 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 Servlet API and Overview 21 Darshan Institute of Engineering & Technology
Servlet Life Cycle: Destroy()
public void destroy()
{
// Finalization code...
}

Unit-3 Servlet API and Overview 22 Darshan Institute of Engineering & Technology
1
2

5
3

23
Ref: https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
Servlet Life Cycle

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

25
Unit-3 Servelt API and Overview 25 Darshan Institute of Engineering & 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 Servlet API and Overview 26 Darshan Institute of Engineering & 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 Servlet API and Overview 27 Darshan Institute of Engineering & 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 Servlet API and Overview 28 Darshan Institute of Engineering & 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 Servlet API and Overview 29 Darshan Institute of Engineering & Technology
doGet() vs doPost()
 Example: doGet()

Unit-3 Servlet API and Overview 30 Darshan Institute of Engineering & 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 insensitive data Used when comparatively large amount of
like a query has to be sent as a request. sensitive 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

Unit-3 Servlet API and Overview 31 Darshan Institute of Engineering & 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
Sum’19
Win’19

2. Servlets vs CGI [3] Sum’16

Unit-3 Servlet API and Overview 32 Darshan Institute of Engineering & 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 Servlet API and Overview 33 Darshan Institute of Engineering & Technology
Steps to run Servlet Program in

Using Netbeans IDE

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

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

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

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

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

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

Unit-3 Servlet API and Overview 41 Darshan Institute of Engineering & 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 Servlet API and Overview 42 Darshan Institute of Engineering & 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 Servlet API and Overview 43 Darshan Institute of Engineering & 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 Servlet API and Overview 44 Darshan Institute of Engineering & Technology
Steps for Servlet Program
Step 9: index.html

Unit-3 Servlet API and Overview 45 Darshan Institute of Engineering & 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 Servlet API and Overview 46 Darshan Institute of Engineering & Technology
Steps for Servlet Program
Step 11: Run your application, right click on your Project and select Run

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

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

49
Unit-3 Servelt API and Overview 49 Darshan Institute of Engineering & 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 Servlet API and Overview 50 Darshan Institute of Engineering & 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 Servlet API and Overview 51 Darshan Institute of Engineering & 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 Servlet API and Overview 52 Darshan Institute of Engineering & 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 Servlet API and Overview 53 Darshan Institute of Engineering & 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 Servlet API and Overview 54 Darshan Institute of Engineering & Technology
GTU Questions
1. GenericServlet vs HttpServlet [3] Sum’16
Win’18
Win’19

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

web.xml

56
Unit-3 Servelt API and Overview 56 Darshan Institute of Engineering & 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 Servlet API and Overview 57 Darshan Institute of Engineering & 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 Servlet API and Overview 58 Darshan Institute of Engineering & Technology
Program to call servlet from html file

Unit-3 Servelt API and Overview 59 Darshan Institute of Engineering & 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 Servlet API and Overview 60 Darshan Institute of Engineering & 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 Servlet API and Overview 61 Darshan Institute of Engineering & Technology
Servlet Program: Output

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

Unit-3 Servelt API and Overview 63 Darshan Institute of Engineering & 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 Servlet API and Overview 64 Darshan Institute of Engineering & 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 Servlet API and Overview 65 Darshan Institute of Engineering & Technology
Output

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

Write a Servlet program to enter two


numbers and find maximum among
them.

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

.html .java
[Servlet]

Unit-3 Servlet API and Overview 68 Darshan Institute of Engineering & 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 Servlet API and Overview 69 Darshan Institute of Engineering & 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 Servlet API and Overview 70 Darshan Institute of Engineering & Technology
Servlet program using doPost()
Executing max.html

Using doPost()

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

Using doGet()

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

Unit-3 Servelt API and Overview 73 Darshan Institute of Engineering & 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 Servlet API and Overview 74 Darshan Institute of Engineering & 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 Servlet API and Overview 75 Darshan Institute of Engineering & 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 Servlet API and Overview 76 Darshan Institute of Engineering & Technology
Servlet Config: Output

<param-value>

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

Unit-3 Servelt API and Overview 78 Darshan Institute of Engineering & 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 Servlet API and Overview 79 Darshan Institute of Engineering & 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 Servlet API and Overview 80 Darshan Institute of Engineering & 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 Servlet API and Overview 81 Darshan Institute of Engineering & 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 Servlet API and Overview 82 Darshan Institute of Engineering & Technology
Output

Unit-3 Servlet API and Overview 83 Darshan Institute of Engineering & 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 Servlet API and Overview 84 Darshan Institute of Engineering & 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 Servlet API and Overview 85 Darshan Institute of Engineering & Technology
HttpServletRequest

Methods

86
Unit-3 Servelt API and Overview 86 Darshan Institute of Engineering & 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 Servlet API and Overview 87 Darshan Institute of Engineering & 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 Servlet API and Overview 88 Darshan Institute of Engineering & 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 Servlet API and Overview 89 Darshan Institute of Engineering & 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 Servlet API and Overview 90 Darshan Institute of Engineering & 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 Servlet API and Overview 91 Darshan Institute of Engineering & 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 Servlet API and Overview 92 Darshan Institute of Engineering & 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 Servlet API and Overview 93 Darshan Institute of Engineering & 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 Servlet API and Overview 94 Darshan Institute of Engineering & Technology
Servlet Collaboration

RequestDispatcher Interface

95
Unit-3 Servelt API and Overview 95 Darshan Institute of Engineering & 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 Servlet API and Overview 96 Darshan Institute of Engineering & 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 Servlet API and Overview 97 Darshan Institute of Engineering & 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 Servlet API and Overview 98 Darshan Institute of Engineering & 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 Servlet API and Overview 99 Darshan Institute of Engineering & 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 Servlet API and Overview 100 Darshan Institute of Engineering & 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 Servlet API and Overview 101 Darshan Institute of Engineering & 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 Servlet API and Overview 102 Darshan Institute of Engineering & Technology
RequestDispatcher: Servlet Program

Validate Servlet
[CallServlet.java]

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

Unit-3 Servlet API and Overview 103 Darshan Institute of Engineering & 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 Servlet API and Overview 104 Darshan Institute of Engineering & 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 Servlet API and Overview 105 Darshan Institute of Engineering & 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 Servlet API and Overview 106 Darshan Institute of Engineering & 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 Servlet API and Overview 107 Darshan Institute of Engineering & Technology
Servlet Collaboration

sendRedirect()
javax.servlet.http.HttpServletResponse

108
Unit-3 Servelt API and Overview 108 Darshan Institute of Engineering & 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 Servlet API and Overview 109 Darshan Institute of Engineering & 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 Servlet API and Overview 110 Darshan Institute of Engineering & Technology
GTU Questions
1. Differentiate the following
i. forward() vs include() method of RequestDispatcher
ii. forward() vs sendRedirect()

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

You might also like