You are on page 1of 26

(1)Program One

//Servlet First Program To Display A Message


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
(2)Program Two
//Passing value from HTML File
//Servlets program accept the request and send the output
//First Create a HTML File and then create a Servlets
program
HTML File Program
<html>
<head>
<title>Calculator Program</title>
</head>
<body>
<FORM method="Get"
ACTION="http://localhost:8080/servletproject/Myservletprog">
<BR>
<font size=5 color="red">

Enter Item Name


<input TYPE=text name=itname VALUE=""><BR>
Enter Item Price
<input TYPE=text name=iprice VALUE=""> <BR>
Enter Item Qty
<input TYPE=text name=iqty VALUE=""> <BR>
<BR>
<INPUT TYPE=submit name=submit Value="Submit">
</font>
</FORM>
</body>
</html>

Servlet Program
import java.io.IOException;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Myservletprog extends HttpServlet
{
protected void doGet(HttpServletRequest rq,
HttpServletResponse response)
throws ServletException, IOException
{
int n1=Integer.parseInt(rq.getParameter("num1"));
int n2=Integer.parseInt(rq.getParameter("num2"));
int sum=n1+n2;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Calculator File</title>");
out.println("</head>");
out.println("<body>");
out.println(<h1>+ sum + </h1>);
out.println("</body>");
out.println("</html>");

}
}
(3)Program Three

//Write A Servlet program that accept string argument from


HTML Page and Display Vowels Characters Only
HTML Program
<html>
<head>
<title>String Program</title>
</head>
<body>
<FORM method="Get"
ACTION="http://localhost:8080/servletproject/SerVowel">
<BR>
<font size=5 color="red">
Enter Any String
<input TYPE=text name=str VALUE=""><BR>
<BR>
<INPUT TYPE=submit name=submit Value="Submit">
</font>
</FORM>
</body>
</html>
Servlet Program
package myserpackage;
import java.io.IOException;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Myservletprog extends HttpServlet
{

protected void doGet(HttpServletRequest rq,


HttpServletResponse response)
throws ServletException, IOException
{
String str =rq.getParameter("str");
char ch;
int ln=str.length();
int i;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>String File</title>");
out.println("</head>");
out.println("<body>");
for(i=0;i<ln;i++)
{
ch=str.charAt(i);
if(ch==a||ch==e||ch==i||ch==o||ch==u)
{
Out.print(ch);
}
}
out.println("</body>");
out.println("</html>");
}
}

Multi-tier Applications: Using JDBC from a Servlet

Servlets can communicate with databases via JDBC (Java Database


Connectivity).

Many of todays applications are three-tier distributed applications,


consisting of a
1. User interface (HTML , XHTML, Dynamic HTML or applets )
2. Business logic ( Web servers )
3. Database access.

Using the networking provided automatically by the browser, the user


interface can communicate with the middle-tier business logic. The middle

tier can then access the database to manipulate the data. The three tiers
can reside on separate computers that are connected to a network.

In multi-tier architectures, Web servers often represent the middle


tier. They provide the business logic that manipulates data from
databases and that communicates with client Web browsers.

Servlets, through JDBC, can interact with popular database systems.


Developers do not need to be familiar with the specifics of each
database system. Rather, developers use SQL-based queries and the
JDBC driver handles the specifics of interacting with each database
system.

(4)Program Four
//Write a servlet program that display all the records from
the Database table after click on show button from the html
page
HTML Program
<html>
<head>
<title>Program For Displaying Record</title>
</head>
<body>
<FORM method="Get"
ACTION="http://localhost:8080/servletproject/ShowRecord">
<BR>
<font size=5 color="red">
Display Record
<BR>
<INPUT TYPE=submit name=submit Value="ShowData">
</font>
</FORM>
</body>
</html>
Servlet Program
package myserpackage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;
import java.io.*;
public class ShowRecord extends HttpServlet
{
public void doGet(HttpServletRequest rq,
HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:emp","","");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("Select * From table1");
p.println("<html>");
p.println("<body bgcolor=#C3C3FF>");
p.println("<font face=verdana size=4 color=#b88ff9>");
p.print("<table border=1><tr><th>Code");
p.println("</th><th>Name</th><th>Designation</th><th>Salary<
/th></tr>");
while (rs.next())
{
p.println("<tr><td>" + rs.getInt(1)+
"</td><td>" + rs.getString(2)+
"</td><td>"+rs.getString(3)+
"</td><td>"+rs.getInt(4)+
"</td></tr>");
}
p.println("</table>") ;
p.println("</body></html>") ;
}//End of try
catch(ClassNotFoundException e)
{}
catch(SQLException T)
{}
}
}

Program 5

//Write a program to insert record into Database through Servlet


