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 = "CookieExpirationServlet", urlPatterns = "/cookie-expiration")
public class CookieExpirationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
if (username != null) {
Cookie cookie = new Cookie("username", username);
// Set the cookie age to 600 seconds (10 minutes). Setting the age
// to 0 will delete the cookie while giving it a negative value will
// not store the cookie, and it will be deleted when the browser is
// closed.
cookie.setMaxAge(600);
response.addCookie(cookie);
}
}
}
Maven dependencies
<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 handle cookies using Jakarta Servlet API? - April 19, 2025
- How do I set response headers with HttpServletResponse? - April 18, 2025
- How do I apply gain and balance using FloatControl? - April 18, 2025