0% found this document useful (0 votes)
37 views64 pages

Unit-3 J2EE

The document provides an overview of Java Servlet technology, detailing its advantages over CGI, the architecture of servlets, and the servlet lifecycle. It explains the roles of various methods such as init(), service(), doGet(), and doPost() in handling client requests. Additionally, it discusses the GenericServlet and HttpServlet classes, including their methods and how to develop HTML forms to interact with servlets.

Uploaded by

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

Unit-3 J2EE

The document provides an overview of Java Servlet technology, detailing its advantages over CGI, the architecture of servlets, and the servlet lifecycle. It explains the roles of various methods such as init(), service(), doGet(), and doPost() in handling client requests. Additionally, it discusses the GenericServlet and HttpServlet classes, including their methods and how to develop HTML forms to interact with servlets.

Uploaded by

deepika.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit-3

Java Servlet Technology

Introduction to Servlet

 Servlets provide a component-based, platform-independent method for building Web


based applications.

 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.

 But Servlets offer several advantages in comparison with the CGI.

 Performance is significantly better.

 Servlets execute within the address space of a Web server. It is not


necessary to create a separate process to handle each client request.

 Servlets are platform-independent because they are written in Java.

 Java security manager on the server enforces a set of restrictions to


protect the resources on a server machine. So servlets are trusted.

 The full functionality of the Java class libraries is available to a


servlet.

 It can communicate with applets, databases, or other software via


the sockets and RMI mechanisms.
Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.

Servlets perform the following major tasks −

 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.

Difference between CGI and Servlet


Servlet
 It is a Java class that helps extend the abilities of servers.
 These are the servers that help host applications, which are accessed using a
requestresponse model.
 They help extend the applications that are hosted using web servers.
 But they also have the ability to respond to other kinds of requests.
 For different kinds of applications, HTTP-specific servlet classes can be defined using
Java Servlet.
 These programs are written in Java, and they run on Java virtual machine.
 It is based on thread.
 This means that for every new request, a new thread is created.
 It is an object oriented concept.
 It is portable.
 It stays in memory until not explicitly eliminated.
 It can use any web-server.
 It allows data sharing.
 It helps link directly to the server.
 It can read and set the HTTP servers.
 The process of construction and destroying a thread is not expensive.

CGI (Common Gateway Interface)


 It behaves like a middleware between www servers and external database and
information resources.
 World Wide Web consortium has defined CGI.
 It also defines how a program would interact with a HTTP (HyperText Transfer
Protocol) server.
 The server would pass the information to an application.
 This application would process the data, and send a confirmation message stating the
same.
 This process of passing/communicating the data back and forth between the
application and the server is known as CGI.
 It is based on a process. This means that for every new request, a new process is
created.
 It can be implemented in any programming language.
 It need not be object oriented.
 It doesn’t link the server directly to the application.
 It doesn’t have the ability to set or read HTTP server data.
 The construction and destruction of processes is considered expensive.
 It is not portable.
 It is removed from memory once the request has been served.
 It uses web-server that it supports.
 It doesn’t support data sharing.

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. The init() Method


 The init method is called only once.
 It is called only when the servlet is created, and not called for any user requests
afterwards.
 So, it is used for one-time initializations, just as with the init method of applets.
 When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate.
 The init() method simply creates or loads some data that will be used throughout the
life of the servlet.

The init method definition

public void init() throws ServletException {


// Initialization code...
}

b. The service() Method


 The service() method is the main method to perform the actual task.
 The servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted response
back to the client.
 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. methods as
appropriate.
 So you have nothing to do with service() method but you override either doGet()
or doPost() depending on what type of request you receive from the client.
 The doGet() and doPost() are most frequently used methods with in each service
request.

Method Definition for service()

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {
}

The doGet() Method


 A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The doPost() Method

 A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

c. The destroy() Method


 The destroy() method is called only once at the end of the life cycle of a servlet.
 This method gives your servlet- a chance to close database connections, halt
background threads, write cookie lists or hit counts to disk, and perform other such
cleanup activities.
 After the destroy() method is called, the servlet object is marked for garbage
collection.

The destroy method definition:

public void destroy() {


// Finalization code...
}

Architecture Diagram

The following figure depicts a typical servlet life-cycle scenario.

 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.