HTML Program
<HTML>
<BODY bgcolor="white">
<FORM Method="Get" ACTION="http://localhost:8080/MywebProject/Servletadd">
<BR>
<font size=5 color="red">
Enter Code
<input TYPE=text name=cd VALUE=""><BR>
Enter Name
<input TYPE=text name=nm VALUE=""> <BR>
Enter Designation
<input TYPE=text name=des VALUE=""><BR>
Enter Salary
<input TYPE=text name=sal VALUE=""><BR>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</font>
</FORM>
</BODY>
</HTML>
Servlet Program
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servletadd extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
int ecode=Integer.parseInt(rq.getParameter("cd"));
String ename=rq.getParameter("nm"));
String edesig=rq.getParameter("des"));
int esal=Integer.parseInt(rq.getParameter("sal"));
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:san","","");
PreparedStatement ps=con.prepareStatement("insert into table1 values(?,?,?,?)");
ps.setInt(1,ecode);
ps.setString(2,ename);
ps.setString(3,edesig);
ps.setInt(4,esal);

ps.executeUpdate();
p.println("<html>");
p.println("<body>");
p.println("Data Is Added");
p.println("</html>");
p.println("</body>");
}//End of try
catch(ClassNotFoundException e)
{}
catch(SQLException T)
{}
}
}
Program 6
//Write a program to Update record using servlet
HTML Program
<HTML>
<BODY bgcolor="white">
<FORM Method="Get" ACTION="http://localhost:8080/Mywebproject/Servletmod">
<BR>
<font size=5 color="red">
Enter Code For Modification
<INPUT TYPE=text name="cd" Value="">
<br>
<INPUT TYPE=submit name=submit Value="Modify">
</font>
</FORM>
</BODY>
</HTML>
Servlet Program6(1)Part
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servletmod extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
int mcode;
int rt;

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:san","","");
Statement stmt=con.createStatement();
String buff;
ResultSet rs;
mcode=Integer.parseInt(rq.getParameter("cd"));
rs=stmt.executeQuery("select * from table1 where code="+mcode);
int i=0;
while(rs.next())
{
i++;
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>MODIFICATION FORM</h1>");
p.println("<form method=Get
action=http://localhost:8080/Mywebproject/Sermodify>");
p.println("Code");
p.println("<input type=text name=cd value='"+rs.getInt(1)+"'
size=20><br>");
p.println("Name");
p.println("<input type=text name=nm value='"+rs.getString(2)+"'
size=20><br>");
p.println("Designation");
p.println("<input type=text name=des value='"+rs.getString(3)+"'
size=20><br>");
p.println("Salary");
p.println("<input type=text name=sal value='"+rs.getInt(4)+"'
size=20><br>");
p.println("<input type=submit value=Update>");
p.println("</form>");
p.println("</body></html>");
}
if(i==0)
{
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>Record Not Found</h1>");
p.println("</body></html>");
}

}//End of try
catch(ClassNotFoundException e)
{}
catch(SQLException T)
{}
}
Servlet Program(6) 2 Part
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Sermodify extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
int mcode,msal;
String mname,mdesig;
int rt;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:san","","");
Statement stmt=con.createStatement();
String buff;
ResultSet rs;
mcode=Integer.parseInt(rq.getParameter("cd"));
mname=rq.getParameter("nm");
mdesig=rq.getParameter("des");
msal=Integer.parseInt(rq.getParameter("sal"));
buff="Update table1 Set
code='"+mcode+"',name='"+mname+"',desig='"+mdesig+"',salary='"+msal+"' where
code="+mcode;
rt=stmt.executeUpdate(buff);
if(rt>0)
{
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>Record Updated</h1>");
p.println("</body></html>");

}
else
{
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>Record Not Updated</h1>");
p.println("</body></html>");
}
}//End of try
catch(ClassNotFoundException e)
{}
catch(SQLException T)
{}
}
}
Program 7
//Write a program to Delete record using servlet
HTML Program
<HTML>
<BODY bgcolor="white">
<FORM Method="Get" ACTION="http://localhost:8080/Mywebproject/Servletdel">
<BR>
<font size=5 color="red">
Enter Code For Deletion
<INPUT TYPE=text name="cd" Value="">
<br>
<INPUT TYPE=submit name=submit Value="Delete">
</font>
</FORM>
</BODY>
</HTML>
Servlet Program
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servletdel extends HttpServlet
{
public void doGet(HttpServletRequest rq, HttpServletResponse res)
throws ServletException,IOException
{

res.setContentType("text/html");
PrintWriter p=res.getWriter();
int mcode;
int rt;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:san","","");
Statement stmt=con.createStatement();
String buff;
ResultSet rs;
mcode=Integer.parseInt(rq.getParameter("cd"));
rs=stmt.executeQuery("select * from table1 where code="+mcode);
int i=0;
while(rs.next())
{
i++;
}
if(i>0)
{
buff="delete from table1 where code="+mcode;
rt=stmt.executeUpdate(buff);
}
if(i>0)
{
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>Record Deleted");
}
else
{
p.println("<html>");
p.println("<body bgcolor=red>");
p.println("<font face=verdana size=4 color=blue>");
p.println("<h1>Record Not Found");
}
p.println("</body></html>");
}
catch(ClassNotFoundException e)
{}
catch(SQLException T)
{}
}
}

