0% found this document useful (0 votes)
2 views23 pages

OOPS unit 5

The document provides an overview of Java Servlets, detailing their role as a middle layer between web clients and servers, and outlining their architecture and lifecycle. It explains the setup of the development environment, including the Java Development Kit and Apache Tomcat, as well as the compilation and deployment of a sample servlet. Additionally, it covers how to handle form data using GET and POST methods in servlets.

Uploaded by

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

OOPS unit 5

The document provides an overview of Java Servlets, detailing their role as a middle layer between web clients and servers, and outlining their architecture and lifecycle. It explains the setup of the development environment, including the Java Development Kit and Apache Tomcat, as well as the compilation and deployment of a sample servlet. Additionally, it covers how to handle form data using GET and POST methods in servlets.

Uploaded by

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

CS1303 Object Oriented Programming Department of CSE 2022-2023

Unit-V
Servlets
Servlets provide a component-based, platform-independent method for building Web-based
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or applications
on the HTTP server.

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

Servlets Architecture:

Following diagram shows the position of Servelts in a Web Application.

Servlets Tasks:

Servlets perform the following major tasks:

 Read the explicit data sent by the clients (browsers).


 Read the implicit HTTP request data sent by the clients (browsers).
 Process the data and generate the results.
 Send the explicit data (i.e., the document) to the clients (browsers).
 Send the implicit HTTP response to the clients (browsers).

Servlets - Environment Setup:

A development environment is where you would develop your Servlet, test them and finally
run them.

1
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Like any other Java program, you need to compile a servlet by using the Java compiler javac
and after compilation the servlet application, it would be deployed in a configured
environment to test and run.

Setting up Java Development Kit

This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up PATH environment variable appropriately.

You can download SDK from Oracle's Java site: Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.

If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the
following line in your C:\autoexec.bat file.

set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select


Properties, then Advanced, then Environment Variables. Then, you would update the PATH
value and press the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use
the C shell, you would put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland


JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat

A number of Web Servers that support servlets are available in the market. Some web servers
are freely downloadable and Tomcat is one of them.

Apache Tomcat is an open source software implementation of the Java Servlet and
JavaServer Pages technologies and can act as a standalone server for testing servlets and can
be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your
machine:

 Download latest version of Tomcat from http://tomcat.apache.org/.


 Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or

2
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

/usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME


environment variable pointing to these locations.

Tomcat can be started by executing the following commands on windows machine:

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine:

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After startup, the default web applications included with Tomcat will be available by visiting
http://localhost:8080/. If everything is fine then it should display following result:

Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org

Tomcat can be stopped by executing the following commands on windows machine:

C:\apache-tomcat-5.5.29\bin\shutdown

3
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine:

/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Setting up CLASSPATH

Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.

If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.

set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select


Properties, then Advanced, then Environment Variables. Then, you would update the
CLASSPATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.

setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

NOTE: Assuming that your development directory is C:\ServletDevel (Windows) or


/usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH in similar way as you have added above.

Servlets - Life Cycle:

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

 The servlet is initialized by calling the init () method.


 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.

4
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

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 looks like this:

public void init() throws ServletException {


// Initialization code...
}

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.

Here is the signature of this method:

public void service(ServletRequest request,


ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, 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.
Here is the signature of these two methods.

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.

5
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

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 looks like this:

public void destroy() {


// Finalization code...
}

Architecture Digram:

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.

6
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Examples

Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.

Sample Code for Hello World:

Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException


{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()


{
// do nothing.
}
}

Compiling a Servlet:

Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows)
or /usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH.

Assuming your environment is setup properly, go in ServletDevel directory and compile


HelloWorld.java as follows:

$ javac HelloWorld.java

7
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.

This command line uses the built-in javac compiler that comes with the Sun Microsystems
Java Software Development Kit (JDK). For this command to work properly, you have to
include the location of the Java SDK that you are using in the PATH environment variable.

If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory. Next section would explain how a compiled servlet would be deployed in
production.

Servlet Deployment:

By default, a servlet application is located at the path <Tomcat-installation-


directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcat-installation-


directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file
located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml file.


There could be various entries in this table already available, but never mind.

You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on
Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address
box. If everything goes fine, you would get following result:

8
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Servlets - Form Data

You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your backend program. The browser uses two
methods to pass this information to web server. These methods are GET Method and POST
Method.

GET method:

The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows:

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server. The GET
method has size limtation: only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method.

POST method:

A generally more reliable method of passing information to a backend program is the POST
method. This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This
message comes to the backend program in the form of the standard input which you can parse
and use for your processing. Servlet handles this type of requests using doPost() method.

9
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Reading Form Data using Servlet:

Servlets handles form data parsing automatically using the following methods depending on
the situation:

 getParameter(): You call request.getParameter() method to get the value of a form


parameter.
 getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
 getParameterNames(): Call this method if you want a complete list of all parameters
in the current request.

GET Method Example Using URL:

Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI

Below is HelloForm.java servlet program to handle input given by web browser. We are
going to use getParameter() method which makes it very easy to access passed information:

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
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" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
}

10
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Assuming your environment is setup properly, compile HelloForm.java as follows:

$ javac HelloForm.java

If everything goes fine, above compilation would produce HelloForm.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your
browser's Location:box and make sure you already started tomcat server, before firing above
command in the browser. This would generate following result:
Using GET Method to Read Form Data

 First Name: ZARA

 Last Name: ALI

GET Method Example Using Form:

Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this imput.

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-


