SlideShare a Scribd company logo
6.Servlet(Marks 14)
Miss.P.S.Dungarwal
Lecturer in CM Department.
SHHJB Polytechnic, Chandwad.
Advance Java Programming(22517)
Mr. Nilesh Vishwasrao Patil
Web and Web Application
 Web consists of billions of clients and server
connected through wires and wireless networks.
 The web clients make requests to web server. The web
server receives the request, finds the resources and return
the response to the client.
2Miss.P.S.Dungarwal
Web Application
 A web application is an application accessible from
the web.
 A Web application is a web site with dynamic
functionality on the server. Google, Facebook,
Twitter are examples of web applications.
 A web application is composed of web components
like Servlet, JSP, Filter etc. and other components such
as HTML.
 The web components typically execute in Web Server
and respond to HTTP request.
3Miss.P.S.Dungarwal
HTTP
 HTTP is a protocol that clients and servers use on
the web to communicate.
 It is similar to other internet protocols such as
SMTP (Simple Mail Transfer Protocol) and FTP
(File Transfer Protocol) but there is one
fundamental difference.
 HTTP is a stateless protocol.
 The client sends an HTTP request and the server
answers with an HTML page to the client, using HTTP.
4Miss.P.S.Dungarwal
HTTP
5Miss.P.S.Dungarwal
Mr. Nilesh Vishwasrao Patil
HTTP methods
Method Name Description
OPTIONS Request for communication options that are available on the
request/response chain.
GET Request to retrieve information from server using a given URI.
HEAD Identical to GET except that it does not return a message-body,
only the headers and status line.
POST Request for server to accept the entity enclosed in the body of
HTTP method.
DELETE Request for the Server to delete the resource.
CONNECT Reserved for use with a proxy that can switch to being a tunnel.
PUT This is same as POST, but POST is used to create, PUT can be
used to create as well as update. It replaces all current
representations of the target resource with the uploaded content.
6Miss.P.S.Dungarwal
HTTP methods
GET Request POST Request
Data is sent in header to the
server
Data is sent in the request body
Get request can send only
limited amount of data
Large amount of data can be
sent.
Get request is not secured
because data is exposed in URL
Post request is secured
because data is not exposed in
URL.
Get request can be
bookmarked and is more
efficient.
Post request cannot be
bookmarked.
7Miss.P.S.Dungarwal
Servlet : Introduction
 Servlet technology is used to create web
application (resides at server side and generates
dynamic web page).
 Servlet is Java program which run on web server
and responding to request of clients (Web
browser).
 Servlet technology is robust and scalable because
of java language.
10Miss.P.S.Dungarwal
Servlet
 Web applications are helper applications that resides at web
server and build dynamic web pages.
 A dynamic page could be anything like a page that randomly
chooses picture to display or even a page that displays the
current time.
11Miss.P.S.Dungarwal
Servlet : Defined in many ways
 Servlet is a technology i.e. used to create web application.
 Servlet is an API that provides many interfaces and
classes including documentations.
 Servlet is an interface that must be implemented
for creating any servlet.
 Servlet is a class that extend the capabilities of the
servers and respond to the incoming request. It can
respond to any type of requests.
 Servlet is a web component that is deployed on the
server to create dynamic web page. 12Miss.P.S.Dungarwal
Servlet : Defined
13Miss.P.S.Dungarwal
Servlet
 A Java Servlet is a Java object that responds to
HTTP requests. It runs inside a Servlet container.
21Miss.P.S.Dungarwal
Servlet
 A Servlet is part of a Java web application.
 A Servlet container may run multiple web applications at the
same time, each having multiple servlets running inside.
22Miss.P.S.Dungarwal
Servlet
 A Java web application can contain other
components than servlets.
 It can also contain Java Server Pages (JSP), images,
text files, documents, Web Services etc.
23Miss.P.S.Dungarwal
HTTP Request and Response
 The browser sends an HTTP request to the Java web
server.
 The web server checks if the request is for a servlet. If it is,
the servlet container is passed the request.
 The servlet container will then find out which servlet the
request is for, and activate that servlet.
 The servlet is activated by calling the
Servlet.service()method.
 Once the servlet has been activated the servlet processes the
request, and generates a response. The response is then sent
back to the browser. 24Miss.P.S.Dungarwal
Servlet Containers
 Java servlet containers are usually running inside a Java web
server.
 Example: Tomcat, GlasssFish, Jboss etc.
 Container:
 It provides runtime environment for JavaEE (j2ee)
applications.
 It performs many operations that are given below:
 Life Cycle Management
 Multithreaded support
 Security etc.
25Miss.P.S.Dungarwal
Types of Servlet
 Generic Servlet:
 It is in javax.servlet.GenericServlet package
 It is protocol independent.
 HTTP Servlet
 It is in javax.servlet.HTTPServlet package
 Built-in HTTP protocol support.
28Miss.P.S.Dungarwal
Types of Servlet
Generic Servlet HTTP Servlet
Package: javax.servlet Package: javax.servlet.http
It is protocol independent
servlet
It is protocol dependent
specifically only HTTP protocol
request- response handle.
It uses service() method for
handling request-response.
It uses methods like doPost(),
doGet()
29Miss.P.S.Dungarwal
Servlet life cycle
 Each servlet instance is loaded once.
 Each execution happens in a separate thread
 Three methods:
 init() : call only once to initialize servlet.
 service() : Call for every request.
 destroy() : call only once
 Method service() is invoked every time a request
