A cookie is a piece of information sent to a browser by a Web Server. The browser then returns that information to the Web server. This is how some Web pages remember your previous visits; for example, an e-commerce website might use a cookie to remember which items you’ve placed in your online shopping cart. Cookies can also store user preference information, login data, etc.
Here is an example to send a cookie in the HTTP response object to the client browser.
package org.kodejava.servlet;
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(name = "CookieServlet", urlPatterns = "/test-cookie")
public class WriteCookieExample extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// Send a cookie named username to the client. There are some others
// properties that we can set before we send the cookie, such as comments,
// domain name, max age, path, a secure flag, etc.
Cookie cookie = new Cookie("username", "jduke");
response.addCookie(cookie);
}
}
Maven dependencies
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024