Skip to main content

Command Palette

Search for a command to run...

Cookies 101

Published
1 min read
S

I love learning about technology and sharing that with others

Motivation

Figuring out how cookies works and stored in the browser and why it is getting corrupted.

Who Creates Cookies ?

most of the time it is the resposibility of the backend to create the cookies and send it in the response.

browser send the cookies back to the server with the next request to the same server

Without cookies the server would have thought that all the requests as the new user.

Backend application can be : java,flask,node js

Webserver : apache, nginx How backend set the cookies ?

So backend will set the cookie in the response using the http header Set-Cookie , by adding key value pair


Set-Cookie: myfirstcookie=somecookievalue

Simple Example how to set cookies using springboot

Very simple controlller

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


    @GetMapping("/addCookie")
    public String addCookies(HttpServletResponse response) {

        Cookie cookie=new Cookie("password", "sandy");
        response.addCookie(cookie);

        return "add cookie is successfull";
    }

simple Example of reading cookies

@GetMapping("/readcookie")
public String readCookies(HttpServletRequest request){

    Cookie[] cookies=request.getCookies();

    if(cookies!=null) {
        for(Cookie a: cookies) {
            System.out.println(a.getName()+"  "+a.getValue());

        }

    }

    return "No-Cookies";
4 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)