comes. It spawns off threads to perform doGet or
doPost based on the method invoked.
30Miss.P.S.Dungarwal
Servlet life cycle
1. Load Servlet Class.
2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
Note: Step 1,2,3 executed only once when servlet is initially
loaded.
Step 4 executed "N"-timeswhenever http requestcomes
Step 5 executed to destroy servlet means unload servlet class
31Miss.P.S.Dungarwal
Mr. N ilesh Vishwasrao Patil
Servlet life cycle
32Miss.P.S.Dungarwal
Servlet API
 Servlet API consists of two important packages
that encapsulates all the important classes and
interface, namely :
 javax.servlet
 javax.servlet.http
34Miss.P.S.Dungarwal
Servlet Interface: javax.servlet
Interfaces Description
Servlet Declare life cycle methods for servlet. To
implement this interface we have to extends
GenericServlet or HttpServlet classes.
ServletConfig Helps servlet to get initialization parameter
means startup information, basic
information about servlet.
ServletContext Allows servlet to log events and access
information about their environment
ServletRequest Used to read data from client
ServletResponse Used to sent data to client
35Miss.P.S.Dungarwal
Servlet Classes: javax.servlet
Classes Description
GenericServlet Used to create servlet (Protocol
independent)
ServletInputStream Provides an input stream for reading
requests from client.
ServletOutputStream This class supports an output stream
for writing responses to a client
ServletException For handling exception: Error Occurred
UnavailableException For handling exception: generate when
servlet not available
36Miss.P.S.Dungarwal
Servlet Interface: javax.servlet.http
Classes Description
HttpServlet Used to create http servlet (Protocol
dependent)
HttpServletRequest It enables servlets to read data from an
HTTP request
HttpServletResponse It enables servlets to write data to an
HTTP response
HttpSession It allows to read and write session data.
Cookie Cookie class allows state information to
be stored on a client machine
37Miss.P.S.Dungarwal
Servlet Interface: Methods
38Miss.P.S.Dungarwal
GenericServlet class
 It implements Servlet, ServletConfig and
Serializable interfaces.
 It provides the implementation of all the methods of
these interfaces except the service method (You
have to write code in your servlet class for this
method).
 GenericServlet class can handle any type of
request so it is protocol-independent.
39Miss.P.S.Dungarwal
ServletConfig interface
 Object of ServletConfig created by the web
container for each servlet.
 This object can be used to get configuration
information from web.xml file.
 Advantage: No need to edit the servlet file if
information is modified from the web.xml file.
40Miss.P.S.Dungarwal
ServletConfig interface
 public String getInitParameter(String name):
Returns the parameter value for the specified
parameter name.
 Enumeration getInitParameterNames():
Returns all the initialized parameter names.
 public String getServletName():
Returns the name of the servlet.
 public ServletContext getServletContext():
Returns an object of ServletContext.
41Miss.P.S.Dungarwal
ServletConfig interface
42Miss.P.S.Dungarwal
ServletContext interface
 An object of ServletContext is created by the
web container at time of deploying the project
(web application).
 This object can be used to get configuration
information from web.xml file.
 There is only one ServletContext object per web
application.
43Miss.P.S.Dungarwal
ServletContext interface
<context-param>
<param-name>dname </param-name>
<param-value> sun.jdbc.odbc.JdbcOdbcDriver
</param-value>
</context-param>
45Miss.P.S.Dungarwal
HttpServlet
 It extends GenericServlet class and
implements Servlet, ServletConfig and
Serializable interface.
 It provides http specific methods such as
doGet, doPost, doHead, doTrace etc.
48Miss.P.S.Dungarwal
HttpServlet
• The most important are six doxxx methods that get
called when a related HTTP request method is used.
• The six methods are doPost, doPut, doGet, doDelete,
doOptions and doTrace.
• For instance, the doGet method is invoked when the
servlet receives an HTTP request that was sent using
the GET method.
• Of the six doxxx methods, the doPost and the doGet
methods are the most frequently used.
49Miss.P.S.Dungarwal
Implementation
 A Java Servlet is just an ordinary Java class
which implements the interface
 javax.servlet.Servlet;
 The easiest way to implement this interface is
to extend either the
 class GenericServlet or HttpServlet.
51Miss.P.S.Dungarwal
Example
52Miss.P.S.Dungarwal
Implementation
 When an HTTP request arrives at the web
server, targeted for your Servlet, the web
server calls your Servlet's service() method.
 The service() method then reads the request,
and generates a response which is sent back to
the client (e.g. a browser).
53Miss.P.S.Dungarwal
Implementation:HTTP
 The javax.servlet.http.HttpServlet class is a
slightly more advanced base class than
the GenericServlet
 The HttpServlet class reads the HTTP request,
and determines if the request is an HTTP GET,
POST, PUT, DELETE, HEAD etc. and calls one
the corresponding method.
54Miss.P.S.Dungarwal
Implementation: HTTP
55Miss.P.S.Dungarwal
HttpRequest: Interface
 This interface present in
javax.servlet.http.HttpRequest
 The purpose of the HttpRequest object is to
represent the HTTP request a browser sends to
your web application. 56Miss.P.S.Dungarwal
HttpRequest: Parameters
 Thus, anything the browser may send,