directory>/webapps/ROOT directory. When you would access
http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name: Last Name:

11
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Try to enter First Name and Last Name and then click submit button to see the result on your
local machine where tomcat is running. Based on the input provided, it will generate similar
result as mentioned in the above example.

POST Method Example Using Form:

Let us do little modification in the above servlet, so that it can handle GET as well as POST
methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
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" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Now compile, deploy the above Servlet and test it using Hello.htm with the POST method as
follows:

<html>
<body>
<form action="HelloForm" method="POST">

12
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

First Name: <input type="text" name="first_name">


<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Here is the actual output of the above form, Try to enter First and Last Name and then click
submit button to see the result on your local machine where tomcat is running.

First Name: Last Name:

Based on the input provided, it would generate similar result as mentioned in the above
examples.

Passing Checkbox Data to Servlet Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

The result of this code is the following form

Maths Physics Chemistry

Below is CheckBox.java servlet program to handle input given by web browser for checkbox
button.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class CheckBox extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{

13
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading Checkbox Data";
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" +
"<ul>\n" +
" <li><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

For the above example, it would display following result:

Reading Checkbox Data

 Maths Flag : : on

 Physics Flag: : null

 Chemistry Flag: : on

Reading All Form Parameters:

Following is the generic example which uses getParameterNames() method of


HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order.

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.

14
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class ReadParams extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading All Form Parameters";
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>Param Name</th><th>Param Value(s)</th>\n"+
"</tr>\n");

Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues =
request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

15
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

doGet(request, response);
}
}

Now, try above servlet with the following form:

<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

Now calling servlet using above form would generate following result:

Reading All Form Parameters

Param Name Param Value(s)

maths on

chemistry on

You can try above servlet to read any other form's data which is having other objects like text
box, radio button or drop down box etc.

Servlets - Cookies Handling

Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.

There are three steps involved in identifying returning users:

 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

This chapter will teach you how to set or reset cookies, how to access them and how to delete
them.

16
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

The Anatomy of a Cookie:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A servlet that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and domain of
the cookie, it will resend the cookie to the server. The browser's headers might look
something like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A servlet will then have access to the cookie through the request method request.getCookies()
which returns an array of Cookie objects.

Servlet Cookies Methods:

Following is the list of useful methods which you can use while manipulating cookies in
servlet.

S.N. Method & Description

public void setDomain(String pattern)


1
This method sets the domain to which cookie applies, for example tutorialspoint.com.
public String getDomain()
2
This method gets the domain to which cookie applies, for example tutorialspoint.com.
public void setMaxAge(int expiry)
3
This method sets how much time (in seconds) should elapse before the cookie expires. If

17
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

you don't set this, the cookie will last only for the current session.
public int getMaxAge()
4
This method returns the maximum age of the cookie, specified in seconds, By default, -1
indicating the cookie will persist until browser shutdown.
public String getName()
5
This method returns the name of the cookie. The name cannot be changed after creation.
public void setValue(String newValue)
6
This method sets the value associated with the cookie.
public String getValue()
7
This method gets the value associated with the cookie.
public void setPath(String uri)
8
This method sets the path to which this cookie applies. If you don't specify a path, the
cookie is returned for all URLs in the same directory as the current page as well as all
subdirectories.
public String getPath()
9
This method gets the path to which this cookie applies.
public void setSecure(boolean flag)
10
This method sets the boolean value indicating whether the cookie should only be sent
over encrypted (i.e. SSL) connections.
public void setComment(String purpose)
11
This method specifies a comment that describes a cookie's purpose. The comment is
useful if the browser presents the cookie to the user.
public String getComment()
12
This method returns the comment describing the purpose of this cookie, or null if the
cookie has no comment.

Setting Cookies with Servlet:

Setting cookies with servlet involves three steps:

(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the
following characters:

18
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the
cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to
add cookies in the HTTP response header as follows:

response.addCookie(cookie);

Example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Setting Cookies 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" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body></html>");

19
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

}
}

Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try
following HTML page to call servlet.

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-


directory>/webapps/ROOT directory. When you would access
http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name:

Last Name:

Try to enter First Name and Last Name and then click submit button. This would display first
name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.

Next section would explain you how you would access these cookies back in your web
application.

Reading Cookies with Servlet:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling


the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use
getName() and getValue() methods to access each cookie and associated value.

Example:

Let us read cookies which we have set in previous example:

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class ReadCookies extends HttpServlet {

public void doGet(HttpServletRequest request,

20
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading Cookies 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" );
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}

Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you
would have set first_name cookie as "John" and last_name cookie as "Player" then running
http://localhost:8080/ReadCookies would display the following result:

Found Cookies Name and Value

Name : first_name, Value: John

Name : last_name, Value: Player

Delete Cookies with Servlet:

To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps:

 Read an already exsiting cookie and store it in Cookie object.


 Set cookie age as zero using setMaxAge() method to delete an existing cookie.
 Add this cookie back into response header.

21
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Example:

Following example would delete and existing cookie named "first_name" and when you
would run ReadCookies servlet next time it would return null value for first_name.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class DeleteCookies extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Delete Cookies 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" );
if( cookies != null ){
out.println("<h2> Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}

Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now
running http://localhost:8080/DeleteCookies would display the following result:

22
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows:

Found Cookies Name and Value

Name : last_name, Value: Player

You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.

Notes: tutorialpoint.com

23
St.Joseph’s College of Engineering

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy