Java Intro to Java Web Development with Spark Bells and Whistles Build Your Own Flash Messages

RICARDO SALA
PRO
RICARDO SALA
Pro Student 13,203 Points

Why not using session instead of request.attribute?

When we do this:

before((request, response) -> { if (request.cookie("username") != null) { request.attribute("username", request.cookie("username")); } });

Why don't use a sessión container for the username too instead of using the request.attribute?

As http is a stateless protocol, wouldn't the request.attribute("username") be in the next interaction?

I mean, I know it will not before the before executes everytime, and as long as the cookie is there, we will keep getting the username and asigning it to the request but...wouldn't it be better if we could save it in the session JUST ONCE and retrieve it as many times as we want?

Plus question: is "session" a cookie? Meaning...is it deleted when the user clears the navigation data?

Another plus question... how the...do I format my code so it looks like a "code snippet"??? xDDD

1 Answer

  • Of course it would be better to use session for username, but in this tutorial it was significant to show other aspects of Spark too (like req.attribute()).
  • Session is not a cookie. Session ID is a cookie. On the server side, session IDs are kept in a Map as keys. So this Map contains sessions which are Maps too :) Something like this: Map<String, Map<String, String>> sessions; So generally, if you clear a cookie, you won't delete the session - it will be preserved in the server memory. But without its' id (passed by cookie) you won't access your session.