is accessible via the HttpRequest.
 We can read initialization parameters also
using HttpServletRequest object with
getInitParameter method.
57Miss.P.S.Dungarwal
HttpRequest: Parameters
 Also we can use following code if request parameters is
send through body part of the Http request.
 If the browser sends an HTTP GET request, the
parameters are included in the query string in the URL.
 If the browser sends an HTTP POST request, the
parameters are included in the body part of the HTTP
request. 58Miss.P.S.Dungarwal
HttpRequest: Header
 The request headers are name, value pairs sent by the browser
along with the HTTP request.
 The request headers contain information about e.g. what
browser software is being used, what file types the browser is
capable of receiving etc. In short, at lot of meta data around the
HTTP request.
 Above example reads the Content-Length header sent by the
browser.
59Miss.P.S.Dungarwal
HttpRequest: InputStream
 If the browser sends an HTTP POST request, request
parameters and other potential data is sent to the server
in the HTTP request body.
 If does not have sent data in parameters means may be
binary data, that time we will require InputStream for
accessing request body come from client.
 InputStream requestBodyInput =
request.getInputStream();
 NOTE: You will have to call this method before
calling any getParameter() method.
60Miss.P.S.Dungarwal
HttpRequest: Session
 It is possible to obtain the session object from the
HttpRequest object too.
 The session object can hold information about a given user,
between requests.
 So, if you set an object into the session object during one
request, it will be available for you to read during any
subsequent requests within the same session time scope.
61Miss.P.S.Dungarwal
HttpResponse: Interface
 This interface is present in java.servlet.http package.
 The purpose of the HttpResponse object is to represent the
HTTP response of web application sends back to the browser.
62Miss.P.S.Dungarwal
HttpResponse: Writing HTML
 To send HTML back to the browser, you have to obtain the
a PrintWriter from the HttpResponse object.
63Miss.P.S.Dungarwal
HttpResponse: Headers
 Headers must be set before any data is written to the response.
 Examples:
 Syntax:
response.setHeader("Header-Name", "Header Value");
 Set Content type:
response.setHeader("Content-Type", "text/html");
 Writing text
response.setHeader("Content-Type", "text/plain");
PrintWriter writer = response.getWriter();
writer.write("This is just plain text");
 Content-length
response.setHeader("Content-Length", "31642"); 64Miss.P.S.Dungarwal
HttpResponse: Writing Binary
Data
 We can also write binary data back to the browser instead of
text.
 For instance, we can send an image back, a PDF file or a Flash
file or something like that.
 First we have to set content type. And need to use following
code:
OutputStream outputStream = response.getOutputStream();
outputStream.write(...);
65Miss.P.S.Dungarwal
HttpResponse: Redirecting
 We can redirect the browser to a different URL from your
servlet.
 You cannot send any data back to the browser when
