How to set SameSite cookie attribute with Java?

Issue

I want to be able to set SameSite property of cookie from my java application. However, jakarta.servlet.http.Cookie from tomcat library doesn’t have a setSameSite method. How can I do this?

Solution

A setSameSite method hasn’t been introduced yet because SameSite is not included yet in official HTTP specifications, even though it is supported by most web browsers.

In Servlet API version 6.0, there is a method that allows adding any attribute to the cookie, that is setAttribute. For example, if you want to set SameSite=None, you can do:

var cookie = new Cookie(cookieName, cookieValue);
cookie.setAttribute("SameSite", "None");
response.addCookie(cookie);

If you’re using a version lower than 6.0, then you’ll have to create the cookie as a string and add it to the Set-Cookie header

String cookie = cookieName + "=" + cookieValue + "; SameSite=None";
response.addHeader("Set-Cookie", cookie);