Servlet Technology Model PDF
Servlet Technology Model PDF
Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
2) Http Methods
GET
POST
HEAD
OPTIONS
PUT
DELETE
TRACE
HttpServlet
Life Cycle of HttpRequst
3) HttpServletRequest
To retrive request parameters
To retrive request headers
To retrive request cookies
Retrieving client & Server information from the request
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
4) HttpServletResponse
To set response headers
To set ContentType of response
To get Text Stream for response
To get Binary stream for response
To perform redirecting
To add Cookies to the response
Differences between send-Redirection and forward mechanism :
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Introduction :
2-tier:
known and fixed number of clients we can access 2-tier.
Web resources :
2 types
static
Dynamic
A web page whose content is fixed i.e., static web page
Ex: html , js , images
A web page whose content will be changed dynamically based on time of request generate input
values of the request.
Ex:Servlets, JSP's , Server side java script(ssjs) , PHP
Based on the place client side web resources program executed.(in browser)
Based on the place server side web resources program executed but not resides .(in server side)
1. Browser software.
2. Technology to develop client side.
3. Technology to develop server side.
4. User software.
5. DataBase software.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Specification related package consists of more number of INTERFACES and less number of
CLASSES.
RULES --->interfaces(method declarations)
GUIDELINES----> classes(concrete methods )
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1.Servlet
2.Jsp
3.Asp.net
4.PHP
5.cold fusion
6.CGI
7.server side Java Script.
A servlet is a Server side web component managed by web container for generation of
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
dynamic information.
Web container is the best assistent to the programmer . It maintains entire life cycle of the
servlet.
So that programmer has to concentrate only on Business logic.The remaining operations
Instantiation of Servlet , Executing life cycle, Destroying the Servlet object and etc, taken care
by Web container.
1. Stand alone :
Both web server and web container are available in a single integrated component ,
such type of web container are called Stand-alone web container.
Ex : Tomcat
This type of web containers are best-suitable for small scale applications and rarely
used.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
CGI SERVLETS
It is Process based i.e, for every request a It is thread-based i.e, for every request a
separate process will be created and it is new thread will be created and it is
responsible to generate required response. responsible to process the request.
Creation and Destruction of process for every Creation and Destruction of new thread for
request is costly. If the number of requests every request is not costly . Hence there is
increase it will effects performance of the no effect on performance even though
system.Hence CGI technology fail to the destroy number of requests increases due to this it
of scalable. succeeds to delevary scalable.
Most of the CGI languages are not object Java language itself is Object-Oriented .
oriented.Hence we are missing benefits of OOPs. Hence we can get all benefits of OOPs.
FAST CGI :
It improves performance when compared with traditional CGI. In this case web container
maintains a pool of process so that a single process can serve multiple requests one by one.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Servlet deffination : Servlet is a single instance multiple thread based server side Technology
to develop Dynamic web resources of web application.
Servlet API :
1. javax.servlet: This package defines several classes and interfaces to develop servlets
from scratch irrespective of any protocol.
2. javax.servlet.http : It is the sub package of javax.servlet and contains several
convenient classes and interfaces to develop http based servlets.
javax.servlet Package :
1) Servlet :
Every servlet in java should implement servlet interface either directly or indirectly. ie, Servlet
interface acts as a root interface for all java Servlets.
This interface defines the most common methods (including life cycle methods) which are
applicable for any servlet object.
2) ServletRequest :
ServletRequest object can be used to hold client data.
ServletRequest interface defines several methods to acts as end users provided data from the
request object.
Ex: getParameter()
3) ServletResponse :
ServletResponse object can be used to prepare and send responds to the client.
ServletResponse interface defines several methods which are required for preparation of
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
response.
Ex: getWriter(), setContentType()
4) ServletConfig :
For every servlet , web container creates one ServletConfig object to hold its configuration
information like logical name of the Servlet , instantiation parameters etc.
ServletConfig interface defines several methods to access servlets configuration information.
Ex: getServletName()
getInitParameter()
5) ServletContext :
For every web application, web container will create one ServletContext object to hold
application level configuration information like name of the app'n and ServletContext
parameter etc.
Note : ServletConfig is per Servlet , where as ServletContext is per web application.
6) RequestDispatcher :
By using RequestDispatcher object we can dispatch the request from one component to
another component.
This interface defines two methods.
1. forward()
2.include()
7) SingleThreadModel :
Servlet technology is single instance multi threaded model. i.e, multi threads can
operate simultaneously on the servlet object . Hence there may be a chance of data
inconsistency problems.
we can resolve these problems by using SingleThreadModel interface. If a servlet
implements SingleThreadModel interface, then a single thread can access servlet object
at a time i.e, Servlet can process only one request at a time. i.e, the main objective of
SingleThreadModel interface is to provide thread-safety.
But the problem with SingleThreadModel is Servlet can process only one request at a
time which impacts performance of the system. Because of this problem
SingleThreadModel interface is not recommended to use and it is deprecated in Servlet
1.3 version without introducing any replacement.
we can provide thread-safety to the Servlet by using syncronized keyword.
SingleThreadModel interface doesn't contain any methods . It is a marker interface.
Note: In addition to above interfaces javax.servlet package defines the following
interfaces also .
8) Filter
9) FilterConfig
10) FilterChain
----- to implements Filter Concept.
11) ServletRequestListener
12) ServletRequestAttributeListener
13) ServletContextListener
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
12 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
14) ServletContextAttributeListener
----- to implements Listener Concept.
1) GenericServlet :
This class implement Servlet interface and provides dafault implementation for every method
except service( ). Hence it is an abstract class.
we can use this class as a base class to develope protocol independent servlets.
2) ServletOutputStream :
we can use this class object to send binary data( pdf files , image files , video/audio files etc )
as response to the client.
3) ServletInputStream:
we can use ServletInputStream objects to read binary data send by the client.
Note:
In addition to above classes javax.servlet package defines the following classes also
4) ServletRequestWrapper
5) ServletResponseWrapper
-----------to implement wrapper concept.
6) ServletRequestEvent
7) ServletRequestAttributeEvent
8) ServletContextEvent
9) ServletContextAttributeEvent
-----------to define Events for Listeners.
1. ServletException.
Servlet can throw this exception whenever it faces any difficulty while processing
client request.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
2. UnavailableException :
It is the child class of ServletException and it is depricated .
Note :
In total javax.servlet package defines
14 - Interfaces
9--Classes
2--Exceptions
javax.servlet.Servlet interface :
Every servlet in java should compulsary implement Servlet interface either directly or
indirectly i.e, Servlet interface acts as a root interface for all servlets.
This interface defines the most common methods which can be applicable for any Servlet
object.
The following are the methods defined in Servlet interface.
1. init( )
2. service( )
3. destroy( )
4. getServletConfig( )
5. getServletInfo( )
1. init():
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
14 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
This method will be executed only once by the web container immediately after Servlet
instantiation to perform initialization activities .
Web container won't place Servlet object into service( ) method in the following cases :
1. If init() throws ServletException.
2. If init() doesn't return with in the time period specified by web container.
In the above cases web contaioner makes that servlet object eligible for Garbage Collection
without calling any other life cycle method .
In this case web container creates a new Servlet object to provide service.
2. service( ) :
web container calls this method for every request to provide response.
Entire servicing logic/business logic , we have to define in this method only.
3. destroy() :
This method will be executed only once by the web container to perform claen up activities ,
when ever web container takes servlet object from out of service. This is usually happens at
the time of application undeployed (or) at the time of server shut down (or) Web Container
requires some free memory .
when ever web container calls destroy( ) method , it may not be executed immediately. It will
wait untill completing all currently executing threads.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
NOTE : init( ) , service( ) , destroy( ) are called life cycle methods of Servlet.
we can call destroy() explicitly from the init( ) and service( ) , in this case destroy( ) will be
executed just like a normal method call and servlet object won't be destroyed .
4. getServletConfig :
5. getServletInfo ( ) :
This method returns information about Servlet like Author, version , copy right information
etc.
FirstServlet.java
1) package com.jobs4times;
2) import java.io.IOException;
3) import java.io.PrintWriter;
4) import javax.servlet.Servlet;
5) import javax.servlet.ServletConfig;
6) import javax.servlet.ServletException;
7) import javax.servlet.ServletRequest;
8) import javax.servlet.ServletResponse;
9)
10) public class FirstServlet implements Servlet {
11)
12) static {
13) System.out.println("Servlet class loading");
14) }
15) public FirstServlet () {
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
16 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
web.xml
1) <web-app>
2) <servlet>
3) <servlet-name>first</servlet-name>
4) <servlet-class>com.jobs4times.FirstServlet</servlet-class>
5) <load-on-startup>5</load-on-startup>
6) </servlet>
7) <servlet-mapping>
8) <servlet-name>first</servlet-name>
9) <url-pattern>/fs</url-pattern>
10) </servlet-mapping>
11) </web-app>
http://localhost:8080/SCWCD1A/fs
1. When ever we are sending the request ,webserver checks whether this request is for
static or dynamic information by using URL pattern.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
2. If the request is for static information , Webserver searches for the required static file
and provides required response.
3. If the request is for dynamic information , Webserver forwards that request to
webcontainer .
The webcontainer identifies the corresponding servlet class by using web.xml
4. Webcontainer loads that .class file , perform instantiation , and execute init( ) and
service( ) methods and provide required response to the webserver
5. webserver inturn forwards that response to end-user.
WithOut <load-on-startup> :
First Request:
With <load-on-startup> :
At server startup/Application deployment
Note:
The allowed values for <load-on-startup> tag is an integer i.e., +ve , zero , -ve
In the case of <load-on-startup> in deployment descriptor
If we give the two servlets having the same <load-on-startup> value we can't expect
execution order or behaviour .
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
18 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
The main disadvantage of <load-on-startup> is it increases server start up time without any
specific requirement don't configure this <load-on-startup> on servlet.
Note:
From servlet 2.5v onwards a single servlet can be mapped with multiple <url-pattern>tags
i.e., we can take multiple <url-pattern> tags with in single <servlet-mapping> tag.
Ex:
1) <servlet-mapping>
2) <url-pattern>/test </url-pattern>
3) <url-pattern>/test </url-pattern>
4) </servlet-mapping>
Note :
Whenever we are writing 2 servlets having same url-pattern , if we are sending a request to
particular url-pattern
Note:If we are invoking destroy( ) explicitly inside service( ) that time any exception will be
raised the exception will show to the end-user, when we won't handle this situation .
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
If web-container calls destroy( ) then that time the exception will be raised the exception that
surpressed by the web-container.
constructor Vs init( ) :
destroy( ) Vs finalise( ) :
Before destroying any object Garbage collector always calls finalise( ) to perform
cleanup activities. But we can't expect exact behaviour of Garbage collector. which is
vendor dependent.
Hence instead of depending on finalise( ) , Sun people introduced a specific method
destroy( ) to perform cleanup activities , which should be executed always.
GenericServlet(AC):
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1st way :
This approach is not recommented , because we are not saving config object for the future
purpose . Hence in our servlet any one calls getServletConfig( ), this method returns null .
2 nd way :
This approach is valid , but not recommended to override in Servlet , because internally 3
init () are executed , which impacts performence of the system .
3rd way :
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
In how many ways we can override init( ) in our Servlet and which is the best way ?
1. Every Servlet in java is Serializable. At the time of Serialization of servlet object the
corresponding config object is serialized automatically . Because it is part of object-
graph of Servlet object.
2. If we are serializing config object , from that config object hacker may get
corresponding context object reference. Once hacker got context object he can able to
perform any operation on our application , which is never be recommended security
wise. Hence at the time of serialization of servlet object , we can't Serialize config
object. Due to this reason config variable declared as transient.
2.javax.servlet.http package :
This package defines more convenient classes and interfaces to define http based Servlets .
//protocol dependent
1) HttpServletRequest :
It is the child interface of ServletRequest .
HttpServletRequest object can be used to hold client information.
2) HttpServletResponse :
It is the child interface of ServletResponse.
This object can be used to prepare and send response to the client.
3) HttpSession :
We can use HttpSession object to remember the client information across multiple
requests. i.e., we can use session object for session management purpose.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
4) HttpSessionListener :
To implement http based Listener
5) HttpSessionAttributeListener :
To implement http based Listener
6) HttpSessionBindingListener :
To implement http based Listener
7) HttpSessionActivationListener :
To implement http based Listener
8) HttpSessionContext :
deprecated and hence not recommended to use
1) HttpServlet :
It is the child class of GenericServlet . It can be used for developing http based Servlets .
2) Cookie :
We can use Cookie objects to implement Session management.
3) HttpSessionEvent :
To define Events for http based Listeners.
4) HttpSessionBindingEvent :
To define Events for http based Listeners.
5) HttpServletRequestWrapper :
To define http based Wrappers.
6) HttpServletResponseWrapper :
To define http based Wrappers.
7) HttpUtils :
Deprecated , not recommended to use .
Note:
In total javax.servlet.http package defines
8 ------->interfaces
7------->classes
Webserver and webclient communicate by using some common language ,which is nothing
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
but HTTP .
Http defines a standard structures for HttpRequst and HttpResponse .
Structure of HttpRequest :
Request Line
Request Headers
Request Body
Request Line :
Request Headers :
The request headers describes configuration information of the browser like
Request Body :
1. It contains end-user provides information for the GET request it is optional where as
for the POST request it is mandatory.
2. This is the structure of HttpRequest , If the browser sends request in this format , then
only webserver understands the request . i.e, webserver understandable form.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Structure of HttpResponse :
Status Line
Response Headers
Response Body
Status Line :
200 OK HTTP/1.1
Status Codes :
Response Headers :
These will provide configuration information of the server and information about the
response [meta data] like content type of response , content length , last modified data etc.,
Browser will use these response headers to represent properly the response to the end-user.
Response Body :
It contains the original response provided by webserver.
If the server sends the response in the above form , then only browser understands the
response i.e., it is browser understandable form.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1. GET
2. POST
3. HEAD
4. OPTIONS
5. PUT
6. DELETE
7. TRACE
8. CONNECT
9. MOVE
10. LOCK
11. PROFIND
GET :
1. We can use get request if we are expecting information from the server .
2. Usually for the get request read operation will be performed at server side . Hence
status of application won't be changed in get request.
3. In GET request end-users provided information will be appended to the url as the part
of Query string.
4. As the end-users information is visible in url. there may be a chance of security
problems will raise. Hence sensitive data we can't send by using get request.
5. The length of the url is fixed . Hence we can send only limited amount of information
by get request .
6. Only character data is allowed in url . Hence we can't send binary data by using get
request.
7. As extra client provided information is available in the url , Bookmarking of url is
possible .
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Idempotent request :
By repeating the request multiple times , if there is no change in response such type of
requests are Idempotent requests.
Ex: GET requests are Idempotent and POST requests are not Idempotent.
Safe request :
By repeating the same request multiple times , if there is no side-effect at server side , such
type of requests are called safe-requests .
Ex: GET requests are safe , where as POST requests are not safe to repeat.
1) Type url in the address bar and submit is always GET request.
2) Clicking hyperlink is always GET request.
3) Submitting the form , where method attribute specify with GET value is always GET
request.
4) Submitting the form without method attribute is always GET request i.e., default
method for form is GET.
1) <form action="/test">
2) ----------
3) ---------
4) </form>
POST :
1. If we want to post huge amount of information to the server then we should go for
POST.
Ex: uploading our resume in job portal.
2. Usually in post requests update operation will be performed. The state of operation
will be changed.
3. In post request , client information will be encapsulated in the request body instead of
appending to the url . Hence we can send sensitive data by using POST request.
4. There is no limit on size of request body . Hence we can send huge amount of
information to the Server.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
There is only one-way to send POST request that is to use the form with method attribute
value is POST .
I.e., without having the form there is no chance of sending POST request.
GET POST
If we are expecting information from server , If we want to post huge information to server ,
then we should go for GET . then we should go for POST .
Usually read operation will be performed. Write & update operators will be performed .
Client data will be appended to url in the Client data will be encapsulated in request
form of Query-String . body .
We can't send sensitive information . We can send sensitive information .
We can send only limited information. We can send Huge information.
We can send only text data. We can send text & binary data.
Bookmarking is possible . Bookmarking is not- possible .
GET requests are Idempotent & Safe. POST requests are not-Idempotent & not-Safe.
Multiple ways to send GET request. Only one way to send POST request.
HEAD :
We can use this method to get only response header information like content type ,
content length , last modified date etc., but no response body i.e., head request
retrives always respone header but not response body.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
29 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
For HEAD request , internally doGet( ) will be executed. HEAD request is part of GET
request.
HEAD requests are Idempotent & Safe.
OPTIONS :
This method is for getting supporting http methods to retrive a perticular resource
from the Server side .
OPTIONS method is Idempotent and Safe.
Note: HEAD response is the part of GET response and OPTIONS is the part of HEAD
response .
Host : www.jobs4times.com
Server : Apache
Date : Fri, o8 Nov
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
30 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
PUT :
1. We can use PUT method for placing a resource at Server side where the location is
specified by URL.
2. At the specified location , if already another resource present then the old resource is
replaced with provided new resource .
3. By means of status code we can identify whether replacement is happend or not .
4. 200 means replacement happen , 201 means replacement not happen.
5. PUT method is Idempotent but not Safe .
DELETE :
We can use this method for deleting a perticular resource from Server side. It is
exactly counter part of PUT method.
DELETE is Idempotent , but not-Safe.
Note: As the PUT & DELETE methods are not safe. Most of the web-servers won't allow these
methods by default.
To allow these methods at server side some configuration changes are required.
TRACE :
We can use this method for debugging purposes. If we want to know what request , server
getting exactly as response, then we should go for TRACE method.
TRACE method is Idempotent and Safe.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
31 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
HttpServlet :
We can use HttpServlet class as a base class to develop Http based Servlets.
It is the child class of GenericServlet.
For every Http method XXX , HttpServlet class contains the corresponding doXxx() methods.
Ex:
protected void doGet(HttpServletRequest request , HttpServletResponse response ) throws
ServletException, IOException
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
32 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1) <html>
2) <body><h1>This is HttpServlet Demo</h1>
3) <form action="/scwcd1c/test" method="post">
4) Enter Name : <input type="text" name="uname" >
5) <input type="submit">
6) </form>
7) </body>
8) </html>
FirstServlet.java
1) import javax.servlet.*;
2) import javax.servlet.http.*;
3) import java.io.*;
4) public class FirstServlet extends HttpServlet {
5) public void doGet(HttpServletRequest request, HttpServletResponse response)
6) throws ServletException, IOException {
7) PrintWriter out=response.getWriter();
8) String name=req.getParameter("uname");
9) out.println("Hello"+name+"Good Morning , This is doGet method");
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
33 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
10) }
11) public void doPost(HttpServletRequest request, HttpServletResponse response)
12) throws ServletException, IOException {
13) PrintWriter out=response.getWriter();
14) String name=req.getParameter("uname");
15) out.println("Hello"+name+"Good Morning , This is doPost method");
16) }
17) }
web.xml
1) <web-app>
2) <servlet>
3) <servlet-name>first</servlet-name>
4) <servlet-class>FirstServlet</servlet-class>
5) </servlet>
6) <servlet-mapping>
7) <servlet-name>first</servlet-name>
8) <url-pattern>/fs</url-pattern>
9) </servlet-mapping>
10) </web-app>
Deployment Structure :
1) When ever we are submitting the form , browser prepares HttpRequest and send to
the Server.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
34 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
2) Webserver checks whether the request is for static or for dynamic information, by
using URL.
3) If the request is for static information , webserver provide required response.
4) If the request is for dynamic information , then webserver forwards that request to
web-container.
5) Webcontainer identifies the corresponding matched servlet by using web.xml
6) Webcontainer checks whether the corresponding Servler object is already available or
not . If it is not already available , then webcontainer loads the corresponding .class
file and perform instantiation by executing public no argument constructor .
7) After instantiation , immediately webcontainer creates the ServletConfig object and
invoke init( ) by passing that config object as argument.
8) Webcontainer creates ServletRequest and ServlerResponse object and by passing
those as arguments , It will invoke public service( ).
9) With in that service( ) , request and response objects will be type casted into
HttpServletRequest and HttpServletResponse and invoke protected service( ) by
passing those as arguments.
10) With in the protected service( ) we will identify HttpRequest method and
corresponding doXxx( ) will be invoked. If it is not a valid Http method then it is
method will return 501 status code response saying invalid Http method .
18) }
11) If our Servlet class contain required doXxx( ) , then it will be executed . Otherwise
parent class doXxx( ) will be executed.
NOTE :
1. For every web application, web container creates one ServletContext object at the
time of application deployment.
2. For every Servlet , web container creates one ServletConfig object just before calling
init( ).
3. For every request web container creates one ServletRequest and one ServletResponse
objects just before calling service( ) . Once service( ) completes both request and
response objects will be eligible for Garbage Collector(GC).
Case 1 : If we are writting public service( ) in our Servlet , then for any type of request [GET or
POST] only service( ) will be executed.
Case 2 : If our Servlet contains both public service( ) and protected service( ) , then for every
request only public service( ) will be executed.
Case 3 : If our Servlet contains both service( ) and doGet( ) , then for any request including
GET , only service( ) will be executed. And there is no chance of executing doGet( ).
Note: It is never recommended to place service( ) in our Servlet. i.e., defining service( ) in our
Servlet is stupid kind of activity.
Case 4 : If we are sending get request , but our Servlet doesn't contain doGet( ) , then
HttpServlet doGet( ) will be executed which provides response with 405 status code saying
Http method GET is not Supported by this url.
Case 5 : If we are sending post request , but our servlet doesn't contain doPost( ) , then
HttpServlet doPost( ) will be executed , which provide 405 status code saying Http method
POST is not Supported by this url.
Case 6 : HttpServlet class doesn't contain any abstract method , still it is declared as abstract
class what is the reason ?
For majority methods in HttpServlet , proper implementation is not available and these are
just to send error information .
Hence if we are creating HttpServlet object directly and calling these methods , we will get
just error information , with that we can't do anything.
To prevent instantiation of HttpServlet , Sun people declared HttpServlet class as abstract .
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
36 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Case 7 : To provide same response for both GET and POST request , we have to implement
doGet( ) and doPost( ) as follows .
Ex:
Case 8 : In our Servlet , It is not recommended to override the following methods . Because
these methods are properly implemented inside HttpServlet.
Case 9 : In our Servlet , it is highly recommended to override the following methods , because
these methods doesn't have proper implementation in HttpServlet.
6. doGet( )
7. doPost( )
8. doPut( )
9. doDelete( )
HttpServletRequest :(I)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
3. getParameterNames( )
4. getParameterMap( )
2. Retrieve request Headers
1. getHeader( )
2. getHeaders( )
3. getHeaderNames( )
4. getIntHeader( )
5. getDateHeader( )
3. Retrive Cookies
1. getCookies( )
Form parameters are key-value pairs , where both key and values are String objects
only.
A parameter can be associated with either a single value or with multiple values.
ServletRequest interface defines the following methods to retrieve Form parameters
at server side .
1. getParameter( )
2. getParameterValues( )
3. getParameterNames( )
4. getParameterMap( )
1. getParameter( ) :
String user=request.getParameter("uname");
2. getParameterValues( )
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
38 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1) String[] course=request.getParameterValues("course");
2) for(String s:course) {
3) out.println(s);
4) }
3. getParameterNames( )
Ex:
1) Enumeration e= request.getParameterNames( ) ;
2) while(e.hasMoreElements( ) {
3) String pname=(String)e.nextElement( ) ;
4) String pvalue=request.getParameter(pname);
5) out.println(pname+" "+pvalue);
6) }
4. getParameterMap( )
Returns the map object containing parameter names as keys and parameter values as
map values.
Keys are strings and values are string[ ] .
If the request doesn't associated with any parameters , this method returns empty
map object , but not null.
key(String) value(String[ ])
subject {SCJP , SCWCD }
user { arun }
.......... ...........
---------- ---------
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
39 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Ex:
1) Map m = request.getParameterMap( ) ;
2) for(Object o : m) {
3) Map.Entry m1=(Map.Entry) o;
4) String pname=(String)m1.getKey( );
5) String[ ] pvalue=(String[])m1.getValue() ;
6) out.print(pname+"......." );
7)
8) for( String s1 : pvalue ) {
9) out.println(s1 + " , ");
10) }
11) out.println(" ");
12) }
13) output :
14) subject .....SCJP , SCWCD
15) user.......arun
Example :
1) Map m=req.getParameterMap();
2) Set keySet=m.entrySet();
3) Iterator itr=keySet.iterator();
4) while(itr.hasNext()) {
5) Map.Entry entry=(Map.Entry)itr.next();
6) String pname=(String)entry.getKey();
7) out.println(pname);
8) String[] pvalues=(String[])entry.getValue();
9) out.println(pvalues);
Example :
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
40 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
For every request browser sends its configuration information in the form of request
headers. These may include the media types accepted by browser , encoding types
supported by browser the type of browser etc.
Server uses these request headers to send customized responses to the client.
1) Accept :
media types accepted by browser.[ like txt/html , pdf , ppt , jar ]
2) Accept-Encoding:
Encoding types supported by browser.
3) User-agent:
It represents the type of the browser.
4) Content-length:
It represents the length of request body.
5) Cookie :
Used to send cookies for Session managament.
1. getHeader( )
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
41 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Ex:
String hvalue=request.getHeader("accept");
output :
accept -- text/html , application/xhtml+xml , application/xml ;
2. getHeaders( )
public Enumeration getHeaders(String hname)
3. getHeaderNames( )
Returns all request header names associated with that request object.
HttpServletRequest defines the following more convinient methods to retrive int and
date values(Headers) directly .
4. getIntHeader( )
public int getIntHeader(String hname);
Ex:
String length=request.getIntHeader("content-length");
int l=Integer.parseInt(length);
(OR)
int l=request.getIntHeader("content-length");
If the specified request header is not associated with int value , then this method
returns NumberFormatException.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
42 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
req.getIntHeader("user-agent");//RE:java.lang.NumberFormatException
If the specified request header is not available in getIntHeader() , this method returns
"-1" but not null.
5. getDateHeader( )
Returns the date value associated with specified header as no. of milliseconds
Since Jan 1st 1970.
If we pass these milliseconds as arguments to Date constructor. We will get
exact date
Ex:
long l=request.getDateHeader("date");
Date d=new Date(l);
If the specified header is not associated with the date , then we will get
RuntimeException saying IllegalArgument Exception.
If the specified request header is not available in getDateHeader() , this
method returns "-1" but not null.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
43 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
HttpServletRequest interface defines the following methods to retrive cookies from the
request object .
Cookie[] c = request.getCookiees( ) ;
ServletRequest interface defines the following methods to retrieve client and server
information from request.
Returns fully qualified name of the client which sends the request.
Returns the name of the Server to which the request has been sent .
HttpServletResponse :
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
45 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Http response header describes the configuration information of the server and
information about the response like content-type , content-length , last modified data
etc.,
Browser using these response headers to display response body properly to the end
user.
If the specified header name is already available , to the existing values , this new
value will also be added.
Replacement will not Occur .
If the specified header is already available . Then the old value will be replaced with
new value .
Note:
If the header associated with multiple values . Then we have to use addHeader( )
If the header associated with only one value , then we should go for setHeader( )
By ServletResponse interface :
It contains the following method to set the response.
public void setContentType(String mimeType)
Ex:
response.setContentType("application/PDF")
By HttpServletResponse interface :
It contains setHeader( ) to set content type.
public void setHeader(String hname , String hvalue)
Ex:
response.setHeader("content type" , "text/html");
Note: In general response.setContentType( ) is recommended to use.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
47 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1) import javax.servlet.*;
2) import javax.servlet.http.*;
3)
4) public class BinaryStream extends HttpServlet {
5) public void doGet(HttpServletRequest request,HttpServletResponse response)
6) throws ServletException,IOException{
7) response.getContentType("image/jpeg");
8) ServletOutputStream sos = response.getOutputStream( ) ;
9)
10) //File f= new File("c:\\tomcat\sunset.jpeg");
11)
12) String path=getServletContext( ).getRealPath("sunset.jpeg");
13) File f= new File(path);
14) FileInputStream fis=new FileInputStream(f);
15)
16) byte[] b=new byte[(int)f.length()];
17) //f.length() returns long so we have to convert into int.
18) //[] --> accepts int only
19)
20)
21) fis.read(b); //reading the image & place into byte[]
22) sos.write(b); //write byte[] to response
23) sos.flush( );
24) sos.close( );
25) }
26) }
1) response.setHeader("content-Type","text/xml");
2) PrintWriter out=response.getWriter();
3) out.print("<?xml version=\"1.0\"?>");
4) out.print("<greeting language=\"en_US\">");
5) out.print("hello world");
6) out.print("</greeting>");
Note :
At any point of time we can get either PrintWriter object (or) ServletOutputSteram object but
not both , simultaneously.
Otherwise we will get RuntimeException saying IllegalStateException
Because from the Servlet we can send only one response at a time.
5) -----------
6) }
IIQ: By using which of the following stream we can send both binary & text data as response
from the Servlet ?
1. PrintWriter( )
2. ServletOutputStream ( )
3. ServletInputStream ( )
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
49 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Forward & include should work when both servlets should be in same server .
Some times we have to re-direct the request to another url we can achieve this by using
sendRedirect( ) of HttpServletResponse .
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
50 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
When ever we are sending request to FirstServlet , SecondServlet will provide the
response through re-direction
After committing the response we are not allow to perform re-direction. Otherwise we
will get RuntimeException saying IllegalStateException(Tomcat people doesn't provide
support for this).
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
52 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
This mechanism will work at client side. Hence This mechanism will work at server side and
client aware of which Servlet is providing the it is not visible to the client. Hence client is
required response. not aware of which Servlet is providing the
required response.
In this approach an extra trip is required to the No extra trip is required to the client &
client side . Hence network traffic increases & hence there are no network traffic &
effects the performence of the system. performance problem.
forward mechanism will work with in the
This is only possible mechanism to
web-container only and we can't use this
communicate with resoueces which are present
mechanism to communicate with the
outside of web-container.
resources present outside of container.
Seperate new request object will be created in
Same request object will be forwarded .
send Redirection .
By using HttpServletResponse object . we can By using Request Dispatcher object we can
achieve send redirection. achieve forward mechanism .
response.sendRedirect("/test2"); rd.forward(req , res);
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
53 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Ex:
Cookie c=new Cookie(String name , String value) ;
response.addCookie(c);
NOTE :
1. We can use redirection to communicate either with in the same server or outside the
server. But recommended to use communicate outside.
2. forward mechanism is applicable to communicate only with in the same server . But
outside of server we can't use.
3. To communicate with in the same server we can use either forward or send
redirection but recommended to use forward.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
54 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
55 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
56 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com