0% found this document useful (0 votes)
9 views159 pages

Unit III Servlets

This document provides an overview of servlets, including their structure, lifecycle, and methods for handling client requests and generating responses. It covers key concepts such as the servlet lifecycle methods (init, service, destroy), handling form data, and reading HTTP request headers. Additionally, it discusses the SingleThreadModel interface and various request headers used in HTTP communication.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views159 pages

Unit III Servlets

This document provides an overview of servlets, including their structure, lifecycle, and methods for handling client requests and generating responses. It covers key concepts such as the servlet lifecycle methods (init, service, destroy), handling form data, and reading HTTP request headers. Additionally, it discusses the SingleThreadModel interface and various request headers used in HTTP communication.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 159

Servlets

Unit – III
Contents of the Unit
• Servlet Structure, Lifecycle, Single Thread model interface, Handling
Client Request: Form Data, Handling Client Request: HTTP Request
Headers. Generating server Response: HTTP Status codes, Generating
server Response: HTTP Response Headers, Handling Cookies
Basic Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Use "request" to read incoming HTTP headers
// (e.g. cookies) and HTML form data (e.g. data the user
// entered and submitted).
// Use "response" to specify the HTTP response status
// code and headers (e.g. the content type, cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
The Servlet Life Cycle
• init method: put one-time setup code.
• service method: each user request results in a thread that calls the
service method of the previously created instance.
• Multiple concurrent requests normally result in multiple threads
calling service simultaneously
• The service method then calls doGet, doPost, or another doXxx
method
• destroy method: when the serverdecides to unload a servlet
The init Method
• Is called when the servlet is first created
• Is not called again for each user request.
• Used for one-time initializations.
• Created when a user first invokes a URL corresponding to the servlet
or when the server is first started.
• Two versions of init:
• One that takes no arguments.
• one that takes a ServletConfig object as an argument.
No argument init
• Used when the servlet does not need to read any settings that vary
from server to server.
• General form
public void init() throws ServletException {
// Initialization code...
}
init with ServletConfig object as an
argument.
• Used when the servlet needs to read server-specific settings before it can complete the
initialization.
• For example, the servlet might need to know about database settings, password files, server-
specific performance parameters, hit count files, or serialized cookie
• General form
public void init(ServletConfig config) throws ServletException
{
super.init(config);
// Initialization code...
}
• This method takes a Servlet-Config as an argument.
• ServletConfig has a getInitParameter method, look up initialization parameters associated with
the servlet.
• The method body must have a call to super.init.
The service Method
• Each time the server receives a request for a servlet, the server spawns a new
thread and calls service.
• The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc., as appropriate.
• To handle both POST and GET requests identically override service directly as
below (but not a good idea)
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet Code
}
doPost call doGet
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Servlet Code
}
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request, response);
}
The doGet, doPost, and doXxx
Methods
• Ninety-nine percent of the time, you only care about GET and/or
POST requests override doGet and/or doPost.
• Override doDelete for DELETE requests, doPut for PUT, doOptions for
OPTIONS, and doTrace for TRACE.
• Automatic support for OPTIONS and TRACE.
The SingleThreadModel
Interface
• A single instance of the servlet is created
• A new thread for each user request, with multiple simultaneous threads running if a new
request comes in while a previous request is still executing.
• The doGet and doPost methods must be careful to synchronize access.
• To prevent this multithreaded access implement the SingleThreadModel interface
public class YourServlet extends HttpServlet
implements SingleThreadModel {
...
}
• Either queues up all the requests and passing them one at a time to a single
servlet instance, or by creating a pool of multiple instances, each of which
handles one request at a time.
The destroy Method
• Removes a previously loaded servlet instance.
• This is explicitly asked by the server administrator or the servlet is idle
for a long time.
• Used to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup
activities.
• This may possibly cause the Web server to crash.

