How to set and get cookies in JSP and servlet? In this JSP and Servlet Tutorial, Let’s create an example to set and get cookies in JSP and Servlet. In real-time, when you visit any website. You get the message “accept cookies” and you just click on agree but do you know what is it? First, let’s see what is cookies.
What is Cookies?
A cookie is a piece of data from a website, Stored in the user’s computer while users are browsing the web. It is generally used to keep track of users’ activity. It also helps website admin to keep track of unique users visiting their website due to unique IDs.
As we know, we create a web application using web technology like JSP and Servlet. So, here we will see how the concept of cookies works. Here, we will see an example of how to get cookies in JSP and Servlet. Read more on Handle Cookies on the JSP page
How to Set Cookies in Servlet
Create an object of Cookie Cookie cookie = new Cookie(cname, value);
that will take two parameters, the first Name of the cookies and the second value of the cookie.
Now Add this cookie object with a response by using response.addCookie(cookie);
// Create a cookie Cookie cookie = new Cookie(cname, cvalue); // add cookies to response object response.addCookie(cookie);
How to Get Cookies in JSP
Now get the cookies on the JSP page. as you know in the above example, we just add a cookie object with the response. Now on JSP, We will get the same object in the form of a request by using request.getCookies();
that will return an array of cookies.
Create a for loop to retrieve the values from the cookies array and get the name of cookies by using cookie.getName();
and get the value by using cookie.getValue();
/* Now, we will get all the cookie on this page */ Cookie[] cookies = request.getCookies(); for(Cookie cookie: cookies) { String cName = cookie.getName(); String cValue = cookie.getValue(); }
Use cookies in Java web using JSP and Servlet
Create a maven project and index.jsp page to demonstrate how we set cookies in servlet and get cookies on the jsp page.
Create Maven Project
Create a Maven project in Eclipse IDE. Following are steps to create a simple JSP and Servlet Maven project in Eclipse.
- Open Eclipse.
- Go to File > New > Other > Maven project > Next > Next > select maven.archetype-webapp > Next Enter Artefact Id > Finish.
Note: In case you face an error during project creation, just check this article https://codedec.com/tutorials/how-to-create-maven-project-and-design-a-mvc-framework/
Create View(index.jsp) to get cookies
Create index.jsp page to add cookie and value as shown below.
<html> <head> <title>Cookie Handling</title> <link href="https://fonts.googleapis.com/css2?family=Playfair+Display&display=swap" rel="stylesheet"> <style type="text/css"> .div1{ height: 200px; width:50%; border: 1px solid; background-color: #fff; margin-right: 50%; } .div2{ height: 350px; width:50%; border: 1px solid; background-color: #fff; margin-right: 50%; } label{ font-family: 'Playfair Display', serif; height: 20px; font-weight: bold; margin-top: 50px; } form{ margin-top: 50px; margin-right: 50px; } button[type="submit"]{ background-color: #fff; font-size: 20px; color: red; height: 25px; } </style> </head> <body style="background: linear-gradient(#ddd6f3,#faaca8)"> <div class="div1"> <form action="CookieServlet" method="post"> <label>Cookie Name</label> <input type="text" name="cname"> <br><br> <label>Cookie Value</label> <input type="text" name="cvalue"> <br><br> <button type="submit">Add Cookie</button> </form> </div> <br> <div class="div2"> <h2>Cookies...</h2> <table border="1" cellpadding="10"> <tr> <td>Cookie Name </td> <td>Cookie Value</td> </tr> <% /* Now, we will get all the cookie on this page */ Cookie[] cookies = request.getCookies(); for(Cookie cookie: cookies){ String cName = cookie.getName(); String cValue = cookie.getValue(); %> <tr> <td><%= cName%></td> <td><%= cValue%></td> </tr> <%} %> </table> </div> </body> </html>
Here, get all the cookies on the page. Iterate over it and get the name and value using the request object
Create Servlet Class to set cookies
Create Servlet class to take both cookie name and value from the JSP page.
package in.codebun; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public CookieServlet() { // TODO Auto-generated constructor stub } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cname = request.getParameter("cname"); String cvalue = request.getParameter("cvalue"); // Create a cookie Cookie cookie = new Cookie(cname, cvalue); // add cookies to response object response.addCookie(cookie); //redirect to index page response.sendRedirect("index.jsp"); } }
- Here, get the cookie name, cookie value from the JSP page using the request object.
- Now, create the object of the Cookie class.
- Next, add the cookie to the response object.
- At last, redirect to index.jsp page.
At last, run the application on the server and see the following output
Thus, if you relaunch your application, you will find the same cookie name and cookie value present. Thus, in this way, we learn How to get cookies in JSP and Servlet.