Cookies in Servlets are used for session management. They are small pieces of information stored as text strings on the client’s browser. When a servlet sends a cookie to the browser, the browser stores it and sends it back with every subsequent request to the server. This allows the server to recognize the client and maintain session information.
Here’s a simple example of how cookies are used in a servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class CookieExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create a cookie
Cookie firstName = new Cookie("first_name", request.getParameter("name"));
// Set expiry date after 24 hours
firstName.setMaxAge(60*60*24);
// Add cookie to the response
response.addCookie(firstName);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using Cookies to Track User";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h2 align=\"center\">" + title + "</h2>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("name") + "\n" +
"</ul>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
In this example, when a user submits their name through a form, the doGet
method is called. A cookie named first_name
is created with the value of the user’s name. This cookie is then added to the response and sent to the client’s browser. The browser will store this cookie and send it back with every subsequent request to the server. The server can then use this cookie to recognize the user.
The setMaxAge
method is used to set the expiration time for the cookie. In this case, it’s set to 24 hours. If you want the cookie to persist for the current session only, you can set its age to -1
.
The doPost
method here simply calls the doGet
method, which means this servlet will handle GET
and POST
requests in the same way.
This is a basic example to illustrate the concept of cookies in servlets.