Create Cookie Example in Java

A cookie lets you save information to the browser that you can use to your server. With cookies, you can define some parameters eg. the desired preference of the user to a website. Cookies are sent to your server whenever you make a request. Think cookies like temporary storage of parameters or information that you can get, retrieve, and check.

Here is a simple cookie example that will be added to the response and to the user’s browser.

Creating a Cookie

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(HttpServletResponse response) {
    //create a cookie with name 'website' and value 'javapointers'
    Cookie cookie = new Cookie("website", "javapointers");
    //set the expiration time
    //1 hour = 60 seconds x 60 minutes
    cookie.setMaxAge(60 * 60);
    //add the cookie to the  response
    response.addCookie(cookie);
    //return the jsp with the response
    return "home";
}

Reading a Cookie

@RequestMapping(value = "/home/cookie", method = RequestMethod.GET)
public String readCookie(HttpServletRequest request) {
    //get all cookies
    Cookie[] cookies = request.getCookies();
    //iterate each cookie
    for (Cookie cookie : cookies) {
        //display only the cookie with the name 'website'
        if (cookie.getName().equals("website")) {
            System.out.println(cookie.getValue());
        }
    }
    return "home";
}

Checking your browser

Below, we can verify that our cookie has been successfully added to the browser.

cookie
Share this tutorial!