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">
  <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="">

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");


Leave a Comment

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