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.
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";
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.