Servlet Application Architecture


 A Servlet is a Java class that can be loaded dynamically into and run by a special web server.
 This Servlet-aware web server is called a Servlet container, which also was called a Servlet
engine in the early days of the Servlet technology.
 Servlets interact with clients via a request-response model based on HTTP.
 Because Servlet technology works on top of HTTP, a Servlet container must support HTTP as the
protocol for client requests and server responses.
 However, a Servlet container also can support similar protocols, such as HTTPS (HTTP over SSL)
for secure transactions.
 Figure 1 below provides the architecture of a Servlet application.

Figure 1: The Servlet application architecture

 In a JSP application, the Servlet container is replaced by a JSP container.


 Both the Servlet container and the JSP container often are referred to as the web container or
Servlet/JSP container, especially if a web application consists of both Servlets and JSP pages.
 As we can see in the Figure 1, a Servlet application also can include static content, such as HTML
pages and image files.
 Allowing the Servlet container to serve static content is not preferable because the content is faster
if served by a more robust HTTP server, such as the Apache web server or Microsoft’s Internet
Information Server (IIS).
 The Web server serves static content and passes to the Servlet containers all client requests for
Servlets.
 Figure 2 below shows a more common architecture for a Servlet application.

Figure 2: The Servlet application architecture employing an HTTP server.

Servlet’s working method (with detailed architecture)

 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

 GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.

 It provides the implementation of all the methods of these interfaces except the service method.

 GenericServlet class can handle any type of request so it is protocol-independent.

 You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.

3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is
being destroyed.

4. public ServletConfig getServletConfig() returns the object of ServletConfig.

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)

7. public ServletContext getServletContext() returns the object of ServletContext.

8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.

9. public Enumeration getInitParameterNames() returns all the parameters defined in the


web.xml file.

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

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the


protected service method by converting the request and response object into http type.

2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request


from the public service method, and dispatches the request to the doXXX() method depending on
the incoming http request type.

3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET


request. It is invoked by the web container.

4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST


request. It is invoked by the web container.

5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD


request. It is invoked by the web container.

6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the


OPTIONS request. It is invoked by the web container.

7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT


request. It is invoked by the web container.

8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the


TRACE request. It is invoked by the web container.

9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the


DELETE request. It is invoked by the web container.

10. protected long getLastModified(HttpServletRequest req) returns the time when


HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Handling Client Request :form data

 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:

1. Use <form>...</form> tag.


2. To develop various controls through <input>...</input> tag and all <input> tag must
be enclosed with in <form>...</form> tag.
3. Every form must call a servlet by using the following:

<form name="name of the form" action="either absolute or relative address"


method="get or post">
.........
.........
</form>

Write an html program to develop the 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>

HTTP Request and Response

 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:

Sr.No Header & Description


.

Accept
1
This header specifies the MIME types that the browser or other clients can handle.

Values of image/png or image/jpeg are the two most common possibilities.

2
Accept-Charset
This header specifies the character sets the browser can use to display the information.

For example ISO-8859-1.

Accept-Encoding
3 This header specifies the types of encodings that the browser knows how to handle.

Values of gzip or compress are the two most common possibilities.

Accept-Language

4
This header specifies the client's preferred languages in case the servlet can produce results
in more than one language.

For example en, en-us, ru, etc

Authorization
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.

A value of Keep-Alive means that persistent connections should be used.

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.

Methods to read HTTP Header

 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.

HttpSession getSession(boolean create)


6
Returns the current HttpSession associated with this request or, if if there is no current
session and value of create is true, returns a new session.

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 getHeader(String name)


14
Returns the value of the specified request header as a String.

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.

String[] getParameterValues(String name)


26
Returns an array of String objects containing all of the values the given request parameter
has, or null if the parameter does not exist.

boolean isSecure()
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 getIntHeader(String name)


29
Returns the value of the specified request header as an int.

int getServerPort()
30
Returns the port number on which this request was received.

HTTP Header Request Example

 Following is the example which uses getHeaderNames() method of


HttpServletRequest to read the HTTP header information.
 This method returns an Enumeration that contains the header information associated
with the current HTTP request.
 Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and
using nextElement() method to get each parameter name

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

Enumeration headerNames = request.getHeaderNames();


