A Servlet in Java is a server-side program that handles client requests and responses in a web application. Cookies in a servlet are typically used for storing small pieces of data on the client’s browser, which can later be retrieved when needed. A cookie is a small piece of information sent from the server to the client's browser, which stores it and sends it back with subsequent requests.
Below is a basic example of how to work with cookies in a Java Servlet:
Steps:
- Set a Cookie (Sending from the server to the client)
- Read a Cookie (Retrieving the cookie from the client on subsequent requests)
Example Servlet for Cookies:
1. Setting a Cookie in the Servlet:
2. Reading a Cookie in the Servlet:
Key Points:
- Setting a Cookie: You use
response.addCookie(Cookie cookie)
to send the cookie from the server to the client. You can also set expiration time usingcookie.setMaxAge(int seconds)
. - Reading a Cookie: You retrieve cookies with
request.getCookies()
, which returns an array ofCookie
objects. You can then iterate through them to find a specific cookie. - Cookie Expiration: A cookie will expire after the time specified in
setMaxAge
. If you set it to0
, the cookie is deleted. - Cookie Attributes: You can set additional attributes like path, domain, secure flag, and HttpOnly flag.
Notes:
- Cookies are stored on the client's browser, and they can be viewed or deleted by the user. Therefore, they are not meant to store sensitive or large amounts of data.
- If the browser does not have cookies enabled, the servlet will not be able to store or retrieve cookies.
Comments
Post a Comment