SlideShare ist ein Scribd-Unternehmen logo
1 von 116
Server-side Programming:
Java Servlets
What is a Servlet?
• 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 extends the capabilities of the
servers and responds to the incoming requests. It can
respond to any type of requests.
• Servlet is a web component that is deployed on the server
to create dynamic web page.
CGI(Commmon Gateway Interface)
• CGI technology enables the web server to call
an external program and pass HTTP request
information to the external program to process
the request.
• For each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:
• If number of clients increases, it takes more time
for sending response.
• For each request, it starts a process and Web
server is limited to start processes.
• It uses platform dependent language e.g. C,
C++, perl.
Advantage of Servlet
• The web container creates threads for handling
the multiple requests to the servlet.
• Threads have a lot of benefits over the
Processes such as they share a common
memory area, lightweight, cost of
communication between the threads are low.
The basic benefits of servlet are as follows:
• Better performance: because it creates a thread for
each request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so we don't need
to worry about memory leak, garbage collection etc.
• Secure: because it uses java language
Benefits of servlet
• .
• Portability
• Powerful
• Efficiency
• Safety
• Integration
• Extensibility
• Inexpensive
• Secure
• Performance
Java Servlet
• Javax.servlet package can be extended for use with
any application layer protocol
– http is the most popularly used protocol
– Javax.servlet.http package is extension of the javax.servlet
package for http protocol
• The Servlet spec allows you to implement separate Java methods
implementing each HTTP method in your subclass of HttpServlet.
– Override the doGet() and/or doPost() method to provide normal
servlet functionality.
– Override doPut() or doDelete() if you want to implement these
methods.
– There's no need to override doOptions() or doTrace().
– The superclass handles the HEAD method all on its own.
Anatomy of a Servlet
• init()
• destroy()
• service()
• doGet()
• doPost()
• Servlet API life cycle methods
– init(): called when servlet is instantiated; must
return before any other methods will be called
– service(): method called directly by server when
an HTTP request is received; default service()
method calls doGet() (or related methods covered
later)
– destroy(): called when server shuts down
Servlet
Container
Thread Thread
Servlet
Create Thread Pool
Instantiate servlet
Call init ( ) method
Allocate request to thread
Allocate request to thread
Block all further requests Wait
for active threads to end
Terminate thread pool
call destroy ( ) method
terminate servlet
Container shutdown
Call service ( ) method
Call service ( ) method
Perform
Initialization
Perform Service
Perform
cleanup
Servlet destroyed
& garbage collected
Perform Service
Shutdown
Initiated
HTTP
Request 1
HTTP
Request 2
HTTP
Response 1
HTTP
Response 2
Anatomy of a Servlet
• HTTPServletRequest object
• Information about an HTTP request
• Headers
• Query String
• Session
• Cookies
• HTTPServletResponse object
• Used for formatting an HTTP response
• Headers
• Status codes
• Cookies
Server-side Programming
• The combination of
– HTML
– JavaScript
– DOM
is sometimes referred to as Dynamic HTML (DHTML)
• Web pages that include scripting are often called
dynamic pages (vs. static)
Server-side Programming
• Similarly, web server response can be static or
dynamic
– Static: HTML document is retrieved from the file
system and returned to the client
– Dynamic: HTML document is generated by a program
in response to an HTTP request
• Java servlets are one technology for producing
dynamic server responses
– Servlet is a class instantiated by the server to
produce a dynamic response
Servlet Overview
Servlet Overview
Reading Data from a Client
1. When server starts it instantiates servlets
2. Server receives HTTP request, determines
need for dynamic response
3. Server selects the appropriate servlet to
generate the response, creates
request/response objects, and passes them to
a method on the servlet instance
4. Servlet adds information to response object via
method calls
5. Server generates HTTP response based on
information stored in response object
• The browser uses two methods to pass this information
to web server. These methods are GET Method and
POST Method.
• GET Method (doGet())
• The GET method sends the encoded user information
appended to the page request. The page and the
encoded information are separated by the ?(question
mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
• POST Method
• A generally more reliable method of passing information
to a backend program is the POST method.
• This packages the information in exactly the same way
as GET method, but instead of sending it as a text string
after a ? (question mark) in the URL it sends it as a
separate message.
• This message comes to the backend program in the
form of the standard input which you can parse and use
for your processing.
• Servlet handles this type of requests
using doPost() method.
• Servlets handles form data parsing automatically using
the following methods depending on the situation −
• getParameter() − You call request.getParameter()
method to get the value of a form parameter.
• getParameterValues() − Call this method if the
parameter appears more than once and returns multiple
values, for example checkbox.
• getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
Example
All servlets we will write
are subclasses of
HttpServlet
Server calls doGet() in response to GET request
Interfaces implemented by request/response objects
Production servlet should
catch these exceptions
First two
things done
by typical servlet;
must be in this
order
Good practice to explicitly close
the PrintWriter when done
Servlets vs. Java Applications
• Servlets do not have a main()
– The main() is in the server
– Entry point to servlet code is via call to a
method (doGet() in the example)
• Servlet interaction with end user is indirect
via request/response object APIs
– Actual HTTP request/response processing is
handled by the server
• Primary servlet output is typically HTML
Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated;
must return before any other methods will be
called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or
related methods covered later)
– destroy(): called when server shuts down
Reading HTTP Request Headers
https://www.tutorialspoint.com/servlets/servlets-client-request.htm
• When a browser requests for a web page, it sends lot of
information to the web server which cannot be read
directly because this information travel as a part of
header of HTTP request. You can check HTTP Protocol
for more information on this.
• Following is the important header information which
comes from browser side and you would use very
frequently in web programming −
Accept
• This header specifies the MIME types that the browser or other
clients can handle. Values of image/png or image/jpeg are the two
most common possibilities.
Accept-Charset
• This header specifies the character sets the browser can use to
display the information. For example ISO-8859-1.
Accept-Encoding
• This header specifies the types of encodings that the browser knows
how to handle. Values of gzip or compress are the two most
common possibilities.
Accept-Language
• This header specifies the client's preferred languages in
case the servlet can produce results in more than one
language. For example en, en-us, ru, etc
Authorization
• This header is used by clients to identify themselves
when accessing password-protected Web pages.
Connection
• This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other
browser to retrieve multiple files with a single request. A value of
Keep-Alive means that persistent connections should be used.
Content-Length
• This header is applicable only to POST requests and gives the size
of the POST data in bytes.
•
Cookie
• This header returns cookies to servers that previously sent them to
the browser.
Host
• This header specifies the host and port as given in the
original URL.
If-Modified-Since
• This header indicates that the client wants the page only
if it has been changed after the specified date. The
server sends a code, 304 which means Not Modified
header if no newer result is available.
If-Unmodified-Since
• This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the specified
date.
Referer
• This header indicates the URL of the referring Web page. For example, if
you are at Web page 1 and click on a link to Web page 2, the URL of Web
page 1 is included in the Referrer header when the browser requests Web
page 2.
User-Agent
• This header identifies the browser or other client making the request and
can be used to return different content to different types of browsers.
Methods
• Cookie[] getCookies()
• Enumeration getAttributeNames()
• Enumeration getHeaderNames()
• Enumeration getParameterNames()
• HttpSession getSession()
• HttpSession getSession(boolean create)
• Locale getLocale()
• Object getAttribute(String name)
• ServletInputStream getInputStream()
• String getAuthType()
• String getCharacterEncoding()
• String getContentType()
• String getContextPath()
• String getHeader(String name)
• String getMethod()
• String getParameter(String name)
Writing HTTP Response Header
• when a Web server responds to an HTTP
request, the response typically consists of a
status line, some response headers, a blank
line, and the document. A typical response looks
like this −
1
Allow
This header specifies the request methods (GET, POST, etc.) that the
server supports.
2
Cache-Control
This header specifies the circumstances in which the response document
can safely be cached. It can have values public, privateor no-cache etc.
Public means document is cacheable, Private means document is for a
single user and can only be stored in private (non-shared) caches and no
cache means document should never be cached.
3
Connection
This header instructs the browser whether to use persistent in HTTP
connections or not. A value of close instructs the browser not to use
persistent HTTP connections and keepalive means using persistent
connections.
4
Content-Disposition
This header lets you request that the browser ask the user to save the
response to disk in a file of the given name.
5
Content-Encoding
This header specifies the way in which the page was encoded during
transmission.
6
Content-Language
This header signifies the language in which the document is written.
For example en, en-us, ru, etc
7
Content-Length
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
8
Content-Type
This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
9
Expires
This header specifies the time at which the content should be considered out-of-
date and thus no longer be cached.
10
Last-Modified
This header indicates when the document was last changed. The client can then
cache the document and supply a date by an If-Modified-Since request header
in later requests.
11
Location
This header should be included with all responses that have a status
code in the 300s. This notifies the browser of the document address. The
browser automatically reconnects to this location and retrieves the new
document.
12
Refresh
This header specifies how soon the browser should ask for an updated
page. You can specify time in number of seconds after which a page
would be refreshed.
13
Retry-After
This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
14
Set-Cookie
This header specifies a cookie associated with the page.
Methods to Set HTTP Response Header
• There are following methods which can be used to set
HTTP response header in your servlet program. These
methods are available with HttpServletResponse object.
Sr.No.
Method & Description
1
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3
boolean containsHeader(String name)
Returns a Boolean indicating whether the named response header has already been set.
4
boolean isCommitted()
Returns a Boolean indicating if the response has been committed.
5
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6
void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7
void addHeader(String name, String value)
Adds a response header with the given name and value.
8
void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9
void flushBuffer()
Forces any content in the buffer to be written to the client.
10
void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11
void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12
void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
Sessions
• Many interactive Web sites spread user
data entry out over several pages:
– Ex: add items to cart, enter shipping
information, enter billing information
• Problem: how does the server know which
users generated which HTTP requests?
– Cannot rely on standard HTTP headers to
identify a user
Sessions
Sessions
Server sends back
new unique
session ID when
the request has
none
Sessions
Client that supports
session stores the
ID and sends it
back to the server
in subsequent
requests
Sessions
Server knows
that all of these
requests are
from the same
client. The
set of requests
is known as a
session.
Sessions
And the server
knows that all
of these
requests are
from a different
client.
Sessions
Returns HttpSession object associated
with this HTTP request.
• Creates new HttpSession object if no
session ID in request or no object with
this ID exists
• Otherwise, returns previously created
object
Sessions
Boolean indicating whether returned
object was newly created or already
existed.
Sessions
Incremented once per session
Sessions
Three web
pages produced
by a single servlet
Sessions
Sessions
Sessions
Sessions
Sessions
,,,
Sessions
,,, Session attribute is a
name/value pair
Sessions
,,,
Session attribute will
have null value until
a value is assigned
Sessions
,,,
Generate
sign-in form
if session is
new or
signIn
attribute has no value,
weclome-back page
otherwise.
Sessions
Sign-in form
Welcome-back
page
Sessions
Second argument
(“Greeting”) used as
action attribute value
(relative URL)
Sessions
Form will be sent using POST HTTP
method (doPost() method will be called)
Sessions
Text field containing
user name is named
signIn
Sessions
…
Sessions
…
Retrieve
signIn
parameter value
Sessions
…
Normal
processing:
signIn
parameter
is present in
HTTP request
Sessions
…
Generate
HTML for
response
Sessions
Thank-you page Must escape
XML special
characters in
user input
Sessions
…
Assign a
value to the
signIn session
attribute
Sessions
• Session attribute methods:
– setAttribute(String name, Object
value): creates a session attribute with the
given name and value
– Object getAttribute(String name):
returns the value of the session attribute
named name, or returns null if this session
does not have an attribute with this name
Sessions
…
Error
processing
(return user
to sign-in form)
Sessions
• By default, each session expires if a
server-determined length of time elapses
between a session’s HTTP requests
– Server destroys the corresponding session
object
• Servlet code can:
– Terminate a session by calling
invalidate() method on session object
– Set the expiration time-out duration (secs) by
calling setMaxInactiveInterval(int)
Cookies
• A cookie is a name/value pair in the Set-
Cookie header field of an HTTP response
• Most (not all) clients will:
– Store each cookie received in its file system
– Send each cookie back to the server that sent
it as part of the Cookie header field of
subsequent HTTP requests
Cookies
Tomcat sends
session ID as value
of cookie named
JSESSIONID
Cookies
Cookie-enabled
browser returns
session ID as value
of cookie named
JSESSIONID
Cookies
• Servlets can set cookies explicitly
– Cookie class used to represent cookies
– request.getCookies() returns an array of
Cookie instances representing cookie data in
HTTP request
– response.addCookie(Cookie) adds a
cookie to the HTTP response
Cookies
Cookies are expired by
client (server can request
expiration date)
Cookies
Cookies
Return array of cookies
contained in HTTP request
Cookies
Search for
cookie
named
COUNT and
extract value
as an int
Cookies
Cookies
Send
replacement
cookie value
to client
(overwrites
existing cookie)
Cookies
Should call
addCookie()
before writing
HTML
Cookies
Privacy issues
Client
Web site
providing
requested
content
HTTP request to
intended site
HTTP response:
HTML document
including ad <img>
Web site
providing
banner
ads
HTTP request for
ad image
Image
plus Set-Cookie
in response:
third-party cookie
Web site
providing
requested
content
Cookies
Privacy issues
Client
Second
Web site
providing
requested
content
HTTP request to 2nd
intended site
HTTP response:
HTML document
including ad <img>
Web site
providing
banner
ads
HTTP request for
ad image plus Cookie (identifies user)
Image Based on
Referer, I know two
Web sites that
this user has
visited
Cookies
Privacy issues
• Due to privacy concerns, many users
block cookies
– Blocking may be fine-tuned. Ex: Mozilla
allows
• Blocking of third-party cookies
• Blocking based on on-line privacy policy
• Alternative to cookies for maintaining
session: URL rewriting
More Servlet Methods
More Servlet Methods
More Servlet Methods
More Servlet Methods
• Response buffer
– All data sent to the PrintWriter object is
stored in a buffer
– When the buffer is full, it is automatically
flushed:
• Contents are sent to the client (preceded by
header fields, if this is the first flush)
• Buffer becomes empty
– Note that all header fields must be defined
before the first buffer flush
More Servlet Methods
More Servlet Methods
• In addition to doGet() and doPost(),
servlets have methods corresponding to
other HTTP request methods
– doHead(): automatically defined if doGet()
is overridden
– doOptions(), doTrace(): useful default
methods provided
– doDelete(), doPut(): override to support
these methods
Common Gateway Interface
• CGI was the earliest standard technology
used for dynamic server-side content
• CGI basics:
– HTTP request information is stored in
environment variables (e.g.,
QUERY_STRING, REQUEST_METHOD,
HTTP_USER_AGENT)
– Program is executed, output is returned in
HTTP response
Common Gateway Interface
• Advantage:
– Program can be written in any programming
language (Perl frequently used)
• Disadvantages:
– No standard for concepts such as session
– May be slower (programs normally run in
separate processes, not server process)
Java Server Pages
Java Server Pages
• Servlets are pure Java programs. They introduce
dynamism into web pages by using programmatic
content.
• JSP technology is an extension/wrapper over the
Java servlet technology.
• JSP are text based documents.
• We will focus only on JSP since it subsumes the
servlet technology.
• Two major components of JSP:
– Static content: provided by HTML or XML
– Dynamic content: generated by JSP tags and
scriplets written in Java language to encapsulate
the application logic.
JSP compilation into Servlets
Web
Browser
Web
Server
J2EE Web
Container
Java
Servlets
JSP
translation
Initial
request
Subseq
request
More on JSP syntax and
contents
• HTML code for user interface lay out
• JSP tags: declarations, actions, directives,
expressions, scriplets
• JSP implicit objects: a request object, response
object, session object, config object
• Javabeans: for logic that can be taken care of at
the JSP level.
• We will examine only JSP tags here.
JSP Tags
• Declaration: variable declaration
<%! int age = 56 %>
• Directive: ex: import classes
<%@ page import = “java.util.*” %>
• Scriplet: Java code
<% if password(“xyz”) {
%>
<H1> Welcome <H1>
• Expression: regular expression using variables
and constants
– <%= param[3]+4 %>
• Action: <jsp:usebean name =“cart”
class=“com.sun.java.Scart”
Methods
S.No. Method & Description
1
out.print(dataType dt)
Print a data type value
2
out.println(dataType dt)
Print a data type value then terminate the line with new
line character.
3
out.flush()
Flush the stream.
The session Object
• The session object is an instance
of javax.servlet.http.HttpSession and behaves
exactly the same way that session objects
behave under Java Servlets.
• The session object is used to track client session
between client requests.

Weitere ähnliche Inhalte

Ähnlich wie Java Servlets: Server-Side Programming Guide

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2PawanMM
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)Amit Ranjan
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesSam Bowne
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
 

Ähnlich wie Java Servlets: Server-Side Programming Guide (20)

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Servlet classnotes
Servlet classnotesServlet classnotes
Servlet classnotes
 
SERVIET
SERVIETSERVIET
SERVIET
 
Servlets
ServletsServlets
Servlets
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 

Mehr von MouDhara1

datacommunicationnetworking-161025074805.pptx
datacommunicationnetworking-161025074805.pptxdatacommunicationnetworking-161025074805.pptx
datacommunicationnetworking-161025074805.pptxMouDhara1
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptxMouDhara1
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
lecture-i-trees.ppt
lecture-i-trees.pptlecture-i-trees.ppt
lecture-i-trees.pptMouDhara1
 
JSP-Servlet.ppt
JSP-Servlet.pptJSP-Servlet.ppt
JSP-Servlet.pptMouDhara1
 
09 Structures in C.pptx
09 Structures in C.pptx09 Structures in C.pptx
09 Structures in C.pptxMouDhara1
 
Chapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptChapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptMouDhara1
 
04_Recurrences_1.ppt
04_Recurrences_1.ppt04_Recurrences_1.ppt
04_Recurrences_1.pptMouDhara1
 
javascript12.pptx
javascript12.pptxjavascript12.pptx
javascript12.pptxMouDhara1
 
Linked list.pptx
Linked list.pptxLinked list.pptx
Linked list.pptxMouDhara1
 
For Client vs.pptx
For Client vs.pptxFor Client vs.pptx
For Client vs.pptxMouDhara1
 
Form tag.pptx
Form tag.pptxForm tag.pptx
Form tag.pptxMouDhara1
 
Web technology.pptx
Web technology.pptxWeb technology.pptx
Web technology.pptxMouDhara1
 
web tech.pptx
web tech.pptxweb tech.pptx
web tech.pptxMouDhara1
 
Introduction to Data Structure.pptx
Introduction to Data Structure.pptxIntroduction to Data Structure.pptx
Introduction to Data Structure.pptxMouDhara1
 

Mehr von MouDhara1 (20)

ppt_dcn.pdf
ppt_dcn.pdfppt_dcn.pdf
ppt_dcn.pdf
 
datacommunicationnetworking-161025074805.pptx
datacommunicationnetworking-161025074805.pptxdatacommunicationnetworking-161025074805.pptx
datacommunicationnetworking-161025074805.pptx
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptx
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
lecture-i-trees.ppt
lecture-i-trees.pptlecture-i-trees.ppt
lecture-i-trees.ppt
 
JSP-Servlet.ppt
JSP-Servlet.pptJSP-Servlet.ppt
JSP-Servlet.ppt
 
09 Structures in C.pptx
09 Structures in C.pptx09 Structures in C.pptx
09 Structures in C.pptx
 
Chapter 12 - Heaps.ppt
Chapter 12 - Heaps.pptChapter 12 - Heaps.ppt
Chapter 12 - Heaps.ppt
 
DTD1.pptx
DTD1.pptxDTD1.pptx
DTD1.pptx
 
04_Recurrences_1.ppt
04_Recurrences_1.ppt04_Recurrences_1.ppt
04_Recurrences_1.ppt
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
queue.pptx
queue.pptxqueue.pptx
queue.pptx
 
javascript12.pptx
javascript12.pptxjavascript12.pptx
javascript12.pptx
 
Linked list.pptx
Linked list.pptxLinked list.pptx
Linked list.pptx
 
For Client vs.pptx
For Client vs.pptxFor Client vs.pptx
For Client vs.pptx
 
Form tag.pptx
Form tag.pptxForm tag.pptx
Form tag.pptx
 
Web technology.pptx
Web technology.pptxWeb technology.pptx
Web technology.pptx
 
cse.pptx
cse.pptxcse.pptx
cse.pptx
 
web tech.pptx
web tech.pptxweb tech.pptx
web tech.pptx
 
Introduction to Data Structure.pptx
Introduction to Data Structure.pptxIntroduction to Data Structure.pptx
Introduction to Data Structure.pptx
 

Kürzlich hochgeladen

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 

Kürzlich hochgeladen (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 

Java Servlets: Server-Side Programming Guide

  • 2. What is a Servlet? • 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 extends the capabilities of the servers and responds to the incoming requests. It can respond to any type of requests. • Servlet is a web component that is deployed on the server to create dynamic web page.
  • 3.
  • 4. CGI(Commmon Gateway Interface) • CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. • For each request, it starts a new process.
  • 5.
  • 6. Disadvantages of CGI There are many problems in CGI technology: • If number of clients increases, it takes more time for sending response. • For each request, it starts a process and Web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl.
  • 7. Advantage of Servlet • The web container creates threads for handling the multiple requests to the servlet. • Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.
  • 8.
  • 9. The basic benefits of servlet are as follows: • Better performance: because it creates a thread for each request not process. • Portability: because it uses java language. • Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc. • Secure: because it uses java language
  • 10. Benefits of servlet • . • Portability • Powerful • Efficiency • Safety • Integration • Extensibility • Inexpensive • Secure • Performance
  • 11. Java Servlet • Javax.servlet package can be extended for use with any application layer protocol – http is the most popularly used protocol – Javax.servlet.http package is extension of the javax.servlet package for http protocol • The Servlet spec allows you to implement separate Java methods implementing each HTTP method in your subclass of HttpServlet. – Override the doGet() and/or doPost() method to provide normal servlet functionality. – Override doPut() or doDelete() if you want to implement these methods. – There's no need to override doOptions() or doTrace(). – The superclass handles the HEAD method all on its own.
  • 12. Anatomy of a Servlet • init() • destroy() • service() • doGet() • doPost()
  • 13. • Servlet API life cycle methods – init(): called when servlet is instantiated; must return before any other methods will be called – service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later) – destroy(): called when server shuts down
  • 14. Servlet Container Thread Thread Servlet Create Thread Pool Instantiate servlet Call init ( ) method Allocate request to thread Allocate request to thread Block all further requests Wait for active threads to end Terminate thread pool call destroy ( ) method terminate servlet Container shutdown Call service ( ) method Call service ( ) method Perform Initialization Perform Service Perform cleanup Servlet destroyed & garbage collected Perform Service Shutdown Initiated HTTP Request 1 HTTP Request 2 HTTP Response 1 HTTP Response 2
  • 15. Anatomy of a Servlet • HTTPServletRequest object • Information about an HTTP request • Headers • Query String • Session • Cookies • HTTPServletResponse object • Used for formatting an HTTP response • Headers • Status codes • Cookies
  • 16. Server-side Programming • The combination of – HTML – JavaScript – DOM is sometimes referred to as Dynamic HTML (DHTML) • Web pages that include scripting are often called dynamic pages (vs. static)
  • 17. Server-side Programming • Similarly, web server response can be static or dynamic – Static: HTML document is retrieved from the file system and returned to the client – Dynamic: HTML document is generated by a program in response to an HTTP request • Java servlets are one technology for producing dynamic server responses – Servlet is a class instantiated by the server to produce a dynamic response
  • 19. Servlet Overview Reading Data from a Client 1. When server starts it instantiates servlets 2. Server receives HTTP request, determines need for dynamic response 3. Server selects the appropriate servlet to generate the response, creates request/response objects, and passes them to a method on the servlet instance 4. Servlet adds information to response object via method calls 5. Server generates HTTP response based on information stored in response object
  • 20. • The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method. • GET Method (doGet()) • The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ?(question mark) symbol as follows − http://www.test.com/hello?key1 = value1&key2 = value2
  • 21. • POST Method • A generally more reliable method of passing information to a backend program is the POST method. • This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. • This message comes to the backend program in the form of the standard input which you can parse and use for your processing. • Servlet handles this type of requests using doPost() method.
  • 22. • Servlets handles form data parsing automatically using the following methods depending on the situation − • getParameter() − You call request.getParameter() method to get the value of a form parameter. • getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox. • getParameterNames() − Call this method if you want a complete list of all parameters in the current request.
  • 24. All servlets we will write are subclasses of HttpServlet
  • 25. Server calls doGet() in response to GET request
  • 26. Interfaces implemented by request/response objects
  • 28. First two things done by typical servlet; must be in this order
  • 29.
  • 30. Good practice to explicitly close the PrintWriter when done
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38. Servlets vs. Java Applications • Servlets do not have a main() – The main() is in the server – Entry point to servlet code is via call to a method (doGet() in the example) • Servlet interaction with end user is indirect via request/response object APIs – Actual HTTP request/response processing is handled by the server • Primary servlet output is typically HTML
  • 39. Servlet Life Cycle • Servlet API life cycle methods – init(): called when servlet is instantiated; must return before any other methods will be called – service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later) – destroy(): called when server shuts down
  • 40.
  • 41.
  • 42.
  • 43. Reading HTTP Request Headers https://www.tutorialspoint.com/servlets/servlets-client-request.htm • When a browser requests for a web page, it sends lot of information to the web server which cannot be read directly because this information travel as a part of header of HTTP request. You can check HTTP Protocol for more information on this. • Following is the important header information which comes from browser side and you would use very frequently in web programming −
  • 44. Accept • This header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities. Accept-Charset • This header specifies the character sets the browser can use to display the information. For example ISO-8859-1. Accept-Encoding • This header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities.
  • 45. Accept-Language • This header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc Authorization • This header is used by clients to identify themselves when accessing password-protected Web pages.
  • 46. Connection • This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used. Content-Length • This header is applicable only to POST requests and gives the size of the POST data in bytes. • Cookie • This header returns cookies to servers that previously sent them to the browser.
  • 47. Host • This header specifies the host and port as given in the original URL. If-Modified-Since • This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available.
  • 48. If-Unmodified-Since • This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. Referer • This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referrer header when the browser requests Web page 2. User-Agent • This header identifies the browser or other client making the request and can be used to return different content to different types of browsers.
  • 49. Methods • Cookie[] getCookies() • Enumeration getAttributeNames() • Enumeration getHeaderNames() • Enumeration getParameterNames() • HttpSession getSession() • HttpSession getSession(boolean create) • Locale getLocale() • Object getAttribute(String name) • ServletInputStream getInputStream() • String getAuthType() • String getCharacterEncoding() • String getContentType() • String getContextPath() • String getHeader(String name) • String getMethod() • String getParameter(String name)
  • 50. Writing HTTP Response Header • when a Web server responds to an HTTP request, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this −
  • 51. 1 Allow This header specifies the request methods (GET, POST, etc.) that the server supports. 2 Cache-Control This header specifies the circumstances in which the response document can safely be cached. It can have values public, privateor no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (non-shared) caches and no cache means document should never be cached. 3 Connection This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keepalive means using persistent connections.
  • 52. 4 Content-Disposition This header lets you request that the browser ask the user to save the response to disk in a file of the given name. 5 Content-Encoding This header specifies the way in which the page was encoded during transmission. 6 Content-Language This header signifies the language in which the document is written. For example en, en-us, ru, etc
  • 53. 7 Content-Length This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. 8 Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. 9 Expires This header specifies the time at which the content should be considered out-of- date and thus no longer be cached. 10 Last-Modified This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests.
  • 54. 11 Location This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. 12 Refresh This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. 13 Retry-After This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. 14 Set-Cookie This header specifies a cookie associated with the page.
  • 55. Methods to Set HTTP Response Header • There are following methods which can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.
  • 56. Sr.No. Method & Description 1 String encodeRedirectURL(String url) Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. 2 String encodeURL(String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. 3 boolean containsHeader(String name) Returns a Boolean indicating whether the named response header has already been set. 4 boolean isCommitted() Returns a Boolean indicating if the response has been committed. 5 void addCookie(Cookie cookie) Adds the specified cookie to the response. 6 void addDateHeader(String name, long date) Adds a response header with the given name and date-value. 7 void addHeader(String name, String value) Adds a response header with the given name and value. 8 void addIntHeader(String name, int value) Adds a response header with the given name and integer value. 9 void flushBuffer() Forces any content in the buffer to be written to the client. 10 void reset() Clears any data that exists in the buffer as well as the status code and headers. 11 void resetBuffer() Clears the content of the underlying buffer in the response without clearing headers or status code. 12 void sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer.
  • 57. Sessions • Many interactive Web sites spread user data entry out over several pages: – Ex: add items to cart, enter shipping information, enter billing information • Problem: how does the server know which users generated which HTTP requests? – Cannot rely on standard HTTP headers to identify a user
  • 59. Sessions Server sends back new unique session ID when the request has none
  • 60. Sessions Client that supports session stores the ID and sends it back to the server in subsequent requests
  • 61. Sessions Server knows that all of these requests are from the same client. The set of requests is known as a session.
  • 62. Sessions And the server knows that all of these requests are from a different client.
  • 63. Sessions Returns HttpSession object associated with this HTTP request. • Creates new HttpSession object if no session ID in request or no object with this ID exists • Otherwise, returns previously created object
  • 64. Sessions Boolean indicating whether returned object was newly created or already existed.
  • 72. Sessions ,,, Session attribute is a name/value pair
  • 73. Sessions ,,, Session attribute will have null value until a value is assigned
  • 74. Sessions ,,, Generate sign-in form if session is new or signIn attribute has no value, weclome-back page otherwise.
  • 76. Sessions Second argument (“Greeting”) used as action attribute value (relative URL)
  • 77. Sessions Form will be sent using POST HTTP method (doPost() method will be called)
  • 78. Sessions Text field containing user name is named signIn
  • 83. Sessions Thank-you page Must escape XML special characters in user input
  • 84. Sessions … Assign a value to the signIn session attribute
  • 85. Sessions • Session attribute methods: – setAttribute(String name, Object value): creates a session attribute with the given name and value – Object getAttribute(String name): returns the value of the session attribute named name, or returns null if this session does not have an attribute with this name
  • 87. Sessions • By default, each session expires if a server-determined length of time elapses between a session’s HTTP requests – Server destroys the corresponding session object • Servlet code can: – Terminate a session by calling invalidate() method on session object – Set the expiration time-out duration (secs) by calling setMaxInactiveInterval(int)
  • 88. Cookies • A cookie is a name/value pair in the Set- Cookie header field of an HTTP response • Most (not all) clients will: – Store each cookie received in its file system – Send each cookie back to the server that sent it as part of the Cookie header field of subsequent HTTP requests
  • 89. Cookies Tomcat sends session ID as value of cookie named JSESSIONID
  • 90. Cookies Cookie-enabled browser returns session ID as value of cookie named JSESSIONID
  • 91. Cookies • Servlets can set cookies explicitly – Cookie class used to represent cookies – request.getCookies() returns an array of Cookie instances representing cookie data in HTTP request – response.addCookie(Cookie) adds a cookie to the HTTP response
  • 92. Cookies Cookies are expired by client (server can request expiration date)
  • 94. Cookies Return array of cookies contained in HTTP request
  • 99. Cookies Privacy issues Client Web site providing requested content HTTP request to intended site HTTP response: HTML document including ad <img> Web site providing banner ads HTTP request for ad image Image plus Set-Cookie in response: third-party cookie
  • 100. Web site providing requested content Cookies Privacy issues Client Second Web site providing requested content HTTP request to 2nd intended site HTTP response: HTML document including ad <img> Web site providing banner ads HTTP request for ad image plus Cookie (identifies user) Image Based on Referer, I know two Web sites that this user has visited
  • 101. Cookies Privacy issues • Due to privacy concerns, many users block cookies – Blocking may be fine-tuned. Ex: Mozilla allows • Blocking of third-party cookies • Blocking based on on-line privacy policy • Alternative to cookies for maintaining session: URL rewriting
  • 105. More Servlet Methods • Response buffer – All data sent to the PrintWriter object is stored in a buffer – When the buffer is full, it is automatically flushed: • Contents are sent to the client (preceded by header fields, if this is the first flush) • Buffer becomes empty – Note that all header fields must be defined before the first buffer flush
  • 107. More Servlet Methods • In addition to doGet() and doPost(), servlets have methods corresponding to other HTTP request methods – doHead(): automatically defined if doGet() is overridden – doOptions(), doTrace(): useful default methods provided – doDelete(), doPut(): override to support these methods
  • 108. Common Gateway Interface • CGI was the earliest standard technology used for dynamic server-side content • CGI basics: – HTTP request information is stored in environment variables (e.g., QUERY_STRING, REQUEST_METHOD, HTTP_USER_AGENT) – Program is executed, output is returned in HTTP response
  • 109. Common Gateway Interface • Advantage: – Program can be written in any programming language (Perl frequently used) • Disadvantages: – No standard for concepts such as session – May be slower (programs normally run in separate processes, not server process)
  • 111. Java Server Pages • Servlets are pure Java programs. They introduce dynamism into web pages by using programmatic content. • JSP technology is an extension/wrapper over the Java servlet technology. • JSP are text based documents. • We will focus only on JSP since it subsumes the servlet technology. • Two major components of JSP: – Static content: provided by HTML or XML – Dynamic content: generated by JSP tags and scriplets written in Java language to encapsulate the application logic.
  • 112. JSP compilation into Servlets Web Browser Web Server J2EE Web Container Java Servlets JSP translation Initial request Subseq request
  • 113. More on JSP syntax and contents • HTML code for user interface lay out • JSP tags: declarations, actions, directives, expressions, scriplets • JSP implicit objects: a request object, response object, session object, config object • Javabeans: for logic that can be taken care of at the JSP level. • We will examine only JSP tags here.
  • 114. JSP Tags • Declaration: variable declaration <%! int age = 56 %> • Directive: ex: import classes <%@ page import = “java.util.*” %> • Scriplet: Java code <% if password(“xyz”) { %> <H1> Welcome <H1> • Expression: regular expression using variables and constants – <%= param[3]+4 %> • Action: <jsp:usebean name =“cart” class=“com.sun.java.Scart”
  • 115. Methods S.No. Method & Description 1 out.print(dataType dt) Print a data type value 2 out.println(dataType dt) Print a data type value then terminate the line with new line character. 3 out.flush() Flush the stream.
  • 116. The session Object • The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets. • The session object is used to track client session between client requests.