Bootstrap FreeKB - Java - Cookies
Java - Cookies

Updated:   |  Java articles

You may want to first read about the difference between a session and a cookie.

This assumes you have created your first dynamic web project in Eclipse. There are two main approaches to use cookies in Eclipse. If your Java application is running on an application server, such as Tomcat or WebSphere, and the application server is configured to create a cookie, such as the popular JSESSIONID cookie, you should be able to use the cookie that is created by the application server. Or, you can create cookies in Eclipse.


Create cookie in Java

Create a new HTML page, such as SendData.html, and place the following markup inside of the <body> tags.

<form action="GetCookie.jsp" method="post">
  What is your name? <input type="text" name="myname"><br />
  <input type="submit" value="Submit">
</form>

 

After deploying the app to your application server (Websphere, Tomcat), navigating to www.example.com/yourapp/SendData.html will present you with the form that is used to send data to the servlet that will create the cookie. 

 

Create a new servlet. Since the form action in the HTML page posts to "CreateCookie", we would name our servlet CreateCookie. Import the following modules.

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;

 

Add the following inside of the doPost block. This will create a cookie called myname, the value of the cookie will be obtained from whatever was entered in the form on the SendData.html page, and the servlet will immediately redirect to the GetCookie.jsp page.

Cookie loginCookie = new Cookie("myname",myname);
response.addCookie(loginCookie);
response.sendRedirect("GetCookie.jsp");

 

Now, when entering Bugs as your name, a cookie called myname will be created where the content is Bugs.

 


Getting cookies in a JSP page

Adding the following markup inside of the body tags of a JSP page will display the name and value of each cookie associated with the site. 

<%
// Create variables
String cookieName = null;
String cookieValue = null;

//Create a variable named cookies that contains all the cookies
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies){
  cookieName = cookie.getName();
  cookieValue = cookie.getValue();
  out.println("Value <b>" + cookieValue + "</b> obtained from the cookie named <b>" + cookieName + "</b><br />");
}
%>

 

The JSP page should now display the name and value of each cookie associated with your site. In this example, both the JSESSIONID cookie created by the application server and the myname cookie created in the Java app are displayed.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 8d7f8f in the box below so that we can be sure you are a human.