Java Servlet addCookie Example

In this tutorial you will learn how to add a cookie in a response and how to get form the request.

Java Servlet addCookie Example

In this tutorial you will learn how to add a cookie in a response and how to get form the request.

Java Servlet addCookie Example

Java Servlet addCookie Example

In this tutorial you will learn how to add a cookie in a response and how to get form the request.

To add a cookie in response there is a method addCookie() of HttpServletResponse interface that adds a specified cookie in response. And to get a cookie there is a method getCookies() of HttpServletRequest interface that returns all the Cookie objects, in an array, sent by a client with the request.

Example :

Here I am giving a simple example which will demonstrate you to how to use these methods. In this example I am trying to do subtraction the two numbers at the same servlet and using the same these numbers want to add on another servlet. For this I have taken a ServletConfig and ServletContext references which will help in to carry the requested value from one servlet to another servlet. But the main thing is that I want to adds these value only when the user is valid for this I create and add a cookie in response object of CookieExample1Sub.java example and in CookieExample1Add.java gets the cookie and matched with the name.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Demo Example of Cookie</title>
</head>
<body>
<form action="CookieExample1Sub">
<table>
<tr>
<td>Enter Your Name</td><td><input type="text" name="name"/></td>
</tr>
<tr>
<td>First Number </td><td><input type="text" name= "firstNumber"/></td>
</tr>
<tr>
<td>Second Number </td> <td><input type="text" name= "secondNumber"/></td>
</tr>
<tr>
<td></td><td><input type="submit" value="subtract"/></td>
</tr>
</table>
</form>
</body>
</html>

CookieExample1Sub.java

package roseindia.Cookie;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CookieExample1Sub")
public class CookieExample1Sub extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name= request.getParameter("name");
int firstNumber= Integer.parseInt(request.getParameter("firstNumber"));
int secondNumber= Integer.parseInt(request.getParameter("secondNumber"));
int result;
ServletConfig config= getServletConfig();
ServletContext context= config.getServletContext();
context.setAttribute("FirstNumber", firstNumber);
context.setAttribute("SecondNumber", secondNumber);
Cookie cookieName= new Cookie("User", name);
response.addCookie(cookieName);

response.setContentType("text/html");
PrintWriter out= response.getWriter();
if(firstNumber>secondNumber)
{
result= firstNumber-secondNumber;
out.println("Subtraction of two numbers are : "+result);
}
else
{
result= secondNumber-firstNumber;
out.println("Subtraction of two numbers are : "+result);
}

out.println("<html><body>");
out.println("<form action=\"CookieExample1Add\">");
out.println("To add these numbers click on \"add\"button.");
out.println("<br><input type=\"submit\" value=\"add\"/>");
}

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

CookieExample1Add.java

package roseindia.Cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CookieExample1Add")
public class CookieExample1Add extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
int number1 = (Integer) context.getAttribute("FirstNumber");
int number2 = (Integer) context.getAttribute("SecondNumber");
int firstNumber = number1;
int secondNumber = number2;
int result;

response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c = null;
Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
c = cookies[i];
String name = c.getValue();
if (name.equals("bipul")) {
result = firstNumber + secondNumber;
out.println("Hi "+name+" your result is : "+result);
} else {
name = c.getValue();
out.println("Sorry " + name
+ ", your are not allowed to add these numbers");
}
}

}

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

}

Output :

When you will execute the above example you will get the output as :

when you will enter the value like the below and will click on "subtract" button :

You will get the output as :

When you will click on "add" button you will get the output as :

When you will enter the value as and click on "subtract" button :

You will get the output as :

And when you will click on "add" button you will get the output as :

Download Source Code