- How to use Cookies in Java web application
- 1. How to create a cookie
- 2. How to read cookies
- 3. How to update a cookie
- 4. How to delete a cookie
- 5. Java Cookies Example Project
- Java Cookies Example
- Add Cookies
- Read Cookies
- Delete Cookies
- API References:
- Other Java Servlet Tutorials:
- About the Author:
- Accessing Cookies
- Retrieving Cookies
- Setting Cookies
- Running the Cookie Applet Example
- Running the Cookie Applet Example
- cookies in java
- 2 Answers 2
How to use Cookies in Java web application
In this tutorial, you will learn how to create, update, read and delete cookies in a Java web application.
A cookie is a small amount of data which is stored in the web browser and transferred between requests and responses through HTTP headers. A cookie has a name and value, plus option attributes like comment, path, domain, max age,… Cookies are commonly used to implement simple, temporary data storage on the client side, such as session management, remember password, shopping cart items, etc.
In Java Servlet API, the javax.servlet.http. Cookie class represents a cookie.
1. How to create a cookie
String name = "Cookie name"; String value = "Cookie value"; Cookie cookie = new Cookie(name, value);
This will send appropriate HTTP headers to the client, and the browser stores the cookie on user’s computer.
Besides the mandatory attributes name and value, you can also specify additional information for a cookie using the following methods:
setComment (String) : specifies a comment that describes the cookie’s purpose. For example:
cookie.setComment("This cookie stores username of the customer");
setDomain (String) : specifies the domain name within which this cookie is visible. By default, cookies are only returned to the server that sent them. So setting the domain name makes the cookies available for different servers under the same domain name. For example:
cookie.setDomain(".codejava.net");
This cookie will be available for all servers under the domain codejava.net. Note that the domain name should starts by a dot. The following example sets domain of the cookie to localhost:
setHttpOnly (boolean) : if set to true, Javascript can’t read this cookie on the client side, which can prevent some kinds of cross-site scripting attacks. For example:
setMaxAge (int) : specifies how long the cookie is stored in user’s computer, in seconds. If not set, the cookie is deleted when the web browser exits. For example:
cookie.setMaxAge(7 * 24 * 60 * 60);
This sets the cookie’s life is 7 days (= 24 hours x 60 minutes x 60 seconds) and it is still stored on the user’s computer when the browser exists.
setPath (String) : use this method if you want to restrict the cookie to be available for a certain path (and its subpaths) on the server. For example:
setSecure (boolean) : if set to true, the cookie is sent from the browser to the server only when using secure protocol (HTTPS or SSL). Default is false.
2. How to read cookies
To read cookies sent from the browser to the server, call getCookies() method on a HttpServletRequest object in a Java servlet class. This method returns an array of Cookie objects that are visible to the current request. For example, the following code read all cookies and print its names and values:
Cookie[] cookies = request.getCookies(); PrintWriter writer = response.getWriter(); for (Cookie aCookie : cookies) < String name = aCookie.getName(); String value = aCookie.getValue(); writer.println(name + " brush:java">String username = null; for (Cookie aCookie : cookies) < String name = aCookie.getName(); if (name.equals("username")) < username = aCookie.getValue(); break; >>
3. How to update a cookie
To update an existing cookie, you need to create a new cookie with the same name and add it to the response. For example:
String name = "Cookie name"; String value = "New value"; Cookie cookie = new Cookie(name, value); response.addCookie(cookie);
4. How to delete a cookie
To remove a cookie from the browser’s cache, you need to create a new cookie with the same name, set its max age to zero and add it to the response. For example:
Cookie cookie = new Cookie("username", ""); cookie.setMaxAge(0); response.addCookie(cookie);
5. Java Cookies Example Project
The following sample project helps you learn how to use cookies in a Java web application. Create a simple Java web project. Code the home page ( index.jsp ) as follows:
Java Cookies Example
Add Cookies
Read Cookies
Delete Cookies
Create the AddCookiesServlet class to handle the hyperlink ‘Add Cookies’ with the following code:
package net.codejava; import java.io.IOException; 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("/add_cookies") public class AddCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; private static int cookieCount; public AddCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String name = "Cookie" + (++cookieCount); String value = String.valueOf(System.currentTimeMillis()); Cookie cookie = new Cookie(name, value); response.addCookie(cookie); response.getWriter().println("A cookie has been created successfully!"); >>
Create the ReadCookiesServlet class to read all cookies visible to the application, with the following code:
package net.codejava; import java.io.IOException; import java.io.PrintWriter; 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("/read_cookies") public class ReadCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; public ReadCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter writer = response.getWriter(); Cookie[] cookies = request.getCookies(); if (cookies == null) < writer.println("No cookies found"); >else < writer.println("Number of cookies: " + cookies.length); for (Cookie aCookie : cookies) < String name = aCookie.getName(); String value = aCookie.getValue(); writer.println(name + " lazy" style="display: block; margin-left: auto; margin-right: auto;" src="https://mail.codejava.net/images/articles/javaee/servlet/cookie/Java_test_read_cookies.png" alt="Java test read cookies" width="600" height="211" />As you can see, the first cookie with name JSESSIONID is created by the server to manage user’s session.And to test removal of cookies, create the DeleteCookiesServlet class with the following code:package net.codejava; import java.io.IOException; import java.io.PrintWriter; 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("/delete_cookies") public class DeleteCookiesServlet extends HttpServlet < private static final long serialVersionUID = 1L; public DeleteCookiesServlet() < >protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter writer = response.getWriter(); Cookie[] cookies = request.getCookies(); if (cookies != null) < for (Cookie aCookie : cookies) < aCookie.setMaxAge(0); response.addCookie(aCookie); >writer.println("All cookies have been deleted!"); > else < writer.println("No cookies found"); >> >API References:
Other Java Servlet Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Accessing Cookies
You can set and retrieve cookies in your rich Internet application (RIA). Cookies can enhance the capabilities of your RIA. For example, consider the scenario where you have applets on various web pages. An applet on a web page cannot directly access or share information with an applet on another web page. In this scenario, cookies provide an important connection between applets and help one applet pass information to another applet on a different web page. Java Web Start applications can also use cookies to store information on the client.
The Cookie Applet example has a CookieAccessor class that retrieves and sets cookies.
Retrieving Cookies
The following code snippet shows the getCookieUsingCookieHandler method of the CookieAccessor class:
public void getCookieUsingCookieHandler() < try < // Instantiate CookieManager; // make sure to set CookiePolicy CookieManager manager = new CookieManager(); manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(manager); // get content from URLConnection; // cookies are set by web site URL url = new URL("http://host.example.com"); URLConnection connection = url.openConnection(); connection.getContent(); // get cookies from underlying // CookieStore CookieStore cookieJar = manager.getCookieStore(); List cookies = cookieJar.getCookies(); for (HttpCookie cookie: cookies) < System.out.println("CookieHandler retrieved cookie: " + cookie); >> catch(Exception e) < System.out.println("Unable to get cookie using CookieHandler"); e.printStackTrace(); >>The CookieManager class is the main entry point for cookie management. Create an instance of the CookieManager class and set its CookiePolicy . Set this instance of the CookieManager as the default CookieHandler .
Open a URLConnection to the website of your choice.
Next, retrieve cookies from the underlying CookieStore by using the getCookies method.
Setting Cookies
The following code snippet shows the setCookieUsingCookieHandler method of the CookieAccessor class:
public void setCookieUsingCookieHandler() < try < // instantiate CookieManager CookieManager manager = new CookieManager(); CookieHandler.setDefault(manager); CookieStore cookieJar = manager.getCookieStore(); // create cookie HttpCookie cookie = new HttpCookie("UserName", "John Doe"); // add cookie to CookieStore for a // particular URL URL url = new URL("http://host.example.com"); cookieJar.add(url.toURI(), cookie); System.out.println("Added cookie using cookie handler"); >catch(Exception e) < System.out.println("Unable to set cookie using CookieHandler"); e.printStackTrace(); >>As shown in Retrieving Cookies, the CookieManager class is the main entry point for cookie management. Create an instance of the CookieManager class and set the instance as the default CookieHandler .
Create the desired HttpCookie with the necessary information. In our example, we have created a new HttpCookie that sets the UserName as John Doe .
Next, add the cookie to the underlying cookie store.
Running the Cookie Applet Example
To access cookies, you must sign your RIA JAR file and request permission to run outside of the security sandbox. See the documentation for the jarsigner tool to learn how to sign JAR files. See Security in Rich Internet Applications for information on requesting permissions.
Download source code for the Cookie Applet example to experiment further.
Note: You must sign your RIA JAR file in order to access cookies. See the documentation for the jarsigner tool to learn how to sign JAR files.
Running the Cookie Applet Example
Open AppletPage.html in a browser to run the Cookie Applet example. Check the Java Console log for details of cookies that have been set and retrieved. You should see the following output in the Java Console log (session details vary).
=== Access cookies using CookieHandler === CookieHandler retrieved cookie: JSESSIONID=3bc935c18b8d36319be9497fb892 CookieHandler retrieved cookie: JROUTE=eKVJ4oW0NOer888s Added cookie using cookie handler .Note: If you don't see the applet running, you need to install at least the Java SE Development Kit (JDK) 6 update 10 release.
Note: If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.
Download source code for the Cookie Applet example to experiment further.
cookies in java
I am having problem in java to pass cookie from client to server. In java I know a method "setProperty" which pass cookie but it takes parameter "Cookie name" and "Cookie value" separately.But cookies are sent in one string. Is it ok to pass cookie in this process?? Most of the cookies are usually contains not only name , values but also domain and expire date . Is it right to skip those domain and expire date and return the cookie only with name and value ?? I want to log in any cookie site like web browsers.
2 Answers 2
For a java servlet you use javax.servlet.http.Cookie to create cookies. Even if the constructor accept name and value parameters that doesn't mean that those are the only parameters that you can set.
A cookie object has few setters like setDomain or setMaxAge to define your cookie. (see http://download.oracle.com/javaee/5/api/javax/servlet/http/Cookie.html)
Finally you can add those cookies to the response object.
Do I have to create cookie ?? Because I only want to get the cookie from the header of previous html page and send it back to server to log in like a browser .
The best way to check this is to check the request object, if there is no cookie there, then you have to create a new one and add it to the request object.
A cookie is a token which contains sub information in the form key-value pair,
it is generated by the server and is made available to client So that a client sent it back to the server as part of sub-sequence request. It provides a simple mechanism of maintaining user information between request.
Cookies can be two types- 1) persistent Cookies 2) Non persistent cookies
1) Persistent cookies remain value for multiple session, they are stored in a text file by the browser on the client machine.
2) Nonpersistent cookies remain valid only for a single session. They are stored by the browser delete cache, they are discarded when the browser is closed. By default each cookie non- persistent.
Cookies in Java:
Servlet API provide a class name cookies for represents these(cookies) as objects. Cookies object can be created as follows —
Public cookie(String name, String value);
Commonly used methods of cookies class-
getName() - Public String getName();
is used to obtain value of cookie.
setMaxAge() - Public void setMaxAge(int seconds);
is used to set the value for time of cookie, when valid time is associated to a cookie, the cookie become persistent.
addCookie()- public void addCookie(Cookie ch);
http servlet response is used to send a cookie as part of the response.
getCookies() - Public Cookie[] getCookies();
method of http servlet request is used to received cookies which are send by browser as part of request.
Below java Class is used for set cookie in browser-
public class CookieSetExample extends HttpServlet < public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException< String name= req.getParameter("name"); Cookie ck = new Cookie("user",name); ck.setMaxAge(600); response.addCookie(ck); res.setContentType("text/html"); PrintWriter out = res.getWriter(); >
Below java Class is used for get cookies from browser-
public class CookieGetExample extends HttpServlet < public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException< String name= "Gust"; Cookie ck[] = getCookies(); if(Optional.ofNullable(ck).ifPresent()) < name = ck[0].value(); >res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(""); >
Limitations of Cookie-
1) A cookie can be disabled in the browser, i.e. It is not reliable.
2) Persistent doesn’t differentiate between user and the server.