COOKIES IN JAVA
Cookies are small pieces of information stored on the client's browser to maintain state between multiple requests. They are used to recognize users and store user-specific information. In Java, cookies are managed using the javax.servlet.http.Cookie class.
Creating and Using Cookies
To create a cookie, you instantiate the Cookie class with a name and a value. For example:
Cookie cookie = new Cookie("username", "JohnDoe");
To add the cookie to the response, use the addCookie method of the HttpServletResponse interface:
response.addCookie(cookie);
To retrieve cookies from a request, use the getCookies method of the HttpServletRequest interface:
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
String value = c.getValue();
// Use the value
}
}
Managing Cookie Attributes
Cookies have several attributes that can be set to control their behavior:
Example:
cookie.setMaxAge(3600); // 1 hour
cookie.setPath("/app");
cookie.setDomain("example.com");
cookie.setSecure(true);
Example Servlet Using Cookies
Here is a simple example of a servlet that sets and retrieves cookies:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Create a cookie
Cookie cookie = new Cookie("username", "JohnDoe");
cookie.setMaxAge(3600); // 1 hour
response.addCookie(cookie);
// Retrieve cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
out.println("Name: " + c.getName());
out.println("Value: " + c.getValue());
}
} else {
out.println("No cookies found");
}
}
}
Advantages and Disadvantages
Advantages:
Disadvantages: