Kristian Kraljić You may compare programming with poetry,
a harmonic script is a piece of creativity which will last forever.
- Kristian Kraljić

Java – (Thread Local) Servlet Cookie Filter

by Kristian Kraljic, December 28, 2015

Sadly but true, it seems that I’m keeping my “one post a year”-momentum up… Oh, No… Not Again! I’m going to challenge myself and pull off a little year-end coding marathon! I’m having a lot of helpfull stuff in my quiver. It’s on, I’m going to release *one* post consecutively for the next six days! Including this one, that’ll make four posts in 2015 and already two post in 2016! So… “LET’S DO THIS!”

Let’s start with a thread local servlet cookie filter implementation. Handling user-based cookies on a server-side servlet application really proves difficult in Java. Cookies (at least for all standard protocol handler implementations) are handled by one central CookieHandler object, which can be set and retrieved using the CookieHandler‘s setDefault and getDefault methods. As this cookie handler is used system-wide, each process shares the same cookies for any given URL. For servlets handling cookies, this becomes a problem sooner or later, e.g. if the servlet is dealing with user-specific logins, or similar.

You can find a really simple solution for this problem on my new profile on GitHub: (isn’t it cool that I got kristian to be my profile name on GitHub? *happy*)

With the Java Servlet Cookie Filter user-based cookie handling becomes a piece of cake. When loading the classes, the CookieFilter class registers as a transparent (no data gets changed) filter implementation using the @WebFilter annotation. The filter first registers a new default CookieHandler which then dynamically intercepts each request and response. From now on each user gets access to a dedicated CookieStore. The store is purged as soon as the response is sent, so the next request going to the same thread will again receive a new CookieStore. This eliminates the risk of sharing any cookie information between threads or requests.

So that was my first of fife posts this week. Hope you liked it. Expect more Java related stuff and some chit-chat in the next couple of days!