Unit-3 J2EE
Unit-3 J2EE
Introduction to Servlet
Servlets have access to the entire family of Java APIs, including the JDBC API to
access enterprise databases.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
Read the explicit data sent by the clients (browsers). This includes an HTML form on
a Web page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands.
Process the data and generate the results. This process may require talking to a
database, executing an RMI call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document
can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications.
Java servlets have been created and compiled just like any other Java class.
After you install the servlet packages and add them to your computer's Classpath,
you can compile servlets with the JDK's Java compiler or any other current compiler.
Servlet Lifecycle
A servlet life cycle can be defined as the entire process from its creation till the
destruction.
The following are the paths followed by a servlet.
a. The servlet is initialized by calling the init() method.
b. The servlet calls service() method to process a client's request.
c. The servlet is terminated by calling the destroy() method.
d. Finally, servlet is garbage collected by the garbage collector of the JVM.
A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
Architecture Diagram
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
A Servlet is loaded by the Servlet container the first time the Servlet is requested.
The Servlet then is forwarded the user request, processes it, and returns the response to the Servlet
container, which in turn sends the response back to the user.
After that, the Servlet stays in memory waiting for other requests—it will not be unloaded from
the memory unless the Servlet container detects a shortage of memory.
Each time the Servlet is requested, however, the Servlet container compares the timestamp of the
loaded servlet with the Servlet class file.
If the class file timestamp is more recent, the Servlet is reloaded into memory.
This way, we don’t need to restart the Servlet container every time we update our Servlet.
The whole process is shown in Figure 3 below.
Figure 3: Servlet detailed architecture
Steps :—
1. The client (web browser) makes a request via HTTP protocol.
2. The web Server receives the request and forwards it to the servlet.
3. The servlet will receive the request and perform some processing (database call).
4. The servlet will return a response back to the web Server.
5. The web server will forward the response to the client in terms of HTML output.
GenericServlet class
It provides the implementation of all the methods of these interfaces except the service method.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is
being destroyed.
5. public String getServletInfo() returns information about servlet such as writer, copyright, version
etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to
call super.init(config)
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file
and a stack trace.
Example
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
Whenever we want to send an input to a servlet that input must be passed through
html form.
An html form is nothing but various controls are inherited to develop an application.
Every form will accept client data and it must send to a servlet which resides in server
side.
Since html is a static language which cannot validate the client data.
Hence, in real time applications client data will be accepted with the help of html tags
by developing form and every form must call a servlet.
Steps for DEVELOPING a FORM:
<html>
<title>About Personal Data</title>
<head><center><h3>Personal Information</h3></center></head>
<body bgcolor="#D8BFD8">
<form name="persdata" action="./DataSer">
<center>
<table bgcolor="#D2B48C" border="1">
<tr>
<th>Enter ur name : </th>
<td><input type="text" name="persdata_eurn" value=""></td>
</tr>
<tr>
<th>Enter ur course : </th>
<td><input type="text" name="persdata_eurc" value=""></td>
</tr>
<tr>
<td align="center"><input type="button" name="persdata_send"
value="Send"></td>
<td align="center"><input type="reset" name="persdata_clear"
value="Clear"></td>
</tr>
</table>
</center>
</form>
</body>
</html>
When a browser requests for a web page, it sends lot of information to the web
server which cannot be read directly because this information travel as a part of
header of HTTP request.
Following is the important header information which comes from browser side:
Accept
1
This header specifies the MIME types that the browser or other clients can handle.
2
Accept-Charset
This header specifies the character sets the browser can use to display the information.
Accept-Encoding
3 This header specifies the types of encodings that the browser knows how to handle.
Accept-Language
4
This header specifies the client's preferred languages in case the servlet can produce results
in more than one language.
Authorization
5
This header is used by clients to identify them when accessing password-protected Web
pages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
6 Persistent connections permit the client or other browser to retrieve multiple files with a
single request.
Content-Length
7
This header is applicable only to POST requests and gives the size of the POST data in
bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
Host
9
This header specifies the host and port as given in the original URL.
If-Modified-Since
This header indicates that the client wants the page only if it has been changed after the
10 specified date.
The server sends a code, 304 which means Not Modified header if no newer result is
available.
If-Unmodified-Since
11
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
12
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
13
This header identifies the browser or other client making the request and can be used to
return different content to different types of browsers.
There are following methods which can be used to read HTTP header in your servlet
program.
These methods are available with HttpServletRequest object
Sr.No Method & Description
.
Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this request.
Enumeration getAttributeNames()
2
Returns an Enumeration containing the names of the attributes available to this request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4
Returns an Enumeration of String objects containing the names of the parameters
contained in this request
HttpSession getSession()
5
Returns the current session associated with this request, or if the request does not have a
session, creates one.
7
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-
Language header.
Object getAttribute(String name)
8
Returns the value of the named attribute as an Object, or null if no attribute of the given
name exists.
ServletInputStream getInputStream()
9
Retrieves the body of the request as binary data using a ServletInputStream.
String getAuthType()
10
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()
11
Returns the name of the character encoding used in the body of this request.
String getContentType()
12
Returns the MIME type of the body of the request, or null if the type is not known.
String getContextPath()
13
Returns the portion of the request URI that indicates the context of the request.
String getMethod()
15
Returns the name of the HTTP method with which this request was made, for example,
GET, POST, or PUT.
16
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
String getPathInfo()
17
Returns any extra path information associated with the URL the client sent when it made
this request
String getProtocol()
18
Returns the name and version of the protocol of the request.
String getQueryString()
19
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
20
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.
String getRemoteUser()
22
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()
23
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.
String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getServletPath()
25
Returns the part of this request's URL that calls the JSP.
boolean isSecure()
27
Returns a Boolean indicating whether this request was made using a secure channel, such
as HTTPS.
int getContentLength()
28
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 getServerPort()
30
Returns the port number on which this request was received.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class DisplayHeader extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
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";
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" );
Output:
HTTP Header Request Example
Accept */*
accept-language en-us
Host localhost:8080
Connection Keep-Alive
cache-control no-cache
When a Web server responds to an HTTP request, the response typically consists of a
status line, some response headers, a blank line, and the document.
A typical response looks like this −
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status
code (200 in the example), and a very short message corresponding to the status code
(OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go
back to the browser from web server side:
Allow
1
This header specifies the request methods (GET, POST, etc.) that the server supports.
Cache-Control
This header specifies the circumstances in which the response document can safely be
cached.
2
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.
Content-Disposition
4
This header lets you request that the browser ask the user to save the response to disk in a
file of the given name.
Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.
Content-Language
6 This header signifies the language in which the document is written.
Content-Length
7
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.
Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension) type of the response
document.
Expires
9
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.
Location
This header should be included with all responses that have a status code in the 300s.
11
This notifies the browser of the document address.
The browser automatically reconnects to this location and retrieves the new document.
Refresh
12 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.
Retry-After
13
This header can be used in conjunction with a 503 (Service Unavailable) response to tell
the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
There are following methods which can be used to set HTTP response header in your
servlet program.
These methods are available with HttpServletResponse object.
boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.
void resetBuffer()
11
Clears the content of the underlying buffer in the response without clearing headers or
status code.
18
void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been
committed yet.
teger value
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Refresh extends HttpServlet
{
Now calling the above servlet would display current system time after every 5
seconds as follows:
HTTP header fields provide required information about the request or response, or
about the object sent in the message body.
There are four types of HTTP message headers:
General-header:
These header fields have general applicability for both request and
response messages.
Client Request-header:
Server Response-header:
Entity-header:
These header fields define Meta information about the entity-body or,
if no body is present, about the resource identified by the request.
1. General Headers
a. Cache-Control
Cache-Control : cache-request-directive|cache-response-directive
o A HTTP client or server can use the Cache-control general header to specify
parameters for the cache or to request certain kinds of documents from the
cache.
o The caching directives are specified in a comma-separated list.
o For example:
Cache-control: no-cache
The following table lists the important cache request directives that can be used by the client
in its HTTP request:
1 no-cache
A cache must not use the response to satisfy a subsequent request without successful revalidation
with the origin server.
2 no-store
The cache should not store anything about the client request or server response.
3 max-age = seconds
Indicates that the client is willing to accept a response whose age is not greater than the
specified time in seconds.
4 max-stale [ = seconds ]
Indicates that the client is willing to accept a response that has exceeded its expiration time.
If seconds are given, it must not be expired by more than that time.
5 min-fresh = seconds
Indicates that the client is willing to accept a response whose freshness lifetime is not less
than its current age plus the specified time in seconds.
6 no-transform
7 only-if-cached
The cache can send a document only if it is in the cache, and should not contact the origin-
server to see if a newer copy exists.
The following important cache response directives that can be used by the server in its
HTTP response:
S.N Cache Response Directive and Description
.
1 public
2 private
Indicates that all or part of the response message is intended for a single user and must not be
cached by a shared cache.
3 no-cache
A cache must not use the response to satisfy a subsequent request without successful re-
validation with the origin server.
4 no-store
The cache should not store anything about the client request or server response.
5 no-transform
6 must-revalidate
The cache must verify the status of the stale documents before using it and expired ones
should not be used.
7 proxy-revalidate
The proxy-revalidate directive has the same meaning as the must- revalidate directive, except
that it does not apply to non-shared user agent caches.
8 max-age = seconds
Indicates that the client is willing to accept a response whose age is not greater than the
specified time in seconds.
9 s-maxage = seconds
The maximum age specified by this directive overrides the maximum age specified by either
the max-age directive or the Expires header.
b. Connection
The Connection general-header field allows the sender to specify options that are
desired for that particular connection and must not be communicated by proxies over
further connections.
Following is the simple syntax for using connection header:
Connection : "Connection"
HTTP/1.1 defines the "close" connection option for the sender to signal that the
connection will be closed after completion of the response.
For example: Connection: close
By default, HTTP 1.1 uses persistent connections, where the connection does not
automatically close after a transaction.
HTTP 1.0 does not have persistent connections by default.
If a 1.0 client wishes to use persistent connections, it uses the keep-alive parameter
as follows:
Connection: keep-alive
c. Date
All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT),
without exception.
HTTP applications are allowed to use any of the following three representations of
date/time stamps:
Sun, 06 Nov 1994 08:49:37 GMT; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994; ANSI C's asctime() format
Here the first format is the most preferred one.
d. Pragma
e. Trailer
The Trailer general field value indicates that the given set of header fields is present
in the trailer of a message encoded with chunked transfer-coding.
Following is the syntax of Trailer header field:
Trailer : field-name
Message header fields listed in the Trailer header field must not include the
following header fields:
Transfer-Encoding
Content-Length
Trailer
f. Transfer-Encoding
Transfer-Encoding: chunked
The Upgrade header field is intended to provide a simple mechanism for transition
from HTTP/1.1 to some other, incompatible protocol.
h. Via
The Via general-header must be used by gateways and proxies to indicate the
intermediate protocols and recipients.
For example, a request message could be sent from an HTTP/1.0 user agent to an
internal proxy code-named "fred", which uses HTTP/1.1 to forward the request to
a public proxy at nowhere.com, which completes the request by forwarding it to the
origin server at www.ics.uci.edu.
The request received by www.ics.uci.edu would then have the following Via header
field:
i. Warning
The Warning general-header is used to carry additional information about the status
or transformation of a message which might not be reflected in the message.
A response may carry more than one Warning header.
a. Accept
The Accept request-header field can be used to specify certain media types which are
acceptable for the response.
The general syntax is as follows:
This would be interpreted as text/html and text/x-c and are the preferred media
types, but if they do not exist, then send the text/x-dvi entity, and if that does not
exist, send the text/plain entity.
b. Accept-Charset
The Accept-Charset request-header field can be used to indicate what character sets
is acceptable for the response.
Following is the general syntax:
Multiple character sets can be listed separated by commas and the optional qvalue
represents an acceptable quality level for nonpreferred character sets on a scale of 0
to 1.
Following is an example:
The special value "*", if present in the Accept-Charset field, matches every
character set and if no Accept-Charset header is present, the default is that any
character set is acceptable.
c. Accept-Encoding
d. Accept-Language
The Accept-Language request-header field is similar to Accept, but restricts the set
of natural languages that are preferred as a response to the request.
The general syntax is:
Multiple languages can be listed separated by commas and the optional qvalue
represents an acceptable quality level for non-preferred languages on a scale of 0 to
1.
Following is an example:
e. Authorization
Authorization : credentials
The HTTP/1.0 specification defines the BASIC authorization scheme, where the
authorization parameter is the string of username:password encoded in base 64.
Following is an example:
The value decodes into is guest:guest123 where guest is user ID and guest123 is the
password.
f. Cookie
Cookie: name=value
g. Expect
The Expect request-header field is used to indicate that a particular set of server
behaviours is required by the client.
The general syntax is:
h. From
The From request-header field contains an Internet e-mail address for the human user
who controls the requesting user agent.
Following is a simple example:
From: [email protected]
This header field may be used for logging purposes and as a means for identifying
the source of invalid or unwanted requests.
i. Host
The Host request-header field is used to specify the Internet host and the port number
of the resource being requested.
The general syntax is:
A host without any trailing port information implies the default port, which is 80.
j. If-Match
If-Match : entity-tag
An asterisk (*) matches any entity, and the transaction continues only if the entity
exists.
Following are possible examples:
If-Match: "xyzzy"
If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz"
If-Match: *
If none of the entity tags match, or if "*" is given and no current entity exists, the
server must not perform the requested method, and must return a 412 (Precondition
Failed) response.
a. Accept-Ranges
The Accept-Ranges response-header field allows the server to indicate its acceptance
of range requests for a resource.
The general syntax is:
Accept-Ranges: bytes
Servers that do not accept any kind of range request for a resource may send:
Accept-Ranges: none
b. Age
The Age response-header field conveys the sender's estimate of the amount of time
since the response was generated at the origin server.
The general syntax is:
Age : delta-seconds
Following is a simple example:
Age: 1030
An HTTP/1.1 server that includes a cache must include an Age header field in every
response generated from its own cache.
c. ETag
The ETag response-header field provides the current value of the entity tag for the
requested variant.
The general syntax is:
ETag : entity-tag
ETag: "xyzzy"
ETag: W/"xyzzy"
ETag: ""
d. Location
Location : absoluteURI
Location: http://www.abc.org/http/index.htm
e. Proxy-Authenticate
Proxy-Authenticate : challenge
f. Retry-After
The Retry-After response-header field can be used with a 503 (Service Unavailable)
response to indicate how long the service is expected to be unavailable to the
requesting client.
The general syntax is:
Examples:
4. Entity Headers
a. Allow
The Allow entity-header field lists the set of methods supported by the resource
identified by the Request-URI.
The general syntax is:
Allow : Method
b. Content-Encoding
Content-Encoding : content-coding
Content-Encoding: gzip
Content-Language : language-tag
Multiple languages may be listed for content that is intended for multiple audiences.
Following is a simple example:
Content-Language: mi, en
d. Content-Length
Content-Length : DIGITS
Content-Length: 3495
e. Content-Location
Content-Location: http://www.abc.org/http/index.htm
The value of Content-Location also defines the base URI for the entity.
HTTP - Status Codes
The Status-Code element in a server response is a 3-digit integer where the first digit
of the Status-Code defines the class of response and the last two digits do not have
any categorization role.
There are 5 values for the first digit:
1 1xx: Informational
It means the request has been received and the process is continuing.
2 2xx: Success
3 3xx: Redirection
1. 1xx: Information
Message Description
100 Continue Only a part of the request has been received by the server, but as long as it has not been
rejected, the client should continue with the request.
2xx: Successful
Message Description
202 Accepted The request is accepted for processing, but the processing is not complete.
203 Non-authoritative The information in the entity header is from a local or third-party copy, not from
Information the original server.
204 No Content A status code and a header are given in the response, but there is no entity-body in
the reply.
205 Reset Content The browser should clear the form used for this transaction for additional input.
206 Partial Content The server is returning partial data of the size requested. The server must specify
the range included in the response with the Content-Range header.
3xx: Redirection
Message Description
300 Multiple A link list. The user can select a link and go to that location. Maximum five addresses .
Choices
301 Moved The requested page has moved to a new url.
Permanently
302 Found The requested page has moved temporarily to a new url.
303 See Other The requested page can be found under a different url.
304 Not Modified This is the response code to an If-Modified-Since or If-None-Match header, where the
URL has not been modified since the specified date.
305 Use Proxy The requested URL must be accessed through the proxy mentioned in
the Location header.
306 Unused This code was used in a previous version. It is no longer used, but the code is reserved.
307 Temporary The requested page has moved temporarily to a new url.
Redirect
Message Description
400 Bad Request The server did not understand the request.
405 Method Not The method specified in the request is not allowed.
Allowed
406 Not Acceptable The server can only generate a response that is not accepted by the client.
407 Proxy You must authenticate with a proxy server before this request can be served.
Authentication Required
408 Request Timeout The request took longer than the server was prepared to wait.
411 Length Required The "Content-Length" is not defined. The server will not accept the request
without it.
412 Precondition Failed The pre-condition given in the request evaluated to false by the server.
413 Request Entity Too The server will not accept the request, because the request entity is too large.
Large
414 Request-url Too The server will not accept the request, because the url is too long. Occurs when
Long you convert a "post" request to a "get" request with long query information.
415 Unsupported Media The server will not accept the request, because the media type is not supported.
Type
416 Requested Range The requested byte range is not available and is out of bounds.
Not Satisfiable
417 Expectation Failed The expectation given in an Expect request-header field could not be met by this
server.
Message Description
500 Internal Server Error The request was not completed. The server met an unexpected condition.
501 Not Implemented The request was not completed. The server did not support the functionality
required.
502 Bad Gateway The request was not completed. The server received an invalid response from
the upstream server.
503 Service Unavailable The request was not completed. The server is temporarily overloading or
down.
505 HTTP Version Not The server does not support the "http protocol" version.
Supported
HTTP - Responses
After receiving and interpreting a request message, a server responds with an HTTP
response message:
A Status-line
Zero or more header (General|Response|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
Message Status-Line
A Status-Line consists of the protocol version followed by a numeric status code and
its associated textual phrase.
The elements are separated by space SP characters.
HTTP Version
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1
Status Code
The Status-Code element is a 3-digit integer where first digit of the Status-Code
defines the class of response and the last two digits do not have any categorization
role.
There are 5 values for the first digit:
1 1xx: Informational
It means the request was received and the process is continuing.
2 2xx: Success
3 3xx: Redirection
HTTP status codes are extensible and HTTP applications are not required to
understand the meaning of all registered status codes.
The response-header fields allow the server to pass additional information about the
response which cannot be placed in the Status- Line.
These header fields give information about the server and about further access to the
resource identified by the Request-URI.
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The following example shows an HTTP response message displaying error condition
when the web server could not find the requested page:
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
After that if request is sent by the user, cookie is added with request by default.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
Persistent cookie
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
Constructor Description
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after creation.
They are:
object.
Creating a Cookie
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Deleting a Cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
To get Cookies
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}
In this example, we are storing the name of the user in the cookie object and accessing
it in another servlet.
So if you access it from too many browsers with different values, you will get the
different value.
index.html
<form action="FirstServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//-creating submit button
out.print("<form action='SecondServlet'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);} } }
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Each time user requests to the server, server treats the request as the new
request.
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
In such case, we store the information in the hidden field and get it from
another servlet.
Here, uname is the hidden field name and Vishal is the hidden field
value.
Example:
index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='SecondServlet'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
} }
URL Rewriting
url?name1=value1&name2=value2&??
When the user clicks the hyperlink, the parameter name/value pairs will
be passed to the server.
Example
index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<a href='SecondServlet?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
HttpSession interface
An object of HttpSession can be used to perform two tasks:
1. bind objects
2. View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
Example
index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='SecondServlet'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}