while(headerNames.hasMoreElements())
{
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}

Output:
HTTP Header Request Example

Header Name Header Value(s)

Accept */*

accept-language en-us

user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;


InfoPath.2; MS-RTC LM 8)

accept-encoding gzip, deflate

Host localhost:8080

Connection Keep-Alive

cache-control no-cache

 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).

HTTP Response Object

 Following is a summary of the most useful HTTP 1.1 response headers which go
back to the browser from web server side:

Sr.No Header & Description


.

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.

For example en, en-us, ru, etc

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.

Methods to Set HTTP Response Header

 There are following methods which can be used to set HTTP response header in your
servlet program.
 These methods are available with HttpServletResponse object.

Sr.No Method & Description


.
String encodeRedirectURL(String url)
1
Encodes the specified URL for use in the sendRedirect method or, if encoding is not
needed, returns the URL unchanged.

String encodeURL(String url)


2
Encodes the specified URL by including the session ID in it, or, if encoding is not needed,
returns the URL unchanged.

boolean containsHeader(String name)


3
Returns a Boolean indicating whether the named response header has already been set.

boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.

void addCookie(Cookie cookie)


5
Adds the specified cookie to the response.

void addDateHeader(String name, long date)


6
Adds a response header with the given name and date-value.

void addHeader(String name, String value)


7
Adds a response header with the given name and value.

void addIntHeader(String name, int value)


8
Adds a response header with the given name and integer value.

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.

void sendError(int sc)


12
Sends an error response to the client using the specified status code and clearing the buffer.

void sendError(int sc, String msg)


13
Sends an error response to the client using the specified status.

void sendRedirect(String location)


14
Sends a temporary redirect response to the client using the specified redirect location URL.

void setBufferSize(int size)


15
Sets the preferred buffer size for the body of the response.

void setCharacterEncoding(String charset)


16
Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.

void setContentLength(int len)


17
Sets the length of the content body in the response. In HTTP servlets, this method sets the
HTTP Content-Length header.

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.

void setDateHeader(String name, long date)


19
Sets a response header with the given name and date-value.

void setHeader(String name, String value)


20
Sets a response header with the given name and value.

void setIntHeader(String name, int value)


21 Sets a response header with the given name and in

teger value

void setLocale(Locale loc)


22
Sets the locale of the response, if the response has not been committed yet.

void setStatus(int sc)


23
Sets the status code for this response

Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Refresh extends HttpServlet
{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
response.setIntHeader("Refresh", 5);
response.setContentType("text/html");
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response.getWriter();
String title = "Auto Refresh Header Setting";
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" +
"<p>Current Time is: " + CT + "</p>\n"
);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}

 Now calling the above servlet would display current system time after every 5
seconds as follows:

Auto Refresh Header Setting


Current Time is: 9:44:50 PM

HTTP - Header Fields

 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:

These header fields have applicability only for request messages.

 Server Response-header:

These header fields have applicability only for response messages.

 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

o The Cache-Control general-header field is used to specify directives that


MUST be obeyed by all the caching system.
o The syntax is as follows:

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:

S.N Cache Request Directive and Description


.

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

Does not convert the entity-body.

7 only-if-cached

Does not retrieve new data.

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

Indicates that the response may be cached by any cache.

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

Does not convert the entity-body.

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.

The s-maxage directive is always ignored by a private cache.

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

 The Pragma general-header field is used to include implementation specific


directives that might apply to any recipient along the request/response chain.
 For example: Pragma: no-cache
 The only directive defined in HTTP/1.0 is the no-cache directive and is maintained
in HTTP 1.1 for backward compatibility.
 No new Pragma directives will be defined in the future.

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

 The Transfer-Encoding general-header field indicates what type of transformation


has been applied to the message body in order to safely transfer it between the sender
and the recipient.
 This is not the same as content-encoding because transfer-encodings are a property
of the message, not of the entity-body.
 The syntax of Transfer-Encoding header field is as follows:

Transfer-Encoding: chunked

 All transfer-coding values are case-insensitive.


g. Upgrade

 The Upgrade general-header allows the client to specify what additional


communication protocols it supports and would like to use if the server finds it
appropriate to switch protocols.
 For example:

Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11

 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:

Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)

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.

Warning: warn-code SP warn-agent SP warn-text SP warn-date

2. Client Request Headers

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:

Accept: type/subtype [q=qvalue]


 Multiple media types can be listed separately by commas and the optional qvalue
represents an acceptable quality level for accept types on a scale of 0 to 1.
 Following is an example:

Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c

 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:

Accept-Charset: character_set [q=qvalue]

 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:

Accept-Charset: iso-8859-5, unicode-1-1; q=0.8

 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

 The Accept-Encoding request-header field is similar to Accept, but restricts the


content-codings that are acceptable in the response.
 The general syntax is:

Accept-Encoding: encoding types

Examples are as follows:

Accept-Encoding: compress, gzip


Accept-Encoding:
Accept-Encoding: *
Accept-Encoding: compress;q=0.5, gzip;q=1.0
Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0

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:

Accept-Language: language [q=qvalue]

 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:

Accept-Language: da, en-gb;q=0.8, en;q=0.7

e. Authorization

 The Authorization request-header field value consists of credentials containing the


authentication information of the user agent for the realm of the resource being
requested.
 The general syntax is:

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:

Authorization: BASIC Z3Vlc3Q6Z3Vlc3QxMjM=

 The value decodes into is guest:guest123 where guest is user ID and guest123 is the
password.

f. Cookie

 The Cookie request-header field value contains a name/value pair of information


stored for that URL.
 Following is the general syntax:

Cookie: name=value

 Multiple cookies can be specified separated by semicolons as follows:


Cookie: name1=value1;name2=value2;name3=value3

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:

Expect : 100-continue | expectation-extension

 If a server receives a request containing an Expect field that includes an expectation-


extension that it does not support, it must respond with a 417 (Expectation Failed)
status.

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:

Host : "Host" ":" host [ ":" port ] ;

 A host without any trailing port information implies the default port, which is 80.

j. If-Match

 The If-Match request-header field is used with a method to make it conditional.


 This header requests the server to perform the requested method only if the given
value in this tag matches the given entity tags represented by ETag.
 The general syntax is:

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.

3. Server Response Headers

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 : range-unit | none

 For example a server that accepts byte-range requests may send:

Accept-Ranges: bytes

 Servers that do not accept any kind of range request for a resource may send:

Accept-Ranges: none

 This will advise the client not to attempt a range request.

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

 Here are some simple examples:

ETag: "xyzzy"
ETag: W/"xyzzy"
ETag: ""

d. Location

 The Location response-header field is used to redirect the recipient to a location


other than the Request-URI for completion.
 The general syntax is:

Location : absoluteURI

 Following is a simple example:

Location: http://www.abc.org/http/index.htm

e. Proxy-Authenticate

 The Proxy-Authenticate response-header field must be included as a part of a 407


(Proxy Authentication Required) response.
 The general syntax is:

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:

Retry-After : HTTP-date | delta-seconds

Examples:

Retry-After: Fri, 31 Dec 1999 23:59:59 GMT


Retry-After: 120

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

 Following is a simple example:

Allow: GET, HEAD, PUT

b. Content-Encoding

 The Content-Encoding entity-header field is used as a modifier to the media-type.


 The general syntax is:

Content-Encoding : content-coding

 The content-coding is a characteristic of the entity identified by the Request-URI.


 Following is a simple example:

Content-Encoding: gzip

 If the content-coding of an entity in a request message is not acceptable to the origin


server, the server should respond with a status code of 415 (Unsupported Media
Type).
c. Content-Language

 The Content-Language entity-header field describes the natural language(s) of the


intended audience for the enclosed entity.
 Following is the general syntax:

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

 The Content-Length entity-header field indicates the size of the entity-body, in


decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
method, the size of the entity-body that would have been sent, had the request been a
GET.
 The general syntax is:

Content-Length : DIGITS

 Following is a simple example:

Content-Length: 3495

 Any Content-Length greater than or equal to zero is a valid value.

e. Content-Location

 The Content-Location entity-header field may be used to supply the resource


location for the entity enclosed in the message when that entity is accessible from a
location separate from the requested resource's URI.
 The general syntax is:

Content-Location: absoluteURI | relativeURI

 Following is a simple example:

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:

S.N. Code and Description

1 1xx: Informational

It means the request has been received and the process is continuing.

2 2xx: Success

It means the action was successfully received, understood, and accepted.

3 3xx: Redirection

It means further action must be taken in order to complete the request.

4 4xx: Client Error

It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error

It means the server failed to fulfil an apparently valid request.

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.

101 Switching The server switches protocol.


Protocols

2xx: Successful

Message Description

200 OK The request is OK.

201 Created The request is complete, and a new resource is created.

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

4xx: Client Error

Message Description

400 Bad Request The server did not understand the request.

401 Unauthorized The requested page needs a username and a password.

402 Payment Required You cannot use this code yet.

403 Forbidden Access is forbidden to the requested page.


404 Not Found The server cannot find the requested page.

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.

409 Conflict The request could not be completed because of a conflict.

410 Gone The requested page is no longer available.

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.

5xx: Server Error

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.

504 Gateway Timeout The gateway has timed out.

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.

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

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:

S.N. Code and Description

1 1xx: Informational
It means the request was received and the process is continuing.

2 2xx: Success

It means the action was successfully received, understood, and accepted.

3 3xx: Redirection

It means further action must be taken in order to complete the request.

4 4xx: Client Error

It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error

It means the server failed to fulfill an apparently valid request.

 HTTP status codes are extensible and HTTP applications are not required to
understand the meaning of all registered status codes.

Response Header Fields

 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.

Examples of Response Message

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:

HTTP/1.1 404 Not Found


Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body>
</html>

 Following is an example of HTTP response message showing error condition when


the web server encountered a wrong HTTP version in the given HTTP request:

HTTP/1.1 400 Bad Request


Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Content-Type: text/html; charset=iso-8859-1
Connection: Closed

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">


<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.</p>
<p>The request line contained invalid characters following the protocol string.</p>
</body>
</html>

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.

 By default, each request is considered as a new request.

 In cookies technique, we add cookie with response from the servlet.

 So cookie is stored in the cache of the browser.

 After that if request is sent by the user, cookie is added with request by default.

 Thus, we recognize the user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

 It is valid for single session only.

 It is removed each time when user closes the browser.

Persistent cookie

 It is valid for multiple session.

 It is not removed each time when user closes the browser.

 It is removed only if user logout or signout.

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

 javax.servlet.http.Cookie class provides the functionality of using cookies.

 It provides a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.


Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

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.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces.

They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in

object.

2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the

cookies from the browser.

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
}

Servlet Cookies example

 In this example, we are storing the name of the user in the cookie object and accessing
it in another servlet.

 As we know well that session corresponds to the particular user.

 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>

Session Tracking in Servlets


 Session simply means a particular interval of time.
 Session Tracking is a way to maintain state (data) of a user.
 It is also known as session management in servlet.

 Http protocol is a stateless protocol, so we need to maintain state using


session tracking techniques.

 Each time user requests to the server, server treats the request as the new
request.

 So we need to maintain the state of a user to recognize to particular user.

 HTTP is stateless that means each request is considered as the new


request.

 It is shown in the figure given below:


Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Hidden Form Field

 In case of Hidden Form Field a hidden (invisible) textfield is used for


maintaining the state of a user.

 In such case, we store the information in the hidden field and get it from
another servlet.

<input type="hidden" name="uname" value="Vishal">

 Here, uname is the hidden field name and Vishal is the hidden field
value.

 It is widely used in comment form of a website.


 In such case, we store page id or page name in the hidden field so that
each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:


1. It is maintained at server side.
2. Extra form submission is required on each page.
3. Only textual information can be used.

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

 In URL rewriting, we append a token or identifier to the URL of the next


Servlet or the next resource.

 We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

 A name and a value is separated using an equal = sign, a parameter


name/value pair is separated from another parameter using the
ampersand(&).

 When the user clicks the hyperlink, the parameter name/value pairs will
be passed to the server.

 From a Servlet, we can use getParameter() method to obtain a parameter


value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser
independent).
2. Extra form submission is not required on each page.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send only textual information.

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:

1. public HttpSession getSession():Returns the current session associated


with this request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current session
and create is true, returns a new session.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique identifier
value.
2. public long getCreationTime():Returns the time when this session was
created, measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent
a request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects
bound to it.

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);}
}
}

You might also like