redirecting
response.sendRedirect("http://www.google.com");
Or Another servlet file call
response.sendRedirect(“HelloServlet");
66Miss.P.S.Dungarwal
HttpSession
 The HttpSession object represents a user session.
 A user session contains information about the user across
multiple HTTP requests.
 When a user enters your site for the first time, the user is given
a unique ID to identify his session by.
 This ID is typically stored in a cookie or in a request parameter.
67Miss.P.S.Dungarwal
HttpSession
 We can store values in the session object, and retrieve
them later. Do it in following way:
session.setAttribute("userName", "theUserName");
 This code sets an attribute named "userName", with
the value "theUserName".
 To read the value again:
String userName = (String) session.getAttribute("userName");
 Values stored in the session object are stored in the
memory of the servlet container.
68Miss.P.S.Dungarwal
HttpSession: Example
 Create one HTML file: index.html which send user name
and password to the servlet file.
 Create two servlet file, one will save user name into
session and that session information is send to another
servlet. This example shows the session tracking.
70Miss.P.S.Dungarwal
RequestDispatcher
 The RequestDispatcher class enables your servlet to "call"
another servlet from inside another servlet.
 We can obtain a RequestDispatcher from the
HttpServletRequest object.
 The above code obtains a RequestDispatcher targeted at whatever Servlet
(or JSP) that is mapped to the URL /anotherUrl.simple. 71Miss.P.S.Dungarwal
RequestDispatcher
 You can call the RequestDispatcher using either its include()
or forward() method.
 The forward() method intended for use in forwarding the request,
meaning after the response of the calling servlet has been committed. You
cannot merge response output using this method.
 The include() method merges the response written by the calling servlet,
and the activated servlet. This way you can achieve "server side includes"
using the include().
72Miss.P.S.Dungarwal
Servlet: Load on start up
 The <servlet> element has a sub-element called
<load-on-startup> which you can use to control when the servlet container
should load the servlet.
 If you do not specify a <load-on-startup> element, the servlet container will
typically load your servlet when the first request arrives for it.
 By setting a <load-on-startup> element, you can tell the servlet container to
load the servlet as soon as the servlet container starts.
 Remember, the servlets init() method is called when the servlet is loaded.
<load-on-startup>1</load-on-startup>
73Miss.P.S.Dungarwal
Cookie
 HTTP Cookies are little pieces of data that a web
application can store on the client machine of users
visiting the web application.
 Typically up to 4 kilo bytes(KB) of data can be store.
 We can write cookies using HttpServletResponse object:
 Example:
Cookie cookie = new Cookie("myCookie",
"myCookieValue"); response.addCookie(cookie);
74Miss.P.S.Dungarwal
Cookie
 By default, each request is considered as a new request.
 In cookies technique, we add cookie with response
from the servlet.
 So cookie is stored in the cache of the browser.
 After that if request is sent by the user, cookie is added
with request by default. Thus, we recognize the user as
the old user.
75Miss.P.S.Dungarwal
Cookie: Types
 Non-persistent cookie:
 It is valid for single session only. It is removed each time
when user closes the browser.
 Persistent cookie:
 It is valid for multiple session . It is not removed each time
when user closes the browser. It is removed only if user
logout or sign-out or clear cookies/cache memory of
browsers.
76Miss.P.S.Dungarwal
Cookie: Pros/Cons
 Advantages:
 Simplest technique of maintaining the state.
 Cookies are maintained at client side.
 Disadvantages
 It will not work if cookie is disabled from the browser.
 Only textual information can be set in Cookie object.
77Miss.P.S.Dungarwal
Cookie: Constructor
 javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of
useful methods for cookies.
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified
name and value.
78Miss.P.S.Dungarwal
Cookie: Methods
 Useful methods:
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.
public String getName() Returns the name of the cookie.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
79Miss.P.S.Dungarwal
Cookie: Methods
 Other methods:
 public void addCookie(Cookie ck):method of
HttpServletResponse interface is used to add cookie in
response object.
 public Cookie[] getCookies():method of
HttpServletRequest interface is used to return all the
cookies from the browser.
80Miss.P.S.Dungarwal
Cookie: How to create?
 Creating cookie object
Cookie ck=new Cookie("user",”Sandip");
 Adding cookie in the response
response.addCookie(ck);//
81Miss.P.S.Dungarwal
Cookie: For delete Cookies
 Deleting value of cookie
Cookie ck=new Cookie("user","");
 Changing the maximum age to 0 seconds
ck.setMaxAge(0);
 Adding cookie in the response
response.addCookie(ck);
82Miss.P.S.Dungarwal
Cookie: To get Cookies
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}
83Miss.P.S.Dungarwal
Cookie: Example
84Miss.P.S.Dungarwal
Cookie: Example
 Create one Html file which send user name to
first servlet.
 First servlet file set cookies of that user name and
call second servlet file.
 Second servlet file retrieve name of user from
cookies instead of from session.
85Miss.P.S.Dungarwal
MCQ
 Which is of the following are classes and which are
interfaces?
 1. Servlet
 2. ServletConfig
 3. ServletRequest
 4. ServletResponse
 5. HttpServlet
 6. GenericServlet
 7. Cookies
 8. Session 86Miss.P.S.Dungarwal
MCQ
 What is returntype of the getSession() method?
 1. Session
 2. int
 3. HttpSession
 4. boolean
 5. void
87Miss.P.S.Dungarwal
MCQ
 Javax.servlet packages does not have:
 1. HttpServlet
 2. ServletConfig
 3. ServletContext
 4. Servlet
 5. HttpServletRequest
 6. ServletResponse
 7. HttpServletResponse
 8. Cookies
88Miss.P.S.Dungarwal
MCQ
 Javax.servlet packages does not have:
 1. HttpServlet
 2. ServletConfig
 3. ServletContext
 4. Servlet
 5. HttpServletRequest
 6. ServletResponse
 7. HttpServletResponse
 8. Cookies
89Miss.P.S.Dungarwal
MCQ
 Which is correct package for HttpServlet and
HttpServletResponse?
 1. javax.servlet.*;
 2. javax.servlet.http.*;
 3. javax.servlet.httpservlet.*;
 4. java.lang.*;
90Miss.P.S.Dungarwal
MCQ
 Which of the following method is invoked when Http
post request?
 1. doPost()
 2. doPostCall()
 3. doHttpPost()
 4. doPut()
 5. doTrace()
 6. doPostOptions()
91Miss.P.S.Dungarwal
MCQ
 Which of the following method is invoked when Http
post request?
 1. doPost()
 2. doPostCall()
 3. doHttpPost()
 4. doPut()
 5. doTrace()
 6. doPostOptions()
92Miss.P.S.Dungarwal

More Related Content

PPTX
Advance Java Topics (J2EE)
PPT
Jsp ppt
PPT
PPTX
PPTX
Core java complete ppt(note)
PPT
Java servlets
PPTX
Java Server Pages(jsp)
PPTX
Session And Cookies In Servlets - Java
Advance Java Topics (J2EE)
Jsp ppt
Core java complete ppt(note)
Java servlets
Java Server Pages(jsp)
Session And Cookies In Servlets - Java

What's hot (20)

PDF
Intro to html 5
PDF
Basics of JavaScript
PPS
Asp Architecture
PDF
Java 8 Lambda Expressions
PPT
Asynchronous JavaScript & XML (AJAX)
PDF
JavaScript - Chapter 12 - Document Object Model
PPTX
React state
PPT
Java Networking
PPS
Jsp element
PPTX
Java RMI
PPT
JavaScript - An Introduction
PPTX
Jdbc ppt
PDF
JavaScript Interview Questions with Answers
PPTX
Java applet
PPT
Java Script ppt
PPTX
JavaScript Promises
PPT
Javascript Basics
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPT
Asp.net basic
PDF
Javascript essentials
Intro to html 5
Basics of JavaScript
Asp Architecture
Java 8 Lambda Expressions
Asynchronous JavaScript & XML (AJAX)
JavaScript - Chapter 12 - Document Object Model
React state
Java Networking
Jsp element
Java RMI
JavaScript - An Introduction
Jdbc ppt
JavaScript Interview Questions with Answers
Java applet
Java Script ppt
JavaScript Promises
Javascript Basics
JavaScript - Chapter 10 - Strings and Arrays
Asp.net basic
Javascript essentials
Ad

Similar to Advance Java Programming (CM5I) 6.Servlet (20)

PDF
Servlet classnotes
PPTX
PPTX
Servlet in java , java servlet , servlet servlet and CGI, API
PPTX
Java servlets
PPT
Servlet1.ppt
PPT
Servlet.ppt
PPT
Servlet.ppt
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PPTX
Java Servlets
PPT
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
PPTX
Servlets-UNIT3and introduction to servlet
PPT
Web Technologies -- Servlets 4 unit slides
PPT
Lecture 2
PPTX
java Servlet technology
PPT
Servlet (1) also contains code to create it.ppt
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
PPTX
Servlets
PPTX
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
ODP
servlet 2.5 & JSP 2.0
Servlet classnotes
Servlet in java , java servlet , servlet servlet and CGI, API
Java servlets
Servlet1.ppt
Servlet.ppt
Servlet.ppt
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Java Servlets
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
Servlets-UNIT3and introduction to servlet
Web Technologies -- Servlets 4 unit slides
Lecture 2
java Servlet technology
Servlet (1) also contains code to create it.ppt
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
Servlets
21CS642 Module 4_1 Servlets PPT.pptx VI SEM CSE Students
servlet 2.5 & JSP 2.0
Ad

Recently uploaded (20)

PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
master seminar digital applications in india
PDF
RMMM.pdf make it easy to upload and study
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Presentation on HIE in infants and its manifestations
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
master seminar digital applications in india
RMMM.pdf make it easy to upload and study
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharma ospi slides which help in ospi learning
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Microbial disease of the cardiovascular and lymphatic systems
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
102 student loan defaulters named and shamed – Is someone you know on the list?
Final Presentation General Medicine 03-08-2024.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Anesthesia in Laparoscopic Surgery in India
Microbial diseases, their pathogenesis and prophylaxis
Pharmacology of Heart Failure /Pharmacotherapy of CHF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Supply Chain Operations Speaking Notes -ICLT Program
Complications of Minimal Access Surgery at WLH
Presentation on HIE in infants and its manifestations

Advance Java Programming (CM5I) 6.Servlet

  • 1. 6.Servlet(Marks 14) Miss.P.S.Dungarwal Lecturer in CM Department. SHHJB Polytechnic, Chandwad. Advance Java Programming(22517)
  • 2. Mr. Nilesh Vishwasrao Patil Web and Web Application  Web consists of billions of clients and server connected through wires and wireless networks.  The web clients make requests to web server. The web server receives the request, finds the resources and return the response to the client. 2Miss.P.S.Dungarwal
  • 3. Web Application  A web application is an application accessible from the web.  A Web application is a web site with dynamic functionality on the server. Google, Facebook, Twitter are examples of web applications.  A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML.  The web components typically execute in Web Server and respond to HTTP request. 3Miss.P.S.Dungarwal
  • 4. HTTP  HTTP is a protocol that clients and servers use on the web to communicate.  It is similar to other internet protocols such as SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol) but there is one fundamental difference.  HTTP is a stateless protocol.  The client sends an HTTP request and the server answers with an HTML page to the client, using HTTP. 4Miss.P.S.Dungarwal
  • 6. Mr. Nilesh Vishwasrao Patil HTTP methods Method Name Description OPTIONS Request for communication options that are available on the request/response chain. GET Request to retrieve information from server using a given URI. HEAD Identical to GET except that it does not return a message-body, only the headers and status line. POST Request for server to accept the entity enclosed in the body of HTTP method. DELETE Request for the Server to delete the resource. CONNECT Reserved for use with a proxy that can switch to being a tunnel. PUT This is same as POST, but POST is used to create, PUT can be used to create as well as update. It replaces all current representations of the target resource with the uploaded content. 6Miss.P.S.Dungarwal
  • 7. HTTP methods GET Request POST Request Data is sent in header to the server Data is sent in the request body Get request can send only limited amount of data Large amount of data can be sent. Get request is not secured because data is exposed in URL Post request is secured because data is not exposed in URL. Get request can be bookmarked and is more efficient. Post request cannot be bookmarked. 7Miss.P.S.Dungarwal
  • 8. Servlet : Introduction  Servlet technology is used to create web application (resides at server side and generates dynamic web page).  Servlet is Java program which run on web server and responding to request of clients (Web browser).  Servlet technology is robust and scalable because of java language. 10Miss.P.S.Dungarwal
  • 9. Servlet  Web applications are helper applications that resides at web server and build dynamic web pages.  A dynamic page could be anything like a page that randomly chooses picture to display or even a page that displays the current time. 11Miss.P.S.Dungarwal
  • 10. Servlet : Defined in many ways  Servlet is a technology i.e. used to create web application.  Servlet is an API that provides many interfaces and classes including documentations.  Servlet is an interface that must be implemented for creating any servlet.  Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.  Servlet is a web component that is deployed on the server to create dynamic web page. 12Miss.P.S.Dungarwal
  • 12. Servlet  A Java Servlet is a Java object that responds to HTTP requests. It runs inside a Servlet container. 21Miss.P.S.Dungarwal
  • 13. Servlet  A Servlet is part of a Java web application.  A Servlet container may run multiple web applications at the same time, each having multiple servlets running inside. 22Miss.P.S.Dungarwal
  • 14. Servlet  A Java web application can contain other components than servlets.  It can also contain Java Server Pages (JSP), images, text files, documents, Web Services etc. 23Miss.P.S.Dungarwal
  • 15. HTTP Request and Response  The browser sends an HTTP request to the Java web server.  The web server checks if the request is for a servlet. If it is, the servlet container is passed the request.  The servlet container will then find out which servlet the request is for, and activate that servlet.  The servlet is activated by calling the Servlet.service()method.  Once the servlet has been activated the servlet processes the request, and generates a response. The response is then sent back to the browser. 24Miss.P.S.Dungarwal
  • 16. Servlet Containers  Java servlet containers are usually running inside a Java web server.  Example: Tomcat, GlasssFish, Jboss etc.  Container:  It provides runtime environment for JavaEE (j2ee) applications.  It performs many operations that are given below:  Life Cycle Management  Multithreaded support  Security etc. 25Miss.P.S.Dungarwal
  • 17. Types of Servlet  Generic Servlet:  It is in javax.servlet.GenericServlet package  It is protocol independent.  HTTP Servlet  It is in javax.servlet.HTTPServlet package  Built-in HTTP protocol support. 28Miss.P.S.Dungarwal
  • 18. Types of Servlet Generic Servlet HTTP Servlet Package: javax.servlet Package: javax.servlet.http It is protocol independent servlet It is protocol dependent specifically only HTTP protocol request- response handle. It uses service() method for handling request-response. It uses methods like doPost(), doGet() 29Miss.P.S.Dungarwal
  • 19. Servlet life cycle  Each servlet instance is loaded once.  Each execution happens in a separate thread  Three methods:  init() : call only once to initialize servlet.  service() : Call for every request.  destroy() : call only once  Method service() is invoked every time a request comes. It spawns off threads to perform doGet or doPost based on the method invoked. 30Miss.P.S.Dungarwal
  • 20. Servlet life cycle 1. Load Servlet Class. 2. Create Instance of Servlet. 3. Call the servlets init() method. 4. Call the servlets service() method. 5. Call the servlets destroy() method. Note: Step 1,2,3 executed only once when servlet is initially loaded. Step 4 executed "N"-timeswhenever http requestcomes Step 5 executed to destroy servlet means unload servlet class 31Miss.P.S.Dungarwal
  • 21. Mr. N ilesh Vishwasrao Patil Servlet life cycle 32Miss.P.S.Dungarwal
  • 22. Servlet API  Servlet API consists of two important packages that encapsulates all the important classes and interface, namely :  javax.servlet  javax.servlet.http 34Miss.P.S.Dungarwal
  • 23. Servlet Interface: javax.servlet Interfaces Description Servlet Declare life cycle methods for servlet. To implement this interface we have to extends GenericServlet or HttpServlet classes. ServletConfig Helps servlet to get initialization parameter means startup information, basic information about servlet. ServletContext Allows servlet to log events and access information about their environment ServletRequest Used to read data from client ServletResponse Used to sent data to client 35Miss.P.S.Dungarwal
  • 24. Servlet Classes: javax.servlet Classes Description GenericServlet Used to create servlet (Protocol independent) ServletInputStream Provides an input stream for reading requests from client. ServletOutputStream This class supports an output stream for writing responses to a client ServletException For handling exception: Error Occurred UnavailableException For handling exception: generate when servlet not available 36Miss.P.S.Dungarwal
  • 25. Servlet Interface: javax.servlet.http Classes Description HttpServlet Used to create http servlet (Protocol dependent) HttpServletRequest It enables servlets to read data from an HTTP request HttpServletResponse It enables servlets to write data to an HTTP response HttpSession It allows to read and write session data. Cookie Cookie class allows state information to be stored on a client machine 37Miss.P.S.Dungarwal
  • 27. GenericServlet class  It implements Servlet, ServletConfig and Serializable interfaces.  It provides the implementation of all the methods of these interfaces except the service method (You have to write code in your servlet class for this method).  GenericServlet class can handle any type of request so it is protocol-independent. 39Miss.P.S.Dungarwal
  • 28. ServletConfig interface  Object of ServletConfig created by the web container for each servlet.  This object can be used to get configuration information from web.xml file.  Advantage: No need to edit the servlet file if information is modified from the web.xml file. 40Miss.P.S.Dungarwal
  • 29. ServletConfig interface  public String getInitParameter(String name): Returns the parameter value for the specified parameter name.  Enumeration getInitParameterNames(): Returns all the initialized parameter names.  public String getServletName(): Returns the name of the servlet.  public ServletContext getServletContext(): Returns an object of ServletContext. 41Miss.P.S.Dungarwal
  • 31. ServletContext interface  An object of ServletContext is created by the web container at time of deploying the project (web application).  This object can be used to get configuration information from web.xml file.  There is only one ServletContext object per web application. 43Miss.P.S.Dungarwal
  • 32. ServletContext interface <context-param> <param-name>dname </param-name> <param-value> sun.jdbc.odbc.JdbcOdbcDriver </param-value> </context-param> 45Miss.P.S.Dungarwal
  • 33. HttpServlet  It extends GenericServlet class and implements Servlet, ServletConfig and Serializable interface.  It provides http specific methods such as doGet, doPost, doHead, doTrace etc. 48Miss.P.S.Dungarwal
  • 34. HttpServlet • The most important are six doxxx methods that get called when a related HTTP request method is used. • The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. • For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method. • Of the six doxxx methods, the doPost and the doGet methods are the most frequently used. 49Miss.P.S.Dungarwal
  • 35. Implementation  A Java Servlet is just an ordinary Java class which implements the interface  javax.servlet.Servlet;  The easiest way to implement this interface is to extend either the  class GenericServlet or HttpServlet. 51Miss.P.S.Dungarwal
  • 37. Implementation  When an HTTP request arrives at the web server, targeted for your Servlet, the web server calls your Servlet's service() method.  The service() method then reads the request, and generates a response which is sent back to the client (e.g. a browser). 53Miss.P.S.Dungarwal
  • 38. Implementation:HTTP  The javax.servlet.http.HttpServlet class is a slightly more advanced base class than the GenericServlet  The HttpServlet class reads the HTTP request, and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method. 54Miss.P.S.Dungarwal
  • 40. HttpRequest: Interface  This interface present in javax.servlet.http.HttpRequest  The purpose of the HttpRequest object is to represent the HTTP request a browser sends to your web application. 56Miss.P.S.Dungarwal
  • 41. HttpRequest: Parameters  Thus, anything the browser may send, is accessible via the HttpRequest.  We can read initialization parameters also using HttpServletRequest object with getInitParameter method. 57Miss.P.S.Dungarwal
  • 42. HttpRequest: Parameters  Also we can use following code if request parameters is send through body part of the Http request.  If the browser sends an HTTP GET request, the parameters are included in the query string in the URL.  If the browser sends an HTTP POST request, the parameters are included in the body part of the HTTP request. 58Miss.P.S.Dungarwal
  • 43. HttpRequest: Header  The request headers are name, value pairs sent by the browser along with the HTTP request.  The request headers contain information about e.g. what browser software is being used, what file types the browser is capable of receiving etc. In short, at lot of meta data around the HTTP request.  Above example reads the Content-Length header sent by the browser. 59Miss.P.S.Dungarwal
  • 44. HttpRequest: InputStream  If the browser sends an HTTP POST request, request parameters and other potential data is sent to the server in the HTTP request body.  If does not have sent data in parameters means may be binary data, that time we will require InputStream for accessing request body come from client.  InputStream requestBodyInput = request.getInputStream();  NOTE: You will have to call this method before calling any getParameter() method. 60Miss.P.S.Dungarwal
  • 45. HttpRequest: Session  It is possible to obtain the session object from the HttpRequest object too.  The session object can hold information about a given user, between requests.  So, if you set an object into the session object during one request, it will be available for you to read during any subsequent requests within the same session time scope. 61Miss.P.S.Dungarwal
  • 46. HttpResponse: Interface  This interface is present in java.servlet.http package.  The purpose of the HttpResponse object is to represent the HTTP response of web application sends back to the browser. 62Miss.P.S.Dungarwal
  • 47. HttpResponse: Writing HTML  To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object. 63Miss.P.S.Dungarwal
  • 48. HttpResponse: Headers  Headers must be set before any data is written to the response.  Examples:  Syntax: response.setHeader("Header-Name", "Header Value");  Set Content type: response.setHeader("Content-Type", "text/html");  Writing text response.setHeader("Content-Type", "text/plain"); PrintWriter writer = response.getWriter(); writer.write("This is just plain text");  Content-length response.setHeader("Content-Length", "31642"); 64Miss.P.S.Dungarwal
  • 49. HttpResponse: Writing Binary Data  We can also write binary data back to the browser instead of text.  For instance, we can send an image back, a PDF file or a Flash file or something like that.  First we have to set content type. And need to use following code: OutputStream outputStream = response.getOutputStream(); outputStream.write(...); 65Miss.P.S.Dungarwal
  • 50. HttpResponse: Redirecting  We can redirect the browser to a different URL from your servlet.  You cannot send any data back to the browser when redirecting response.sendRedirect("http://www.google.com"); Or Another servlet file call response.sendRedirect(“HelloServlet"); 66Miss.P.S.Dungarwal
  • 51. HttpSession  The HttpSession object represents a user session.  A user session contains information about the user across multiple HTTP requests.  When a user enters your site for the first time, the user is given a unique ID to identify his session by.  This ID is typically stored in a cookie or in a request parameter. 67Miss.P.S.Dungarwal
  • 52. HttpSession  We can store values in the session object, and retrieve them later. Do it in following way: session.setAttribute("userName", "theUserName");  This code sets an attribute named "userName", with the value "theUserName".  To read the value again: String userName = (String) session.getAttribute("userName");  Values stored in the session object are stored in the memory of the servlet container. 68Miss.P.S.Dungarwal
  • 53. HttpSession: Example  Create one HTML file: index.html which send user name and password to the servlet file.  Create two servlet file, one will save user name into session and that session information is send to another servlet. This example shows the session tracking. 70Miss.P.S.Dungarwal
  • 54. RequestDispatcher  The RequestDispatcher class enables your servlet to "call" another servlet from inside another servlet.  We can obtain a RequestDispatcher from the HttpServletRequest object.  The above code obtains a RequestDispatcher targeted at whatever Servlet (or JSP) that is mapped to the URL /anotherUrl.simple. 71Miss.P.S.Dungarwal
  • 55. RequestDispatcher  You can call the RequestDispatcher using either its include() or forward() method.  The forward() method intended for use in forwarding the request, meaning after the response of the calling servlet has been committed. You cannot merge response output using this method.  The include() method merges the response written by the calling servlet, and the activated servlet. This way you can achieve "server side includes" using the include(). 72Miss.P.S.Dungarwal
  • 56. Servlet: Load on start up  The <servlet> element has a sub-element called <load-on-startup> which you can use to control when the servlet container should load the servlet.  If you do not specify a <load-on-startup> element, the servlet container will typically load your servlet when the first request arrives for it.  By setting a <load-on-startup> element, you can tell the servlet container to load the servlet as soon as the servlet container starts.  Remember, the servlets init() method is called when the servlet is loaded. <load-on-startup>1</load-on-startup> 73Miss.P.S.Dungarwal
  • 57. Cookie  HTTP Cookies are little pieces of data that a web application can store on the client machine of users visiting the web application.  Typically up to 4 kilo bytes(KB) of data can be store.  We can write cookies using HttpServletResponse object:  Example: Cookie cookie = new Cookie("myCookie", "myCookieValue"); response.addCookie(cookie); 74Miss.P.S.Dungarwal
  • 58. Cookie  By default, each request is considered as a new request.  In cookies technique, we add cookie with response from the servlet.  So cookie is stored in the cache of the browser.  After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. 75Miss.P.S.Dungarwal
  • 59. Cookie: Types  Non-persistent cookie:  It is valid for single session only. It is removed each time when user closes the browser.  Persistent cookie:  It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or sign-out or clear cookies/cache memory of browsers. 76Miss.P.S.Dungarwal
  • 60. Cookie: Pros/Cons  Advantages:  Simplest technique of maintaining the state.  Cookies are maintained at client side.  Disadvantages  It will not work if cookie is disabled from the browser.  Only textual information can be set in Cookie object. 77Miss.P.S.Dungarwal
  • 61. Cookie: Constructor  javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value. 78Miss.P.S.Dungarwal
  • 62. Cookie: Methods  Useful methods: Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. 79Miss.P.S.Dungarwal
  • 63. Cookie: Methods  Other methods:  public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.  public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser. 80Miss.P.S.Dungarwal
  • 64. Cookie: How to create?  Creating cookie object Cookie ck=new Cookie("user",”Sandip");  Adding cookie in the response response.addCookie(ck);// 81Miss.P.S.Dungarwal
  • 65. Cookie: For delete Cookies  Deleting value of cookie Cookie ck=new Cookie("user","");  Changing the maximum age to 0 seconds ck.setMaxAge(0);  Adding cookie in the response response.addCookie(ck); 82Miss.P.S.Dungarwal
  • 66. Cookie: To get Cookies Cookie ck[]=request.getCookies(); for(int i=0;i<ck.length;i++) { out.print("<br>"+ck[i].getName()+" "+ck[i].getValue()); //printing name and value of cookie } 83Miss.P.S.Dungarwal
  • 68. Cookie: Example  Create one Html file which send user name to first servlet.  First servlet file set cookies of that user name and call second servlet file.  Second servlet file retrieve name of user from cookies instead of from session. 85Miss.P.S.Dungarwal
  • 69. MCQ  Which is of the following are classes and which are interfaces?  1. Servlet  2. ServletConfig  3. ServletRequest  4. ServletResponse  5. HttpServlet  6. GenericServlet  7. Cookies  8. Session 86Miss.P.S.Dungarwal
  • 70. MCQ  What is returntype of the getSession() method?  1. Session  2. int  3. HttpSession  4. boolean  5. void 87Miss.P.S.Dungarwal
  • 71. MCQ  Javax.servlet packages does not have:  1. HttpServlet  2. ServletConfig  3. ServletContext  4. Servlet  5. HttpServletRequest  6. ServletResponse  7. HttpServletResponse  8. Cookies 88Miss.P.S.Dungarwal
  • 72. MCQ  Javax.servlet packages does not have:  1. HttpServlet  2. ServletConfig  3. ServletContext  4. Servlet  5. HttpServletRequest  6. ServletResponse  7. HttpServletResponse  8. Cookies 89Miss.P.S.Dungarwal
  • 73. MCQ  Which is correct package for HttpServlet and HttpServletResponse?  1. javax.servlet.*;  2. javax.servlet.http.*;  3. javax.servlet.httpservlet.*;  4. java.lang.*; 90Miss.P.S.Dungarwal
  • 74. MCQ  Which of the following method is invoked when Http post request?  1. doPost()  2. doPostCall()  3. doHttpPost()  4. doPut()  5. doTrace()  6. doPostOptions() 91Miss.P.S.Dungarwal
  • 75. MCQ  Which of the following method is invoked when Http post request?  1. doPost()  2. doPostCall()  3. doHttpPost()  4. doPut()  5. doTrace()  6. doPostOptions() 92Miss.P.S.Dungarwal