Difference between HttpServlet and GenericServlet


javax.servlet.GenericServlet
public abstract class GenericServlet extends java.lang.Object implements Servlet,
ServletConfig, java.io.Serializable

GenericServlet defines a generic, protocol-independent servlet.


GenericServlet gives a blueprint and makes writing servlet easier.
GenericServlet provides simple versions of the lifecycle methods init and destroy
and of the methods in the ServletConfig interface.
GenericServlet implements the log method, declared in the ServletContext
interface.
To write a generic servlet, it is sufficient to override the abstract service method.

javax.servlet.http.HttpServlet
public abstract class HttpServlet extends GenericServlet implements java.io.Serializable

HttpServlet defines a HTTP protocol specific servlet.


HttpServlet gives a blueprint for Http servlet and makes writing them easier.
HttpServlet extends the GenericServlet and hence inherits the properties
GenericServlet.

What is the difference between GenericServlet and HttpServlet?


GenericServlet:

GenericServlet belongs to javax.servlet package

GenericServlet is an abstract class which extends Object and implements Servlet,


ServletConfig and java.io.Serializable interfaces.

The direct subclass to GenericServlet is HttpServlet.It is a protocol-independent


servlet.

To write a GenericServlet you need abstract service() to be overridden.


HttpServlet:
HttpServlet belongs to javax.servlet.http package
This is an abstract class which extends GenericServlet and implements
java.io.Serializable
A subclass of HttpServlet must override at least one method of doGet(),
doPost(),doPut(), doDelete(), init(), destroy(), getServletInfo()

GenericServlet is an abstract class it can handle all types of protocols,but HttpServlet


handle only Http specific protocols.In generic we use only service method but Http we
use doGet() & doPost().but now a days we use only Http becoz WWW depends upon
Http PROTOCOLS.

Difference between doGet() and doPost()?


doGet()

doPost()

1 In doGet() the parameters are


In doPost(), on the other hand will
appended to the URL and sent along (typically) send the information
with header information.
through a socket back to the
webserver and it won't show up in the

URL bar.

The amount of information you can


send back using a GET is restricted
2
as URLs can only be 1024
characters.

You can send much more information


to the server this way - and it's not
restricted to textual data either. It is
possible to send files and even binary
data such as serialized Java objects!

doPost() provides information (such as


doGet() is a request for information;
placing an order for merchandise)
it does not (or should not) change
3
that the server is expected to
anything on the server. (doGet()
remember
should be idempotent)
4

Parameters are not encrypted

doGet() is faster if we set the


response content length since the
same connection is used. Thus
increasing the performance

doGet() should be safe without any


side effects for which user is held
responsible

7 It allows bookmarks.

Parameters are encrypted

doPost() is generally used to update or


post some information to the
server.doPost is slower compared to
doGet since doPost does not write the
content length
This method does not need to be
either safe
It disallows bookmarks

When to use doGet() and when doPost()?


Always prefer to use GET (As because GET is faster than POST), except
mentioned in the following reason:
If data is sensitive
Data is greater than 1024 characters
If your application don't need bookmarks.

.What are the differences between the ServletConfig interface and the
ServletContext interface?
ServletConfig
The ServletConfig interface is
implemented by the servlet container
in order to pass configuration
information to a servlet. The server
passes an object that implements the
ServletConfig interface to the
servlet's init() method.

ServletContext
A ServletContext defines a set of
methods that a servlet uses to
communicate with its servlet
container.

There is one ServletContext for the


There is one ServletConfig parameter
entire webapp and all the servlets in
per servlet.
a webapp share it.
The param-value pairs for
ServletConfig object are specified in
the <init-param> within the <servlet>
tags in the web.xml file

The param-value pairs for


ServletContext object are specified in
the <context-param> tags in the
web.xml file.

.What's the difference between GenericServlet and HttpServlet?


GenericServlet

HttpServlet

The GenericServlet is an abstract


class that is extended by HttpServlet
to provide HTTP protocol-specific
methods.

An abstract class that simplifies


writing HTTP servlets. It extends the
GenericServlet base class and
provides an framework for handling
the HTTP protocol.

The GenericServlet does not include


protocol-specific methods for
handling request parameters,
cookies, sessions and setting response
headers.

The HttpServlet subclass passes


generic service method requests to
the relevant doGet() or doPost()
method.

GenericServlet is not specific to any


