SlideShare a Scribd company logo
1 of 51
JAVA SERVLETS
By Yuvarani P
Kongu Engineering College
 Servlet technology is used to create a web application
(resides at server side and generates a dynamic web page).
 Servlet is an API that provides many interfaces and classes
including documentation.
PROPERTIES OF SERVLETS
 Servlets work on the server-side.
 Servlets are capable of handling complex requests
obtained from web server.
EXECUTION OF SERVLETS
 The clients send the request to the web server.
 The web server receives the request.
 The web server passes the request to the corresponding
servlet.
 The servlet processes the request and generates the
response in the form of output.
 The servlet sends the response back to the web server.
 The web server sends the response back to the client and
the client browser displays it on the screen.
CGI (COMMON 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
 If the number of clients increases, it takes more
time for sending the response.
 For each request, it starts a process, and the web
server is limited to start processes.
 It uses platform dependent language
e.g. C, C++, perl.
ADVANTAGES OF SERVLET
 Better performance: because it creates a thread for each
request, not process.
 Portability: because it uses Java language.
 Robust: JVM manages Servlets, so we don't need to worry
about the memory leak, garbage collection, etc.
 Secure: because it uses java language.
DIFFERENCE BETWEEN SERVLET AND CGI
Servlet CGI(Common Gateway Interface)
Servlets are portable and efficient. CGI is not portable
In Servlets, sharing of data is
possible.
In CGI, sharing of data is not
possible.
Servlets can directly communicate
with the web server.
CGI cannot directly communicate
with the web server.
Servlets are less expensive than
CGI.
CGI are more expensive than
Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
SERVLETS API’S:
 Servlets are build from two packages:
 javax.servlet(Basic)
The javax.servlet package contains many interfaces
and classes that are used by the servlet or web
container. These are not specific to any protocol.
 javax.servlet.http(Advance)
The javax.servlet.http package contains interfaces and
classes that are responsible for http requests only.
INTERFACES IN JAVAX.SERVLET PACKAGE
 Servlet
 ServletRequest
 ServletResponse
 RequestDispatcher
 ServletConfig
 ServletContext
 SingleThreadModel
 Filter
 FilterConfig
 FilterChain
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener
CLASSES IN JAVAX.SERVLET PACKAGE
 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletRequestWrapper
 ServletResponseWrapper
 ServletRequestEvent
 ServletContextEvent
 ServletRequestAttributeEvent
 ServletContextAttributeEvent
 ServletException
 UnavailableException
INTERFACES IN JAVAX.SERVLET.HTTP PACKAGE
 HttpServletRequest
 HttpServletResponse
 HttpSession
 HttpSessionListener
 HttpSessionAttributeListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext (deprecated now)
CLASSES IN JAVAX.SERVLET.HTTP PACKAGE
 HttpServlet
 Cookie
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpUtils (deprecated now)
SERVLET INTERFACE
 Servlet interface needs to be implemented for creating
any servlet (either directly or indirectly).
 It provides 3 life cycle methods that are used to initialize
the servlet, to service the requests, and to destroy the
servlet and 2 non-life cycle methods.
METHODS OF SERVLET INTERFACE
 There are 5 methods in Servlet interface.
 The init, service and destroy are the life cycle methods of
servlet.
 These are invoked by the web container.
METHODS OF SERVLET INTERFACE
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.
public void service(ServletRequest
request,ServletResponse response)
provides response for the incoming
request. It is invoked at each request by
the web container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such
as writer, copyright, version etc.
GENERICSERVLET CLASS
 GenericServlet class
implements Servlet, ServletConfig and Serializable interf
aces.
 It provides the implementation of all the methods of these
interfaces except the service method.
 GenericServlet class can handle any type of request so it is
protocol-independent.
METHODS OF GENERICSERVLET CLASS
 public void init(ServletConfig config) is used to initialize
the servlet.
 public abstract void service(ServletRequest request,
ServletResponse response) provides service for the
incoming request. It is invoked at each time when user
requests for a servlet.
 public void destroy() is invoked only once throughout the
life cycle and indicates that servlet is being destroyed.
 public ServletConfig getServletConfig() returns the
object of ServletConfig.
 public String getServletInfo() returns information about
servlet such as writer, copyright, version etc.
METHODS OF GENERICSERVLET CLASS
 public void init() it is a convenient method for the servlet
programmers, now there is no need to call super.init(config)
 public ServletContext getServletContext() returns the object
of ServletContext.
 public String getInitParameter(String name) returns the
parameter value for the given parameter name.
 public Enumeration getInitParameterNames() returns all the
parameters defined in the web.xml file.
 public String getServletName() returns the name of the servlet
object.
 public void log(String msg) writes the given message in the
servlet log file.
 public void log(String msg,Throwable t) writes the
explanatory message in the servlet log file and a stack trace.
SERVLET EXAMPLE BY INHERITING THE
GENERICSERVLET CLASS
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HTTPSERVLET CLASS
 The HttpServlet class extends the GenericServlet class
and implements Serializable interface.
 It provides http specific methods such as doGet, doPost,
doHead, doTrace etc.
METHODS OF HTTPSERVLET CLASS
 public void service(ServletRequest req,ServletResponse
res) dispatches the request to the protected service method by
converting the request and response object into http type.
 protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the
service method, and dispatches the request to the doXXX()
method depending on the incoming http request type.
 protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request. It is
invoked by the web container.
 protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request. It is
invoked by the web container.
METHODS OF HTTPSERVLET CLASS
 protected void doHead(HttpServletRequest req,
HttpServletResponse res) handles the HEAD request. It
is invoked by the web container.
 protected void doOptions(HttpServletRequest req,
HttpServletResponse res) handles the OPTIONS
request. It is invoked by the web container.
 protected void doPut(HttpServletRequest req,
HttpServletResponse res) handles the PUT request. It is
invoked by the web container.
METHODS OF HTTPSERVLET CLASS
 protected void doTrace(HttpServletRequest req,
HttpServletResponse res) handles the TRACE
request. It is invoked by the web container.
 protected void doDelete(HttpServletRequest
req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web
container.
 protected long
getLastModified(HttpServletRequest req) returns
the time when HttpServletRequest was last
modified since midnight January 1, 1970 GMT.
SERVLETS - CLIENT HTTP REQUEST
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.
An HTTP client sends an HTTP request to a server in the
form of a request message which includes following
format
 A Request-line
 Zero or more header (General|Request|Entity) fields
followed by CRLF
 An empty line (i.e., a line with nothing preceding the
CRLF) indicating the end of the header fields
 Optionally a message-body of HTTP request.
REQUEST-LINE
 The Request-Line begins with a method token,
followed by the Request-URI and the protocol
version, and ending with CRLF. The elements are
separated by space SP characters.
 Request-Line = Method SP Request-URI SP HTTP-
Version CRLF
REQUEST METHOD
GET The GET method is used to retrieve information from the given
server using a given URI. Requests using GET should only retrieve
data and should have no other effect on the data.
HEAD Same as GET, but it transfers the status line and the header section
only.
POST A POST request is used to send data to the server, for example,
customer information, file upload, etc. using HTML forms.
PUT Replaces all the current representations of the target resource with
the uploaded content.
DELETE Removes all the current representations of the target resource given
by URI.
CONNECT Establishes a tunnel to the server identified by a given URI.
OPTIONS Describe the communication options for the target resource.
TRACE Performs a message loop back test along with the path to the target
resource.
REQUEST-URI
 The Request-URI is a Uniform Resource Identifier and identifies the
resource upon which to apply the request.
Request-URI = "*" | absoluteURI | abs_path | authority
S.N. Method and Description
1 The asterisk * is used when an HTTP request does not apply to a particular resource,
but to the server itself, and is only allowed when the method used does not necessarily
apply to a resource.
For example:OPTIONS * HTTP/1.1
2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is
requested to forward the request or service from a valid cache, and return the response.
For example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
3 The most common form of Request-URI is that used to identify a resource on an origin
server or gateway. For example, a client wishing to retrieve a resource directly from the
origin server would create a TCP connection to port 80 of the host "www.w3.org" and
send the following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original URI, it
MUST be given as "/" (the server root).
HEADER & DESCRIPTION
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.
HEADER & DESCRIPTION
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.
HEADER & DESCRIPTION
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.
HEADER & DESCRIPTION
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 TO READ HTTP HEADER
Cookie[] getCookies()
 Returns an array containing all of the Cookie objects the
client sent with this request.
Enumeration getAttributeNames()
 Returns an Enumeration containing the names of the
attributes available to this request.
Enumeration getHeaderNames()
 Returns an enumeration of all the header names this
request contains.
Enumeration getParameterNames()
 Returns an Enumeration of String objects containing the
names of the parameters contained in this request
METHODS TO READ HTTP HEADER
HttpSession getSession()
 Returns the current session associated with this request, or if
the request does not have a session, creates one.
HttpSession getSession(boolean create)
 Returns the current HttpSession associated with this request
or, if if there is no current session and value of create is true,
returns a new session.
Locale getLocale()
 Returns the preferred Locale that the client will accept content
in, based on the Accept-Language header.
Object getAttribute(String name)
 Returns the value of the named attribute as an Object, or null
if no attribute of the given name exists.
ServletInputStream getInputStream()
 Retrieves the body of the request as binary data using a
ServletInputStream.
METHODS TO READ HTTP HEADER
String getAuthType()
 Returns the name of the authentication scheme used to protect
the servlet, for example, "BASIC" or "SSL," or null if the JSP was
not protected.
String getCharacterEncoding()
 Returns the name of the character encoding used in the body of
this request.
String getContentType()
 Returns the MIME type of the body of the request, or null if the
type is not known.
String getContextPath()
 Returns the portion of the request URI that indicates the context
of the request.
String getHeader(String name)
 Returns the value of the specified request header as a String.
METHODS TO READ HTTP HEADER
String getMethod()
 Returns the name of the HTTP method with which this request
was made, for example, GET, POST, or PUT.
String getParameter(String name)
 Returns the value of a request parameter as a String, or null if
the parameter does not exist.
String getPathInfo()
 Returns any extra path information associated with the URL
the client sent when it made this request
String getProtocol()
 Returns the name and version of the protocol the request.
String getQueryString()
 Returns the query string that is contained in the request URL
after the path.
METHODS TO READ HTTP HEADER
String getRemoteAddr()
 Returns the Internet Protocol (IP) address of the client
that sent the request.
String getRemoteHost()
 Returns the fully qualified name of the client that sent
the request.
String getRemoteUser()
 Returns the login of the user making this request, if the
user has been authenticated, or null if the user has not
been authenticated.
String getRequestURI()
 Returns the part of this request's URL from the protocol
name up to the query string in the first line of the HTTP
request.
METHODS TO READ HTTP HEADER
String getRequestedSessionId()
 Returns the session ID specified by the client.
String getServletPath()
 Returns the part of this request's URL that calls the JSP.
String[] getParameterValues(String name)
 Returns an array of String objects containing all of the
values the given request parameter has, or null if the
parameter does not exist.
boolean isSecure()
 Returns a Boolean indicating whether this request was
made using a secure channel, such as HTTPS.
METHODS TO READ HTTP HEADER
int getContentLength()
 Returns the length, in bytes, of the request body
and made available by the input stream, or -1 if the
length is not known.
int getIntHeader(String name)
 Returns the value of the specified request header
as an int.
int getServerPort()
 Returns the port number on which this request was
received.
HTTP HEADER REQUEST EXAMPLE
 Use getHeaderNames() method of HttpServletRequest
to read the HTTP header information.
 This method returns an Enumeration that contains the
header information associated with the current HTTP
request.
 Once we have an Enumeration, we can loop down the
Enumeration in the standard manner,
using hasMoreElements() method to determine when to
stop and using nextElement() method to get each
parameter name
HTTP HEADER REQUEST EXAMPLE
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "HTTP Header Request Example";
String docType =
"<!doctype html public "-//w3c//dtd html 4.0 " + "transitional//en">n";
HTTP HEADER REQUEST EXAMPLE
out.println(docType +
"<html>n" +
"<head><title>" + title + "</title></head>n"+
"<body bgcolor = "#f0f0f0">n" +
"<h1 align = "center">" + title + "</h1>n" +
"<table width = "100%" border = "1" align =
"center">n" +
"<tr bgcolor = "#949494">n" +
"<th>Header Name</th><th>Header
Value(s)</th>n"+
"</tr>n"
);
HTTP HEADER REQUEST EXAMPLE
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>n");
}
out.println("</table>n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
Header Name Header Value(s)
accept */*
accept-language en-us
user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;
InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate
host localhost:8080
connection Keep-Alive
cache-control no-cache
EXAMPLES OF REQUEST MESSAGE
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01;
Windows NT)
Host: www.tutorialspoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
SERVLETS - SERVER HTTP RESPONSE
 An initial status line + CRLF ( Carriage Return +
Line Feed i.e. New Line )
 Zero or more header lines + CRLF
 A blank line, i.e., a CRLF
 An optional message body like file, query data or
query output.
FOR EXAMPLE, A SERVER RESPONSE HEADER
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body> ... </body>
</html>
HTTP RESPONSE STATUS CODES
 HTTP response status codes indicate whether a
specific HTTP request has been successfully
completed. Responses are grouped in five classes:
 Informational responses (100–199)
 Successful responses (200–299)
 Redirects (300–399)
 Client errors (400–499)
 Server errors (500–599)
HTTP RESPONSE HEADERS
S.No. Header & Description
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, private or 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 nocache 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.
HTTP RESPONSE HEADERS
S.No. Header & Description
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.
HTTP RESPONSE HEADERS
S.No. Header & Description
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.

More Related Content

What's hot

What's hot (20)

Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 

Similar to Java servlets

Similar to Java servlets (20)

Servlet
Servlet Servlet
Servlet
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Servlets
ServletsServlets
Servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Servlet viva questions
Servlet viva questionsServlet viva questions
Servlet viva questions
 
Servlet
ServletServlet
Servlet
 

Recently uploaded

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Recently uploaded (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Java servlets

  • 1. JAVA SERVLETS By Yuvarani P Kongu Engineering College
  • 2.  Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).  Servlet is an API that provides many interfaces and classes including documentation.
  • 3. PROPERTIES OF SERVLETS  Servlets work on the server-side.  Servlets are capable of handling complex requests obtained from web server.
  • 4. EXECUTION OF SERVLETS  The clients send the request to the web server.  The web server receives the request.  The web server passes the request to the corresponding servlet.  The servlet processes the request and generates the response in the form of output.  The servlet sends the response back to the web server.  The web server sends the response back to the client and the client browser displays it on the screen.
  • 5. CGI (COMMON 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.
  • 6. DISADVANTAGES OF CGI  If the number of clients increases, it takes more time for sending the response.  For each request, it starts a process, and the web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
  • 7. ADVANTAGES OF SERVLET  Better performance: because it creates a thread for each request, not process.  Portability: because it uses Java language.  Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.  Secure: because it uses java language.
  • 8. DIFFERENCE BETWEEN SERVLET AND CGI Servlet CGI(Common Gateway Interface) Servlets are portable and efficient. CGI is not portable In Servlets, sharing of data is possible. In CGI, sharing of data is not possible. Servlets can directly communicate with the web server. CGI cannot directly communicate with the web server. Servlets are less expensive than CGI. CGI are more expensive than Servlets. Servlets can handle the cookies. CGI cannot handle the cookies.
  • 9. SERVLETS API’S:  Servlets are build from two packages:  javax.servlet(Basic) The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol.  javax.servlet.http(Advance) The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
  • 10. INTERFACES IN JAVAX.SERVLET PACKAGE  Servlet  ServletRequest  ServletResponse  RequestDispatcher  ServletConfig  ServletContext  SingleThreadModel  Filter  FilterConfig  FilterChain  ServletRequestListener  ServletRequestAttributeListener  ServletContextListener  ServletContextAttributeListener
  • 11. CLASSES IN JAVAX.SERVLET PACKAGE  GenericServlet  ServletInputStream  ServletOutputStream  ServletRequestWrapper  ServletResponseWrapper  ServletRequestEvent  ServletContextEvent  ServletRequestAttributeEvent  ServletContextAttributeEvent  ServletException  UnavailableException
  • 12. INTERFACES IN JAVAX.SERVLET.HTTP PACKAGE  HttpServletRequest  HttpServletResponse  HttpSession  HttpSessionListener  HttpSessionAttributeListener  HttpSessionBindingListener  HttpSessionActivationListener  HttpSessionContext (deprecated now)
  • 13. CLASSES IN JAVAX.SERVLET.HTTP PACKAGE  HttpServlet  Cookie  HttpServletRequestWrapper  HttpServletResponseWrapper  HttpSessionEvent  HttpSessionBindingEvent  HttpUtils (deprecated now)
  • 14. SERVLET INTERFACE  Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).  It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
  • 15. METHODS OF SERVLET INTERFACE  There are 5 methods in Servlet interface.  The init, service and destroy are the life cycle methods of servlet.  These are invoked by the web container.
  • 16. METHODS OF SERVLET INTERFACE Method Description public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
  • 17. GENERICSERVLET CLASS  GenericServlet class implements Servlet, ServletConfig and Serializable interf aces.  It provides the implementation of all the methods of these interfaces except the service method.  GenericServlet class can handle any type of request so it is protocol-independent.
  • 18. METHODS OF GENERICSERVLET CLASS  public void init(ServletConfig config) is used to initialize the servlet.  public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.  public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.  public ServletConfig getServletConfig() returns the object of ServletConfig.  public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
  • 19. METHODS OF GENERICSERVLET CLASS  public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)  public ServletContext getServletContext() returns the object of ServletContext.  public String getInitParameter(String name) returns the parameter value for the given parameter name.  public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.  public String getServletName() returns the name of the servlet object.  public void log(String msg) writes the given message in the servlet log file.  public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace.
  • 20. SERVLET EXAMPLE BY INHERITING THE GENERICSERVLET CLASS import java.io.*; import javax.servlet.*; public class First extends GenericServlet{ public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello generic servlet</b>"); out.print("</body></html>"); } }
  • 21. HTTPSERVLET CLASS  The HttpServlet class extends the GenericServlet class and implements Serializable interface.  It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
  • 22. METHODS OF HTTPSERVLET CLASS  public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.  protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.  protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.  protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.
  • 23. METHODS OF HTTPSERVLET CLASS  protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.  protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.  protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.
  • 24. METHODS OF HTTPSERVLET CLASS  protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.  protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.  protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.
  • 25. SERVLETS - CLIENT HTTP REQUEST 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. An HTTP client sends an HTTP request to a server in the form of a request message which includes following format  A Request-line  Zero or more header (General|Request|Entity) fields followed by CRLF  An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields  Optionally a message-body of HTTP request.
  • 26. REQUEST-LINE  The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters.  Request-Line = Method SP Request-URI SP HTTP- Version CRLF
  • 27. REQUEST METHOD GET The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. HEAD Same as GET, but it transfers the status line and the header section only. POST A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms. PUT Replaces all the current representations of the target resource with the uploaded content. DELETE Removes all the current representations of the target resource given by URI. CONNECT Establishes a tunnel to the server identified by a given URI. OPTIONS Describe the communication options for the target resource. TRACE Performs a message loop back test along with the path to the target resource.
  • 28. REQUEST-URI  The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Request-URI = "*" | absoluteURI | abs_path | authority S.N. Method and Description 1 The asterisk * is used when an HTTP request does not apply to a particular resource, but to the server itself, and is only allowed when the method used does not necessarily apply to a resource. For example:OPTIONS * HTTP/1.1 2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is requested to forward the request or service from a valid cache, and return the response. For example: GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1 3 The most common form of Request-URI is that used to identify a resource on an origin server or gateway. For example, a client wishing to retrieve a resource directly from the origin server would create a TCP connection to port 80 of the host "www.w3.org" and send the following lines: GET /pub/WWW/TheProject.html HTTP/1.1 Host: www.w3.org Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).
  • 29. HEADER & DESCRIPTION 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.
  • 30. HEADER & DESCRIPTION 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.
  • 31. HEADER & DESCRIPTION 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.
  • 32. HEADER & DESCRIPTION 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.
  • 33. METHODS TO READ HTTP HEADER Cookie[] getCookies()  Returns an array containing all of the Cookie objects the client sent with this request. Enumeration getAttributeNames()  Returns an Enumeration containing the names of the attributes available to this request. Enumeration getHeaderNames()  Returns an enumeration of all the header names this request contains. Enumeration getParameterNames()  Returns an Enumeration of String objects containing the names of the parameters contained in this request
  • 34. METHODS TO READ HTTP HEADER HttpSession getSession()  Returns the current session associated with this request, or if the request does not have a session, creates one. HttpSession getSession(boolean create)  Returns the current HttpSession associated with this request or, if if there is no current session and value of create is true, returns a new session. Locale getLocale()  Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. Object getAttribute(String name)  Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. ServletInputStream getInputStream()  Retrieves the body of the request as binary data using a ServletInputStream.
  • 35. METHODS TO READ HTTP HEADER String getAuthType()  Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected. String getCharacterEncoding()  Returns the name of the character encoding used in the body of this request. String getContentType()  Returns the MIME type of the body of the request, or null if the type is not known. String getContextPath()  Returns the portion of the request URI that indicates the context of the request. String getHeader(String name)  Returns the value of the specified request header as a String.
  • 36. METHODS TO READ HTTP HEADER String getMethod()  Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. String getParameter(String name)  Returns the value of a request parameter as a String, or null if the parameter does not exist. String getPathInfo()  Returns any extra path information associated with the URL the client sent when it made this request String getProtocol()  Returns the name and version of the protocol the request. String getQueryString()  Returns the query string that is contained in the request URL after the path.
  • 37. METHODS TO READ HTTP HEADER String getRemoteAddr()  Returns the Internet Protocol (IP) address of the client that sent the request. String getRemoteHost()  Returns the fully qualified name of the client that sent the request. String getRemoteUser()  Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. String getRequestURI()  Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
  • 38. METHODS TO READ HTTP HEADER String getRequestedSessionId()  Returns the session ID specified by the client. String getServletPath()  Returns the part of this request's URL that calls the JSP. String[] getParameterValues(String name)  Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. boolean isSecure()  Returns a Boolean indicating whether this request was made using a secure channel, such as HTTPS.
  • 39. METHODS TO READ HTTP HEADER int getContentLength()  Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. int getIntHeader(String name)  Returns the value of the specified request header as an int. int getServerPort()  Returns the port number on which this request was received.
  • 40. HTTP HEADER REQUEST EXAMPLE  Use getHeaderNames() method of HttpServletRequest to read the HTTP header information.  This method returns an Enumeration that contains the header information associated with the current HTTP request.  Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name
  • 41. HTTP HEADER REQUEST EXAMPLE // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class DisplayHeader extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "HTTP Header Request Example"; String docType = "<!doctype html public "-//w3c//dtd html 4.0 " + "transitional//en">n";
  • 42. HTTP HEADER REQUEST EXAMPLE out.println(docType + "<html>n" + "<head><title>" + title + "</title></head>n"+ "<body bgcolor = "#f0f0f0">n" + "<h1 align = "center">" + title + "</h1>n" + "<table width = "100%" border = "1" align = "center">n" + "<tr bgcolor = "#949494">n" + "<th>Header Name</th><th>Header Value(s)</th>n"+ "</tr>n" );
  • 43. HTTP HEADER REQUEST EXAMPLE Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("<tr><td>" + paramName + "</td>n"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>n"); } out.println("</table>n</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
  • 44. Header Name Header Value(s) accept */* accept-language en-us user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8) accept-encoding gzip, deflate host localhost:8080 connection Keep-Alive cache-control no-cache
  • 45. EXAMPLES OF REQUEST MESSAGE GET /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive
  • 46. SERVLETS - SERVER HTTP RESPONSE  An initial status line + CRLF ( Carriage Return + Line Feed i.e. New Line )  Zero or more header lines + CRLF  A blank line, i.e., a CRLF  An optional message body like file, query data or query output.
  • 47. FOR EXAMPLE, A SERVER RESPONSE HEADER HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
  • 48. HTTP RESPONSE STATUS CODES  HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:  Informational responses (100–199)  Successful responses (200–299)  Redirects (300–399)  Client errors (400–499)  Server errors (500–599)
  • 49. HTTP RESPONSE HEADERS S.No. Header & Description 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, private or 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 nocache 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.
  • 50. HTTP RESPONSE HEADERS S.No. Header & Description 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.
  • 51. HTTP RESPONSE HEADERS S.No. Header & Description 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.