Set and read cookies within JSP

How to read and create cookies in Java within JSP pages.

This example will write the value sel cookie “username”. If the cookie does not exist it will be created and will be visible once the page is reloaded.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>JSP Cookie example</title>
  <meta name="description" content="Setting and Reading Cookies Within JSP">
  <meta name="author" content=".Maui">
  <link rel="stylesheet" href="https://cdn.dotmaui.com/dotmaui/css/dark.css">

</head>
<body>
  
<%
Cookie[] cookies = request.getCookies();
boolean cookieExists = false;

for(int i = 0; i < cookies.length; i++) { 
    Cookie c = cookies[i];
    if (c.getName().equals("username")) {
        out.println("usernale = " + c.getValue());
        cookieExists = true;
    }
}  

if (!cookieExists) {
    Cookie c = new Cookie("username", ".maui");
    c.setMaxAge(24*60*60);
    c.setPath("/");
    response.addCookie(c); 
}
%> 

</body>
</html>

Leave a Comment

Your email address will not be published. Required fields are marked *