protocol.

HttpServlet only supports HTTP and


HTTPS protocol.

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.

1- public class Cookie extends java.lang.Object implements java.lang.Cloneable


Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved
by the browser, and later sent back to the server. A cookie's value can uniquely identify a
client, so cookies are commonly used for session management.
2- getCookies
public Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this
request. This method returns null if no cookies were sent.
Returns:
an array of all the Cookies included with this request, or null if the request
has no cookies
3- addCookie
public void addCookie(Cookie cookie)
Adds the specified cookie to the response. This method can be called multiple
times to set more than one cookie.
Parameters:
cookie - the Cookie to return to the client

public String getName()


This method returns the name of the cookie. The name cannot be
changed after creation.

public String getValue()


This method gets the value associated with the cookie.
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)


This method sets the domain to which cookie applies, for
example tutorialspoint.com.

public String getDomain()


This method gets the domain to which cookie applies, for
example tutorialspoint.com.

public void setMaxAge(int expiry)


This method sets how much time (in seconds) should elapse
before the cookie expires. If you don't set this, the cookie will
last only for the current session.

public int getMaxAge()


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()


This method returns the name of the cookie. The name cannot be
changed after creation.

public void setValue(String newValue)


This method sets the value associated with the cookie.

public String getValue()


This method gets the value associated with the cookie.

public void setPath(String uri)


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()


This method gets the path to which this cookie applies.

10

public void setSecure(boolean flag)

This method sets the boolean value indicating whether the cookie
should only be sent over encrypted (i.e. SSL) connections.
11

public void setComment(String purpose)


This method specifies a comment that describes a cookie's
purpose. The comment is useful if the browser presents the
cookie to the user.

12

public String getComment()


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:
[ ] ( ) = , " / ? @ : ;
(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);

Program For Cookies


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

public class CookieExample extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// print out cookies
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
String name = c.getName();
String value = c.getValue();
out.println(name + " = " + value);
}
// set a cookie
String name = request.getParameter("cookieName");
if (name != null && name.length() > 0) {
String value =
request.getParameter("cookieValue");
Cookie c = new Cookie(name, value);
response.addCookie(c);
}
}
}

1. Overview of Cookies
Cookies are small bits of textual information that a Web server sends to a browser and
that the browser returns unchanged when visiting the same Web site or domain later. By
having the server read information it sent the client previously, the site can provide
visitors with a number of conveniences:
Benefits of Cookies
There are four typical ways in which cookies can add value to your site.
Identifying a user during an e-commerce session. This type of
short-term tracking is so important that another API is layered on top
of cookies for this purpose.

Remembering usernames and passwords. Cookies let a user log


in
to a site automatically, providing a significant convenience for users of
unshared computers.
Customizing sites. Sites can use cookies to remember user
preferences.
Focusing advertising. Cookies let the site remember which topics
interest certain users and show advertisements relevant to those
interests.

Identifying a user during an e-commerce session. Many on-line stores use a


"shopping cart" metaphor in which the user selects an item, adds it to his
shopping cart, then continues shopping. Since the HTTP connection is closed after
each page is sent, when the user selects a new item for his cart, how does the store
know that he is the same user that put the previous item in his cart? Cookies are a
good way of accomplishing this. In fact, this is so useful that servlets have an API
specifically for this, and servlet authors don't need to manipulate cookies directly
to make use of it.
Avoiding username and password. Many large sites require you to register in
order to use their services, but it is inconvenient to remember the username and
password. Cookies are a good alternative for low-security sites. When a user
registers, a cookie is sent with a unique user ID. When the client reconnects at a
later date, the user ID is returned, the server looks it up, determines it belongs to a
registered user, and doesn't require an explicit username and password.
Customizing a site. Many "portal" sites let you customize the look of the main
page. They use cookies to remember what you wanted, so that you get that result
initially next time.
Focusing advertising. The search engines charge their customers much more for
displaying "directed" ads than "random" ads. That is, if you do a search on "Java
Servlets", a search site can charge much more for an ad for a servlet development
environment than an ad for an on-line travel agent. On the other hand, if the
search had been "Bali Hotels", the situation would be reversed. The problem is
that they have to show a random ad when you first arrive and haven't yet
performed a search, as well as when you search on something that doesn't match
any ad categories. Cookies let them remember "Oh, that's the person who was
searching for such and such previously" and display an appropriate (read "high
priced") ad instead of a random (read "cheap") one.

Another Example for Creating Cookies Pogram


The cookies for first and last name.
// 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>");
}
}
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-installationdirectory>/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.
Program 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,
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>");
}
}
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:
1. Read an already exsiting cookie and store it in Cookie object.
2. Set cookie age as zero using setMaxAge() method to delete an existing cookie.
3. Add this cookie back into response header.
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>");
}
}

You might also like