SlideShare a Scribd company logo
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

Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Java web application development
Java web application developmentJava web application development
Java web application development
RitikRathaur
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
Java Collections
Java  Collections Java  Collections
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
Guddu gupta
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
DrSonali Vyas
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Peter R. Egli
 
Basic Graphics in Java
Basic Graphics in JavaBasic Graphics in Java
Basic Graphics in Java
Prakash Kumar
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
Venkateswara Rao N
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Web controls
Web controlsWeb controls
Web controls
Sarthak Varshney
 
servlet in java
servlet in javaservlet in java
servlet in java
sowfi
 

What's hot (20)

Java beans
Java beansJava beans
Java beans
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Basic Graphics in Java
Basic Graphics in JavaBasic Graphics in Java
Basic Graphics in Java
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web controls
Web controlsWeb controls
Web controls
 
servlet in java
servlet in javaservlet in java
servlet in java
 

Similar to Java servlets

Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
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
PRIYADARSINISK
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Servlets
ServletsServlets
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
bharathiv53
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
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
Tushar B Kute
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
Servlet viva questions
Servlet viva questionsServlet viva questions
Servlet viva questions
Vipul Naik
 

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
 
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
 
Servlets
ServletsServlets
Servlets
 
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

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

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.