Reading Form Data from
Servlets
• HttpServletRequest class has two methods
• getParameter(String);
• Returns a single string
• getParameterValues();
• Returns an array of strings
• To the getParameter method supply the case-sensitive parameter name as an argument.
• Use getParameter for both get and post methods, the server handles it appropriately behind the scenes.
• The return value is a String corresponding to the URL-decoded value of the first occurrence of that parameter
name.
• An empty String is returned if the parameter exists but has no value, and null is returned if there was no such
parameter.
• If the parameter could potentially have more than one value, call getParameterValues instead of
getParameter
• The return value of getParameterValues is null for nonexistent parameter names and is a one-element array
when the parameter has only a single value.
• Parameter names are case sensitive
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
<FORM ACTION="/servlet/coreservlets.ThreeParams">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY>
</HTML>
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" + " <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" + " <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" + " <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" + "</UL>\n" +
"</BODY></HTML>");
}
}
Reading All Parameters
Reading Request Headers from
Servlets
• Request Headers:
• Accept,
• Accept-Encoding,
• Connection,
• Cookie,
• Host,
• Referer, and
• User-Agent
Example of Request Header
GET /search?keywords=servlets+jsp HTTP/1.1
Accept: image/gif, image/jpg, */*
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id456578
Host: www.somebookstore.com
Referer: http://www.somebookstore.com/findbooks.html
User-Agent: Mozilla/4.7 [en] (Win98; U)
Getting Request Headers
• The getHeader method of HttpServletRequest returns a String if the
specified header was supplied on this request is available, null
otherwise.
• Header names are not case sensitive.
• getHeader is the general-purpose way to read incoming headers
Specific Header Methods In
Httpservletrequest
• getCookies
• The getCookies method returns the contents of the Cookie header, parsed
and stored in an array of Cookie objects.
• getAuthType and getRemoteUser
• The getAuthType and getRemoteUser methods break the Authorization
header into its component pieces.
• getContentLength
• The getContentLength method returns the value of the Content-Length
header (as an int).
Special Access Methods In
Httpservletrequest cont..
• getContentType
• The getContentType method returns the value of the Content-Type header (as
a String).
• getDateHeader and getIntHeader
• The getDateHeader and getIntHeader methods read the specified header and
then convert them to Date and int values, respectively.
• getHeaderNames
• Rather than looking up one particular header, you can use the
getHeaderNames method to get an Enumeration of all header names
received on this particular request.
Special Access Methods In
Httpservletrequest cont..
• getHeaders
• In most cases, each header name appears only once in the request.
Occasionally, however, a header can appear multiple times, with each
occurrence listing a separate value. Accept-Language is one such example. If a
header name is repeated in the request, version 2.1 servlets cannot access
the later values without reading the raw input stream, since getHeader
returns the value of the first occurrence of the header only. In version 2.2,
however, getHeaders returns an Enumeration of the values of all occurrences
of the header.
Additional methods
• getMethod
• The getMethod method returns the main request method (normally GET or
POST, but things like HEAD, PUT, and DELETE are possible).
• • getRequestURI
• The getRequestURI method returns the part of the URL that comes after the host
and port but before the form data. For example, for a URL of http
://randomhost.com/servlet/search.BookSearch, getRequestURI would return
/servlet/search.BookSearch.
• getProtocol
• The getProtocol method returns the third part of the request line, which is
generally HTTP/1.0 or HTTP/1.1. Servlets should usually check getProtocol before
specifying response headers.
Reading All Headers
HTTP 1.1 Request Headers
• To perform a number of optimizations and to provide a number of
features not otherwise possible.
• HTTP 1.1 supports a superset of the headers permitted in HTTP 1.0.
• HTTP 1.1 specification - RFC 2616.
Accept
• Specifies the MIME types that the browser or other client can handle.
• Example
• images in PNG format have some compression advantages over those in GIF.
• only a few browsers support PNG.
• a servlet could call request.getHeader("Accept"), check for image/png, and if
it finds it, use xxx.png filenames in all the IMG elements it generates.
Otherwise it would just use xxx.gif.
Accept-Charset
• This header indicates the character sets (e.g., ISO-8859-1) the
browser can use.
Accept-Encoding
• Designates the types of encodings that the client knows how to handle.
• The server is free to encode the page by using the format specified by sending
the Content-Encoding response header.
• This encoding type is completely distinct from the MIME type of the actual
document.
• This encoding is reversed before the browser decides what to do with the
content.
• Values of gzip or compress are the two standard possibilities.
• Compressing pages before returning them is a very valuable service because
the decoding time is likely to be small compared to the savings in
transmission time.
Accept-Language
• Specifies the client’s preferred languages.
• The standard language codes are en, en-us, da, etc.
• See RFC 1766 for details.
Authorization
• This header is used by clients to identify themselves when accessing
password-protected Web pages
Cache-Control
• Used by the client to specify a number of options for how pages
should be cached by proxy servers.
• Usually ignored by servlets, but the Cache-Control response header
can be valuable to indicate that a page is constantly changing and
shouldn’t be cached.
Connection
• This header tells whether or not the client can handle persistent HTTP connections.
• These let the client or other browser retrieve multiple files (e.g., an HTML file and
several associated images) with a single socket connection, saving the overhead of
negotiating several independent connections.
• With an HTTP 1.1 request, persistent connections are the default, and the client must
specify a value of close for this header to use old-style connections.
• In HTTP 1.0, a value of keep-alive means that persistent connections should be used.
• The server invokes the servlet only after the server has already read the HTTP
request.
• Servlets need help from the server to handle persistent connections.
• Servlet’s job is just to make it possible for the server to use persistent connections,
which is done by sending a Content-Length response header
Content-Length
• This header is only applicable to POST requests and gives the size of
the POST data in bytes.
• Use request.getContentLength().
Content-Type
• Usually used in responses from the server.
• Part of client requests when the client attaches a document as the
POST data or when making PUT requests.
• access this header using request. getContentType().
Cookie
• Used to return cookies to servers that previously sent them to the
browser.
• Technically, Cookie is not part of HTTP 1.1.
• It was originally a Netscape extension but is now very widely
supported, including in both Netscape and Internet Explorer.
Expect
• This rarely used header lets the client tell the server what kinds of
behaviors it expects.
• The one standard value for this header, 100-continue, is sent by a
browser that will be sending an attached document and wants to
know if the server will accept it.
• The server should send a status code of either 100 (Continue) or 417
(Expectation Failed) in such a case.
From
• This header gives the e-mail address of the person responsible for the
HTTP request.
• Browsers do not send this header, but Web spiders (robots) often set
it as a courtesy to help identify the source of server overloading or
repeated improper requests.
Host
• Browsers are required to specify this header, which indicates the host
and port as given in the original URL.
• Due to request forwarding and machines that have multiple
hostnames, it is quite possible that the server could not otherwise
determine this information.
• This header is not new in HTTP 1.1, but in HTTP 1.0 it was optional,
not required.
If-Match
• This rarely used header applies primarily to PUT requests.
• The client can supply a list of entity tags as returned by the ETag
response header, and the operation is performed only if one of them
matches.
If-Modified-Since
• Indicates that the client wants the page only if it has been changed
after the specified date.
• Very useful for browsers to cache documents and reload them over
the network only when they’ve changed.
• servlets don’t need to deal directly with this header, just implement
the getLastModified method to have the system handle modification
dates automatically.
If-None-Match
• This header is like If-Match, except that the operation should be
performed only if no entity tags match.
If-Range
• This rarely used header lets a client that has a partial copy of a
document ask for either the parts it is missing (if unchanged) or an
entire new document (if it has changed since a specified date).
If-Unmodified-Since
• Similar to If-Modified-Since in reverse.
• The operation should succeed only if the document is older than the
specified date.
• If-Modified-Since is used for GET requests (“give me the document
only if it is newer than my cached version”), whereas If-Unmodified-
Since is used for PUT requests (“update this document only if nobody
else has changed it since I generated it”).
Pragma
• A Pragma header with a value of no-cache indicates that a servlet that
is acting as a proxy should forward the request even if it has a local
copy.
• The only standard value for this header is no-cache.
Proxy-Authorization
• This header lets clients identify themselves to proxies that require it.
• Servlets typically ignore this header, using Authorization instead.
Range
• This rarely used header lets a client that has a partial copy of a
document ask for only the parts it is missing.
Referer
• indicates the URL of the referring Web page.
• All major browsers set this header, useful way of tracking where requests came
from.
• helpful for tracking advertisers who refer people to the site, for changing content
slightly depending on the referring site, or simply for keeping track of where the
traffic comes from.
• In the last case, most people simply rely on Web server log files, since the Referer is
typically recorded there.
• Although it’s useful, don’t rely too heavily on the Referer header since it can be
easily spoofed by a custom client.
• Note that this header is Referer, not the expected Referrer, due to a spelling mistake
by one of the original HTTP authors.
Upgrade
• Lets the browser or other client specify a communication protocol it
prefers over HTTP 1.1.
• If the server also supports that protocol, both the client and the
server can switch protocols.
• This type of protocol negotiation is almost always performed before
the servlet is invoked.
• Servlets rarely care about this header.
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.
• Relying on a hard-coded list of browser versions and associated features can make for
unreliable and hard-to-modify servlet code.
• Use something specific in the HTTP headers instead.
• Example
• Instead of trying to remember which browsers support gzip on which platforms check the Accept-
Encoding header
• Browser-specific feature does not adds enough value to be worth the maintenance cost.
• The User-Agent header is sometimes used to determine which JavaScript features are
supported.
• This header can be easily spoofed.
Via
• This header is set by gateways and proxies to show the intermediate
sites the request passed through
Warning
• This rarely used catchall header lets clients warn about caching or
content transformation errors.
Generating the Server Response: HTTP Status
Codes

• When a Web server responds to a request from a browser or other


Web client, the response typically consists of a status line.
• Example:

• All of the headers are optional except for Content-Type, which


specifies the MIME type of the document that follows.
Specifying Status Codes
• The HTTP response status line consists of an HTTP version, a status
code, and an associated message.
• setStatus method of HttpServletResponse is used to set response
status code.
• If response includes a special status code and a document, be sure to
call setStatus before actually returning any of the content via the
PrintWriter.
• An HTTP response consists of the status line, one or more headers, a
blank line, and the actual document, in that order.
Specifying Status Codes
• The setStatus method takes an int (the status code) as an argument.
• The constants defined in HttpServletResponse is clearer and more
reliable.
• The name of each constant is derived from the standard HTTP 1.1
message for each constant, all uppercase with a prefix of SC (for
Status Code) and spaces changed to underscores.
• Example:
• The message for 404 is “Not Found,” the equivalent constant in
HttpServletResponse is SC_NOT_FOUND.
Exceptions
• In version 2.1 ofthe servlet specification, there are three exceptions.
• The constant for code302 is derived from the HTTP 1.0 message (Moved
Temporarily), not the HTTP 1.1 message (Found), and the constants for codes
307 (Temporary Redirect) and 416 (Requested Range Not Satisfiable) are
missing altogether.
• Version 2.2 added the constant for 416
Shortcut Method In
Httpservletresponse
• public void sendError(int code, String message)
• The sendError method sends a status code (usually 404) along with a short
message that is automatically formatted inside an HTML document and sent
to the client.
• public void sendRedirect(String url)
• The sendRedirect method generates a 302 response along with a Location
header giving the URL of the new document.
• With servlets version 2.1, this must be an absolute URL.
• In version 2.2, either an absolute or a relative URL is permitted and the
system automatically translates relative URLs into absolute ones before
putting them in the Location header.
HTTP 1.1 Status Codes and
Their Purpose
• The complete HTTP 1.1 specification is given in RFC 2616.
• http://www.rfc-editor.org/
• Status codes available inHTTP 1.1 fall into five general categories:
• 100-199
• Codes in the 100s are informational, indicating that the client should respond with some other action.
• 200-299
• Values in the 200s signify that the request was successful.
• 300-399
• Values in the 300s are used for files that have moved and usually include a Location header indicating the new address.
• 400-499
• Values in the 400s indicate an error by the client.
• 500-599
• Codes in the 500s signify an error by the server.
• Use response.setStatus(response.SC_NO_CONTENT) rather than response.setStatus(204),
since the latter is unclear to readers and is prone to typographical errors.
100 (Continue)
• If the server receives an Expect request header with a value of 100-
continue, it means that the client is asking if it can send an attached
document in a follow-up request.
• In such a case, the server should either respond with status 100
(SC_CONTINUE) to tell the client to go ahead or use 417 (Expectation
Failed) to tell the browser it won’t accept the document.
• This status code is new in HTTP 1.1.
101 (Switching Protocols)
• A 101 (SC_SWITCHING_PROTOCOLS) status indicates that the server
will comply with the Upgrade header and change to a different
protocol.
• This status code is new in HTTP 1.1.
200 (OK)
• A value of 200 (SC_OK) means that everything is fine.
• The document follows for GET and POST requests.
• This status is the default for servlets; if setStatus is not used, 200 is
returned.
201 (Created)
• A status code of 201 (SC_CREATED) signifies that the server created a
new document in response to the request; the Location header
should give its URL.
202 (Accepted)
• A value of 202 (SC_ACCEPTED) tells the client that the request is being
acted upon, but processing is not yet complete.
203 (Non-Authoritative Information)
• A 203 (SC_NON_AUTHORITATIVE_INFORMATION) status signifies that
the document is being returned normally, but some of the response
headers might be incorrect since a document copy is being used.
• This status code is new in HTTP 1.1.
204 (No Content)
• A status code of 204 (SC_NO_CONTENT) stipulates that the browser
should continue to display the previous document because no new
document is available.
• This behavior is useful if the user periodically reloads a page by
pressing the “Reload” button, and you can determine that the
previous page is already up-to-date.
• Example:
204 (No Content) cont..
• Does not work for pages that are automatically reloaded via the
Refresh response header or the equivalent <META HTTP-
EQUIV="Refresh" ...> HTML entry, since returning a 204 status code
stops future reloading.
• JavaScript-based automatic reloading could still work in such a case
205 (Reset Content)
• A value of 205 (SC_RESET_CONTENT) means that there is no new
document, but the browser should reset the document view.
• This status code is used to force browsers to clear form fields.
• It is new in HTTP 1.1.
206 (Partial Content)
• A status code of 206 (SC_PARTIAL_CONTENT) is sent when the server
fulfills a partial request that includes a Range header.
• This value is new in HTTP 1.1.
300 (Multiple Choices)
• A value of 300 (SC_MULTIPLE_CHOICES) signifies that the requested
document can be found several places, which will be listed in the
returned document.
• If the server has a preferred choice, it should be listed in the Location
response header.
301 (Moved Permanently)
• The 301 (SC_MOVED_PERMANENTLY) status indicates that the
requested document is elsewhere; the new URL for the document is
given in the Location response header.
• Browsers should automatically follow the link to the new URL.
302 (Found)
• This value is similar to 301, except that the URL given by the Location
header should be interpreted as a temporary replacement, not a
permanent one.
• Note: in HTTP 1.0, the message was Moved Temporarily instead of
Found, and the constant in HttpServletResponse is
SC_MOVED_TEMPORARILY, not the expected SC_FOUND.
• Status code 302 is very useful because browsers automatically follow
the reference to the new URL given in the Location response header.
• there is a special method for it, sendRedirect.
Advantages of using sendRedirect over
response.setStatus(response.SC_MOVED_TEMPORAR
ILY)
• It is shorter and easier.
• With sendRedirect, the servlet automatically builds a page containing
the link to show to older browsers that don’t automatically follow
redirects
• With version 2.2 of servlets (the version in J2EE), sendRedirect can
handle relative URLs, automatically translating them into absolute
ones.
303 (See Other)
• The 303 (SC_SEE_OTHER) status is similar to 301 and 302, except that
if the original request was POST, the new document (given in the
Location header) should be retrieved with GET.
• This code is new in HTTP 1.1.
304 (Not Modified)
• When a client has a cached document, it can perform a conditional request
by supplying an If-Modified-Since header to indicate that it only wants the
document if it has been changed since the specified date.
• A value of 304 (SC_NOT_MODIFIED) means that the cached version is up-to-
date and the client should use it.
• Otherwise, the server should return the requested document with the
normal (200) status code.
• Servlets normally should not set this status code directly.
• Instead, they should implement the getLastModified method and let the
default service method handle conditional requests based upon this
modification date.
305 (Use Proxy)
• A value of 305 (SC_USE_PROXY) signifies that the requested
document should be retrieved via the proxy listed in the Location
header.
• This status code is new in HTTP 1.1.
307 (Temporary Redirect)
• The rules for how a browser should handle a 307 status are identical to those for
302.
• The 307 value was added to HTTP 1.1 since many browsers erroneously follow the
redirection on a 302 response even if the original message is a POST.
• Browsers are supposed to follow the redirection of a POST request only when they
receive a 303 response status.
• This new status is intended to be unambiguously clear: follow redirected GET and
POST requests in the case of 303 responses; follow redirected GET but not POST
requests in the case of 307 responses.
• Note: For some reason there is no constant in HttpServletResponse corresponding
to this status code.
• This status code is new in HTTP 1.1.
400 (Bad Request)
• A 400 (SC_BAD_REQUEST) status indicates bad syntax in the client
request.
401 (Unauthorized)
• A value of 401 (SC_UNAUTHORIZED) signifies that the client tried to
access a password-protected page without proper identifying
information in the Authorization header.
• The response must include a WWW-Authenticate header.
403 (Forbidden)
• A status code of 403 (SC_FORBIDDEN) means that the server refuses
to supply the resource, regardless of authorization.
• This status is often the result of bad file or directory permissions on
the server.
404 (Not Found)
• The infamous 404 (SC_NOT_FOUND) status tells the client that no resource could be found
at that address.
• This value is the standard “no such page” response.
• There is a special method for it in the HttpServletResponse class: sendError("message").
• The advantage of sendError over setStatus:
• with sendError, the server automatically generates an error page showing the error message.
• Unfortunately, however, the default behavior of Internet Explorer 5 is to ignore the error page send
back and displays its own, even though doing so contradicts the HTTP specification.
• To turn off this setting, go to the Tools menu, select Internet Options, choose the Advanced tab, and
make sure “Show friendly HTTP error messages” box is not checked.
• Unfortunately, however, few users are aware of this setting, so this “feature” prevents most users of
Internet Explorer version 5 from seeing any informative messages you return.
• Other major browsers and version 4 of Internet Explorer properly display server-generated error
pages
405 (Method Not Allowed)
• A 405 (SC_METHOD_NOT_ALLOWED) value indicates that the request
method (GET, POST, HEAD, PUT, DELETE, etc.) was not allowed for this
particular resource.
• This status code is new in HTTP 1.1.
406 (Not Acceptable)
• A value of 406 (SC_NOT_ACCEPTABLE) signifies that the requested
resource has a MIME type incompatible with the types specified by
the client in its Accept header.
• The 406 value is new in HTTP 1.1.
407 (Proxy Authentication Required)
• The 407 (SC_PROXY_AUTHENTICATION_REQUIRED) value is similar to
401, but it is used by proxy servers.
• It indicates that the client must authenticate itself with the proxy
server.
• The proxy server returns a Proxy-Authenticate response header to the
client, which results in the browser reconnecting with a Proxy-
Authorization request header.
• This status code is new in HTTP 1.1.
408 (Request Timeout)
• The 408 (SC_REQUEST_TIMEOUT) code means that the client took too
long to finish sending the request.
• It is new in HTTP 1.1.
409 (Conflict)
• Usually associated with PUT requests, the 409 (SC_CONFLICT) status is
used for situations such as an attempt to upload an incorrect version
of a file.
• This status code is new in HTTP 1.1.
410 (Gone)
• A value of 410 (SC_GONE) tells the client that the requested
document is gone and no forwarding address is known.
• Status 410 differs from 404 in that the document is known to be
permanently gone, not just unavailable for unknown reasons, as with
404.
• This status code is new in HTTP 1.1.
411 (Length Required)
• A status of 411 (SC_LENGTH_REQUIRED) signifies that the server
cannot process the request (assumedly a POST request with an
attached document) unless the client sends a Content-Length header
indicating the amount of data being sent to the server.
• This value is new in HTTP 1.1.
412 (Precondition Failed)
• The 412 (SC_PRECONDITION_FAILED) status indicates that some pre-
condition specified in the request headers was false.
• It is new in HTTP 1.1.
413 (Request Entity Too Large)
• A status code of 413 (SC_REQUEST_ENTITY_TOO_LARGE) tells the
client that the requested document is bigger than the server wants to
handle now.
• If the server thinks it can handle it later, it should include a Retry-After
response header.
• This value is new in HTTP 1.1.
414 (Request URI Too Long)
• The 414 (SC_REQUEST_URI_TOO_LONG) status is used when the URI
is too long.
• In this context, “URI” means the part of the URL that came after the
host and port in the URL.
• For example, in http://www.y2k-disaster.com:8080/we/look/silly/now/, the
URI is /we/look/silly/now/.
• This status code is new in HTTP 1.1.
415 (Unsupported Media Type)
• A value of 415 (SC_UNSUPPORTED_MEDIA_TYPE) means that the
request had an attached document of a type the server doesn’t know
how to handle.
• This status code is new in HTTP 1.1.
416 (Requested Range Not
Satisfiable)
• A status code of 416 signifies that the client included an unsatisfiable
Range header in the request.
• This value is new in HTTP 1.1.
• The constant that corresponds to this value was omitted from
HttpServletResponse in version 2.1 of the servlet API.
417 (Expectation Failed)
• If the server receives an Expect request header with a value of 100-
continue, it means that the client is asking if it can send an attached
document in a follow-up request.
• In such a case, the server should either respond with this status (417)
to tell the browser it won’t accept the document or use 100
(SC_CONTINUE) to tell the client to go ahead.
• This status code is new in HTTP 1.1.
500 (Internal Server Error)
• 500 (SC_INTERNAL_SERVER_ERROR) is the generic “server is
confused” status code.
• It often results from CGI programs or servlets that crash or return
improperly formatted headers.
501 (Not Implemented)
• The 501 (SC_NOT_IMPLEMENTED) status notifies the client that the
server doesn’t support the functionality to fulfill the request.
• It is used, for example, when the client issues a command like PUT
that the server doesn’t support.
502 (Bad Gateway)
• A value of 502 (SC_BAD_GATEWAY) is used by servers that act as
proxies or gateways; it indicates that the initial server got a bad
response from the remote server.
503 (Service Unavailable)
• A status code of 503 (SC_SERVICE_UNAVAILABLE) signifies that the
server cannot respond because of maintenance or overloading.
• For example, a servlet might return this header if some thread or
database connection pool is currently full.
• The server can supply a Retry-After header to tell the client when to
try again.
504 (Gateway Timeout)
• A value of 504 (SC_GATEWAY_TIMEOUT) is used by servers that act as
proxies or gateways; it indicates that the initial server didn’t get a
timely response from the remote server.
• This status code is new in HTTP 1.1.
505 (HTTP Version Not Supported)
• The 505 (SC_HTTP_VERSION_NOT_SUPPORTED) code means that the
server doesn’t support the version of HTTP named in the request line.
• This status code is new in HTTP 1.1
Generating the Server Response: HTTP
Response
Headers
• The HTTP response headers are set along with setting the status codes.
• Example:
• all the “document moved” status codes (300 through 307) have an accompanying Location
header.
• a 401 (Unauthorized) code always includes an accompanying WWW-Authenticate header
• Headers can also be set when no unusual status code is set.
• specify cookies,
• to supply the page modification date (for client-side caching),
• to instruct the browser to reload the page after a designated interval,
• to give the file size so that persistent HTTP connections can be used,
• to designate the type of document being generated,
• and to perform many other tasks.
Setting Response Headers from
Servlets
• Use the setHeader method of the HttpServletResponse.
• Takes two strings: the header name and the header value.
• Specify headers before returning the actual document.
• With servlets version 2.1, set the headers before the first use of the
PrintWriter or raw OutputStream
• With 2.2 version, the PrintWriter may use a buffer, so you can set
headers until the first time the buffer is flushed
Setting Response Headers from
Servlets cont..
• Two specialized methods to set headers
• setDateHeader(String header, long milliseconds)
• setIntHeader(String header, int headerValue)
• HTTP allows multiple occurrences of the same header name.
• Example: Accept and Set-Cookie headers takes multiple values.
• With servlets version 2.1, setHeader, setDateHeader and setIntHeader always
add new headers no way to “unset” headers.
• With servlets version 2.2
• setHeader, setDateHeader, and setIntHeader replace any existing headers of the same
name.
• addHeader, addDateHeader, and addIntHeader add a header.
• use containsHeader to check
Methods For Common Headers
• setContentType
• This method sets the Content-Type header and is used by the majority of
servlets.
• setContentLength
• This method sets the Content-Length header, which is useful if the browser
supports persistent (keep-alive) HTTP connections.
• addCookie
• This method inserts a cookie into the Set-Cookie header.
• There is no corresponding setCookie method, since it is normal to have
multiple Set-Cookie lines.
Methods For Common Headers
• sendRedirect
• sets the Location header as well as setting the status code to 302.
HTTP 1.1 Response Headers and
Their Meaning
• A superset of those permitted in HTTP 1.0.
• Standard specifications RFC 2616.
• Header names are not case sensitive, but are traditionally written
with the first letter of each word capitalized.
Accept-Ranges
• New in HTTP 1.1
• tells the client whether or not it accept Range request headers.
• Specify a value of bytes to indicate that it accept Range requests, and
a value of none to indicate that it does not.
Age
• Used by proxies to indicate how long ago the document was
generated by the original server.
• It is new in HTTP 1.1 and is rarely used by servlets.
Allow
• Specifies the request methods (GET, POST, etc.) that the server
supports.
• It is required for 405 (Method Not Allowed) responses.
• The default service method of servlets automatically generates this
header for OPTIONS requests.
Cache-Control
• Tells the browser or other client the circumstances in which the response document can safely be cached.
• It has the following possible values:
• public: Document is cacheable, even if normal rules (e.g., for password-protected pages) indicate that it shouldn’t be.
• private: Document is for a single user and can only be stored in private (nonshared) caches.
• no-cache:
• Document should never be cached (i.e., used to satisfy a later request).
• The server can also specify “no-cache="header1,header2,...,headerN"” to indicate the headers that should be
omitted if a cached response is later used.
• Browsers normally do not cache documents that were retrieved by requests that include form data.
• However, if a servlet generates different content for different requests even when the requests contain no form
data, it is critical to tell the browser not to cache the response.
• Since older browsers use the Pragma header for this purpose, the typical servlet approach is to set both
headers.
• Example
response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache");
Cache-Control
• no-store:
• Document should never be cached and should not even be stored in a temporary location on disk.
• This header is intended to prevent inadvertent copies of sensitive information.
• must-revalidate: Client must revalidate document with original server (not just intermediate proxies)
each time it is used.
• proxy-revalidate: This is the same as must-revalidate, except that it applies only to shared caches.
• max-age=xxx:
• Document should be considered stale after xxx seconds.
• This is a convenient alternative to the Expires header, but only works with HTTP 1.1 clients.
• If both max-age and Expires are present in the response, the max-age value takes precedence.
• s-max-age=xxx: Shared caches should consider the document stale after xxx seconds.

• The Cache-Control header is new in HTTP 1.1.


Connection
• A value of close for this response header instructs the browser not to
use persistent HTTP connections.
• Persistent connections are the default when the client supports HTTP
1.1 and does not specify a “Connection: close” request header.
• require a Content-Length response header.
• no reason for a servlet to explicitly use the Connection header
• omit the ContentLength header
Content-Encoding
• Indicates the way the page was encoded during transmission.
• The browser should decoding before deciding what to do with the
document.
• Compressing the document with gzip can result in huge savings in
transmission time
Content-Language
• Signifies the language in which the document is written.
• The value of the header should be one of the standard language
codes such as en, en-us, da, etc.
• See RFC 1766
Content-Location
• This header supplies an alternative address for the requested
document.
• Content-Location is informational; responses that include this header
also include the requested document, unlike the case with the
Location header.
• This header is new to HTTP 1.1.
Content-MD5
• Provides an MD5 digest for the subsequent document.
• This digest provides a message integrity check for clients that want to
confirm they received the complete, unaltered document.
• See RFC 1864 for details on MD5.
• This header is new in HTTP 1.1.
Content-Range
• This new HTTP 1.1 header is sent with partial-document responses
and specifies how much of the total document was sent.
• For example, a value of “bytes 500-999/2345” means that the current
response includes bytes 500 through 999 of a document that contains
2345 bytes in total.
Content-Type
• Gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
• There is a special method in HttpServletResponse for it: setContentType.
• MIME types are of the form maintype/subtype for officially registered
types, and of the form maintype/x-subtype for unregistered types.
• The default MIME type for servlets is text/plain, but servlets usually
explicitly specify text/html.
• Other examples:
• image/gif
• application/vnd.ms-excel.
Content-Type
• RFC 1521 and RFC 1522.
• The officially registered types are listed at
http://www.isi.edu/in-notes/iana/assignments/media-types/media-
types.
• For common unregistered types,
http://www.ltsw.se/knbase/internet/mime.htp
Common MIME Types
Type Meaning
application/msword Microsoft Word document
application/octet-stream Unrecognized or binary data
application/pdf Acrobat (.pdf) file
application/postscript PostScript file
application/vnd.lotus-notes Lotus Notes file
application/vnd.ms-excel Excel spreadsheet
application/vnd.ms-powerpoint Powerpoint presentation
application/x-gzip Gzip archive
application/x-java-archive JAR file
application/x-java-serialized- Serialized Java object
object
application/x-java-vm Java bytecode (.class) file
Zip archive Zip archive
Common MIME Types cont..
audio/basic Sound file in .au or .snd format
audio/x-aiff AIFF sound file
audio/x-wav Microsoft Windows sound file
audio/midi MIDI sound file
text/css HTML cascading style sheet
text/html HTML document
text/plain Plain text
image/gif GIF image
image/jpeg JPEG image
image/png PNG image
image/tiff TIFF image
image/x-xbitmap X Window bitmap image
video/mpeg MPEG video clip
video/quicktime QuickTime video clip
Date
• Specifies the current date in GMT format.
• To set the date from a servlet, use the setDateHeader method.
• Most servers set this header automatically.
ETag
• This new HTTP 1.1 header gives names to returned documents so that
they can be referred to by the client later
Expires
• This header stipulates the time at which the content should be
considered out-of-date and thus no longer be cached.
• A servlet might use this for a document that changes relatively
frequently, to prevent the browser from displaying a stale cached value.
• For example, the following would instruct the browser not to cache the
document for longer than 10 minutes
long currentTime = System.currentTimeMillis();
long tenMinutes = 10*60*1000; // In milliseconds
response.setDateHeader("Expires", currentTime + tenMinutes);
Last-Modified
• 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.
• This request is treated as a conditional GET, with the document only being returned
if the Last-Modified date is later than the one specified for If-Modified-Since.
• Otherwise, a 304 (Not Modified) status line is returned, and the client uses the
cached document.
• If you set this header explicitly, use the setDateHeader method to save yourself the
bother of formatting GMT date strings.
• Or simply implement the getLastModified method and let the standard service
method handle If-Modified-Since requests.
Location
• Included with all responses that have a status code in the 300s,
notifies the browser of the document address.
• The browser automatically reconnects to this location and retrieves
the new document.
• usually set indirectly, along with a 302 status code, by the
sendRedirect method of HttpServletResponse
Pragma
• A value of no-cache instructs HTTP 1.0 clients not to cache the
document.
• Support for this header was inconsistent with HTTP 1.0 browsers.
• In HTTP 1.1, “Cache-Control: no-cache” is a more reliable
replacement.
Refresh
• Indicates how soon (in seconds) the browser should ask for an updated
page.
• Example
response.setIntHeader("Refresh", 30)
• Does not stipulate continual updates; it just specifies when the next
update should be.
• Continue to supply Refresh in all subsequent responses, and sending a
204 (No Content) status code.
• To reload some other page, useful for “splash screens”
response.setHeader("Refresh", "5; URL=http://host/path")
Refresh cont..
• Alternately, useful for static HTML pages
<META HTTP-EQUIV="Refresh“ CONTENT="5; URL=http://host/path">
• This header is not officially part of HTTP 1.1 but is an extension
supported by both Netscape and Internet Explorer.
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.
Server
• This header identifies the Web server. Servlets don’t usually set this;
the Web server itself does.
Set-Cookie
• Specifies a cookie associated with the page.
• Each cookie requires a separate Set-Cookie header.
• Use the special-purpose addCookie method.
• Set-Cookie is not part of HTTP 1.1.
• It was originally a Netscape extension but is now very widely
supported, including in both Netscape and Internet Explorer.
Trailer
• This new and rarely used HTTP 1.1 header
• Identifies the header fields that are present in the trailer of a message
that is sent with “chunked” transfer-coding.
• Allows the sender to include additional fields at the end of chunked
messages in order to supply metadata that might be dynamically
generated while the message body is sent, such as a message
integrity check, digital signature, or post-processing status.
Transfer-Encoding
• Supplying this header with a value of chunked indicates “chunked”
transfer-coding.
• Example for without transfer encoding:
Transfer-Encoding cont..
• Example for with transfer encoding
Upgrade
• The client sends Upgrade request header, the server agrees and sends
a 101 (Switching Protocols) status code
• This response also includes an Upgrade response header with the
specific protocol it is switching to.
• This protocol negotiation is usually carried on by the server itself, not
by a servlet.
Vary
• This rarely used
• Added in HTTP 1.1
• Tells the client which headers can be used to determine if the
response document can be cached.
• Determines how to match future request headers to decide whether
a cached response can be used rather than requesting a fresh one
from the origin server.
• It is used by the server to indicate which headers it used when
selecting a representation of a resource in a content negotiation
algorithm.
Via
• This header is used by gateways and proxies to list the intermediate
sites the request passed through.
• It is new in HTTP 1.1
Warning
• This new and rarely used catchall header lets you warn clients about
caching or content transformation errors.
AutoRefresh
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
response.setHeader("Refresh", "5");
response.setHeader("Connection", "close");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AutoRefersh</title>");
out.println("</head>");
out.println("<body>");
out.println(new Date());
out.println("</body>");
out.println("</html>");
}
}
Setting Content-type Header
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new
FileInputStream("C:\\NetBeansProjects\\WebApplication4\\src\\java\\p\\image.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
Downloading a MS-Word Document
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String filename="myfile.docx";
String filepath="C:\\Users\\User\\Documents\\NetBeansProjects\\WebApplication4\\src\\java\\p\\";
response.setContentType("application/msword");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream=new FileInputStream(filepath+filename);
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
Redirecting a Page
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect("SendImage");
}
Customize Page Not Found
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.sendError(404,"This is not working");

}
Handling Cookies
• Benefits of Cookies
• Four typical ways in which cookies can add value to the site
• Identifying a User During an E-commerce Session
• Avoiding Username and Password
• Customizing a Site
• Focusing Advertising
Some Problems with Cookies
• Not a serious security threat.
• Never interpreted or executed
• Browsers generally only accept
• 20 cookies per site
• 300 cookies total
• Each cookie can be limited to 4 kilobytes => cookies cannot be used to fill up
someone’s disk or launch other denial of service attacks.
Some Problems with Cookies
• Present a significant threat to privacy
• Search engines Remembering searches on certain topics
• To avoid banner ad tipping off their coworkers next time they do a search
• Two sites can share data on a user by each loading small images off the same third-party
site.
• Associating cookies with images can even be exploited via e-mail if you use an HTML-
enabled e-mail reader
• Sites rely on cookies for overly sensitive data.
• Form filling without reentering much of your personal information like (credit card number)
• An attacker who got access to someone’s computer or cookie file could get on-line access
to valuable personal information.
• Incompetent sites might embed credit card or other sensitive information directly in the
cookies themselves
Points to remember
• Even when cookies are used to give added value to a site, the site
shouldn’t depend on them.
• Be careful not to use cookies for particularly sensitive information
The Servlet Cookie API
• Create one or more cookies with designated names and values
new Cookie(name, value).
• Set any optional attributes
cookie.setXxx (readable later by cookie.getXxx),
• insert the cookies into the response headers
response.addCookie(cookie)
• To read incoming cookies
request.getCookies() //returns an array of cookies
getValue()
Creating Cookies
• Call the Cookie constructor.
• Takes two strings: The cookie name and the cookie value
• Neither the name nor the value should contain white space or any of
the following characters:
[]()=,"/?@:;
Cookie Attributes
• Set various characteristics of the cookie by using one of the setXxx
methods
• Xxx is the name of the attribute.
• Each setXxx method has a corresponding getXxx method to retrieve
the attribute value.
• Applies only to outgoing cookies
public String getComment()
public void setComment(String
comment)
• Look up or specify a comment associated with the cookie.
• The comment is used purely for informational purposes on the server;
it is not sent to the client.
public String getDomain()
public void setDomain(String
domainPattern)
• Get or set the domain to which the cookie applies.
• The browser only returns cookies to the exact same hostname that sent them.
• use setDomain method to instruct the browser to return them to other hosts
within the same domain.
• To prevent servers setting cookies that apply to hosts outside their domain, the
domain specified is required to start with a dot.
• Must contain two dots for noncountry domains like .com, .edu and .gov
• Three dots for country domains like .co .uk and .es.
• Example: bali.vacations.com would not normally get sent by the browser to pages
at mexico.vacations.com.
cookie.setDomain(".vacations.com").
public int getMaxAge()
public void setMaxAge(int
lifetime)
• Tells how much time (in seconds) should elapse before the cookie
expires.
• A negative value is the default, indicates that the cookie will last only
for the current session and will not be stored on disk.
• The LongLivedCookie class is a subclass of Cookie
• Sets a maximum age automatically to one year in the future.
• Specifying a value of 0 instructs the browser to delete the cookie.
public String getName()
public void setName(String
cookieName)
• setName() is rarely used.
• getName is used on almost every cookie received on the server.
public String getPath()
public void setPath(String path)
• Get or set the path to which the cookie applies.
• If path not set, the browser returns the cookie only to URLs in or
below the directory containing the page that sent the cookie.
• Example: A cookie of http://ecommerce.site.com/toys/specials.html is
returned to http://ecommerce.site.com/toys/bikes/beginners.html
but not to http://ecommerce.site.com/cds/classical.html.
• General path: someCookie.setPath("/") specifies that all pages on the
server should receive the cookie.
public boolean getSecure()
public void setSecure(boolean
secureFlag)
• gets or sets the boolean value indicating whether the cookie should
only be sent over encrypted (i.e., SSL) connections.
• The default is false; the cookie should apply to all connections.
public String getValue()
public void setValue(String
cookieValue)
• The getValue method looks up the value associated with the cookie.
public int getVersion()
public void setVersion(int
version)
• get/set the cookie protocol version the cookie complies with.
• Version 0, the default, follows the original Netscape specification
• Version 1, not yet widely supported
• RFC 2109
Placing Cookies in the Response
Headers
• addCookie method of HttpServletResponse.
• Example:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // 1 year
response.addCookie(userCookie);
Reading Cookies from the Client
• Call getCookies on the HttpServletRequest.
• Returns an array of Cookie objects corresponding to the values that
came in on the Cookie HTTP request header.
• If there are no cookies, getCookies returns null.
• Loop down it, calling getName on each Cookie until a match is found.
• Call getValue on the matching Cookie

You might also like