Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Ricardo Sala
Ricardo Sala
15,606 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.