Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.