Servlet Tutorial
Cookies are small pieces of information that a server sends to the client, and the client sends them back to the server with every subsequent request. They're commonly used for session management, personalization, and tracking.
In Java servlets, you can use the javax.servlet.http.Cookie
class to create and read cookies.
Here's a brief tutorial on how to handle cookies in a Java Servlet:
1. Creating a Cookie
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SetCookieServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Create a cookie Cookie userName = new Cookie("user", "John Doe"); // Set expiry date after 24 Hrs for this cookie. userName.setMaxAge(60*60*24); // Add the cookie to the response response.addCookie(userName); } }
In this example, we're creating a new cookie with the name "user" and the value "John Doe". We then set the cookie's maximum age to 24 hours (in seconds), and add the cookie to the HTTP response with response.addCookie(userName)
.
2. Reading Cookies
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class GetCookieServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); String username = null; if(cookies !=null){ for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { username = cookie.getValue(); } } } if (username != null) { out.println("Hello, " + username); } else { out.println("No username found."); } } }
In this example, we're getting all the cookies associated with the client's request with request.getCookies()
. We then iterate over the cookies to find the one with the name "user" and print its value to the response.
Note that cookies are associated with the domain and path that created them. If you're testing on localhost, make sure to use the same domain and port for both the servlet that sets the cookie and the servlet that reads the cookie.
Remember that cookies are sent with every HTTP request, so they should not be used to store sensitive information or large amounts of data. If you need to store such data, consider using HTTP sessions or a database instead.
Setting and getting cookies in Servlet: Set a cookie in the response and retrieve it from the request.
Cookie cookie = new Cookie("username", "JohnDoe"); response.addCookie(cookie); // Retrieving cookies Cookie[] cookies = request.getCookies();
Servlet cookie attributes: Set attributes such as name, value, and domain for a cookie.
Cookie cookie = new Cookie("username", "JohnDoe"); cookie.setDomain(".example.com");
Cookie expiration in Servlet: Set the expiration time for a cookie.
Cookie cookie = new Cookie("username", "JohnDoe"); cookie.setMaxAge(60 * 60 * 24); // 1 day
Servlet cookie domain and path: Define the domain and path for which the cookie is valid.
Cookie cookie = new Cookie("username", "JohnDoe"); cookie.setDomain(".example.com"); cookie.setPath("/app");
Secure cookies in Java Servlet: Mark a cookie as secure to be transmitted only over HTTPS.
Cookie cookie = new Cookie("username", "JohnDoe"); cookie.setSecure(true);
HttpOnly cookies in Servlet: Set the HttpOnly attribute to prevent access via JavaScript.
Cookie cookie = new Cookie("username", "JohnDoe"); cookie.setHttpOnly(true);
Deleting cookies in Java Servlet: Remove a cookie by setting its maxAge to 0.
Cookie cookie = new Cookie("username", ""); cookie.setMaxAge(0); response.addCookie(cookie);
Servlet cookie session management: Use cookies for session management by setting session-related information.
Cookie sessionCookie = new Cookie("sessionID", "123456"); response.addCookie(sessionCookie);
Persistent cookies in Java Servlet: Create cookies with a longer expiration for persistence.
Cookie persistentCookie = new Cookie("preferences", "darkMode"); persistentCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days response.addCookie(persistentCookie);
Managing multiple cookies in Servlet: Handle multiple cookies in the request and response.
Cookie cookie1 = new Cookie("user", "Alice"); Cookie cookie2 = new Cookie("language", "en"); response.addCookie(cookie1); response.addCookie(cookie2); // Retrieve multiple cookies Cookie[] cookies = request.getCookies();
Cookie encoding and decoding in Servlet: Encode and decode cookie values to handle special characters.
String encodedValue = URLEncoder.encode("special#chars", "UTF-8"); Cookie cookie = new Cookie("specialCookie", encodedValue); // Decode String decodedValue = URLDecoder.decode(cookie.getValue(), "UTF-8");