Introduction
This article explains cookies in Java. NetBeans IDE is used for sample example. This article also explains other terms, like its working process, how to create cookies, the method of cookies and understanding them by an example.
What Cookies are
Cookies represent the information in the form of key-value pairs. This information is sent by the server to the client machine as part of a response. So that the client can provide it to the server as part of subsequent requests. Cookies provide a simple mechanism for maintaining user information between requests.
Cookies are of the following two types:
- Persistent
- Non-persistent
Persistent cookies remain valid for multiple sessions. They are stored in a text file on a client machine by the browser.
Non-persistent cookies remain valid only for a single session. They are discarded when the session is completed.
By default all cookies are non-persistent.
Working process
1.0: First request (request data).
1.1: Response (request content + cookies).
1.2: Content are displayed.
1.3: Cookies are stored in cache.
2.0: Subsequent request (cookies stored in cache).
Packaging class
javax.servlet.http.Cookie is the package containing all the method for cookies.
Use the following to create a cookie object:
public Cookie(String name, String value);
The following are some commonly used methods of cookies.
1. getName()
Obtains the name of the cookie.
Syntax
public String getName();
2. getValue()
Obtains the value of cookie.
Syntax
public String getValue();
3. setMaxAge()
Specifies the time for which a cookie remains valid. When validity is associated with a cookie it becomes persistent.
Syntax
public void setMaxAge(int expiry);
4. addCookie()
A HttpServletResponse interface method sent as a part of a response.
Syntax
public void addCookie(Cookie ck);
5. getCookies()
A HttpServletResponse interface method to obtain the cookies sent by the client as part of a response.
Syntax
public Cookie[] getCookies();
Advantages
- They are maintained in the client machine.
- Uses the simplest technique for maintaining the state.
Disadvantages
- We can sent only textual components in our cookie object.
- It works only when cookies are enabled in the client browser.
Let's see an example
Understand the following scenario.
We are creating a website but for some reasons this site is under construction, in other words the site is not ready to display. But we want to show the module of our website to the user. So what we can do is we can create an interface in which we show the full module of our website to the users but if he accesses those parts that are not developed yet then we pass the message to the users "Welcome User_Name, this site is under construction, please visit again thanks for visiting". That message passing is done using cookies, the role of cookies is to remember the user name, create session, etcetera.
In the following example we show a demo of this type of problem. In this we create an interface in which the user enters the website and clicks on a link and he suddenly gets the message "Welcome User_Name, this site is under construction please visit again. Thanks for visiting".
Now we need to perform the following procedure.
Step 1
Open the NetBeans IDE.
Step 2
Choose "Java Web" -> "Web Application" then click on "Next", as shown below.
Step 3
Now type your project name and click on "Next".
Step 4
Choose your server and click on "Finish" as shown below.
Step 5
Now delete the "index.jsp" file and create a new HTML file with the name "index.html" as shown below.
Step 6
Now provide the following code in "index.html".
<!DOCTYPE html>
<html>
<body>
<form action="FirstServlet" method="post">
Enter Name:<input type="text" name="uname"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Step 7
Now create a new servlet with the name "FirstServlet" using:
Right-click on your project then select "New" -> "Servlet" as shown below.
Step 8
Type your servlet name as "FirstServlet" and click on "Choose the checkbox for adding it to XML" then click on "Finish" as shown below.
Step 9
Now provide the following code for it.
FirstServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class FirstServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("uname");
out.println("Welcome " + username);
Cookie cke = new Cookie("name", username);
response.addCookie(cke);
//Creating a new submit button for next servlet
out.println("<form action='SecondServlet' method='post'>");
out.println("<input type='submit' value='submit'>");
out.println("</form>");
out.close();
}
}
Step 10
Create another servlet with the name "SecondServlet" and provide the following code for it.
SecondServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SecondServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie cke[] = request.getCookies();
out.println("Welcome " + cke[0].getValue());
out.println("<p>This site is under construction please visit again. Thanks for visiting<p>");
out.close();
}
}
Step 11
Check your "web.xml" file to ensure it is the same as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Step 12
Now your project is ready to run. Run your project and see the output as in the following:
Now the result of passing the name "Sandeep" is shown below.
Now click on the "Submit" button and see the output, as shown below.
Note:
In this output we reach to FirstServlet, in other words we assume that the user logs into our web site. Now he/she starts using our web site functionality. In this example we provide a "Submit" button when the user clicks on this button a message is generated for them, as shown below.
Note:
Now the main work of the cookie starts in this output. The cookie stored the name of the user that was provided by the user the first time they logged into our web site (since we assume that our index page is a kind of web site). Then the advantage of the cookie is that whenever we need to process a username then we catch the name of the user from the cookies and use it. So in the same way in SecondServlet we don't pass the user name again, we just use it by creating a cookies object.