4

Today I tried this kind of code... after logged in I removed all cookies with my FF browser, then I refreshed web page and I got NPE :P So I've been thinking is there a simple way to "restore" or whatever session if cookies were removed manually on the client or what is the most optimal way in this situation especially if there is some data (related to session attribute) is still in the servlet context scope?

For example if I have some id in session as

session.setAttribute("id","hello world");

...and I have code like a

String userID=null;
                Cookie []cookies=req.getCookies();

                    for(Cookie cookie:cookies)
                    {
                        if(cookie.getName().equals("id")){userID=cookie.getValue();}
                    }


String id=session.getAttribute("id");
User user=((MyUsers)context.getAttribute("Users")).getUser(id);

how can I remove user (to avoid duplicates) if

  • A) There is no cookies because they were removed manually
  • B) and session.getAttribute("id"); throws NPE?

Thanks

Community
  • 1
  • 1
user592704
  • 3,674
  • 11
  • 70
  • 107

1 Answers1

0

The Servlet environment uses URL rewriting or Cookies to keep track of user sessions (this is an HTTP thing). If you delete the cookies on your browser you (must likely) end up losing all the connection between the user browser and your web application.

If you want to remember the user, you need the cookies. The NPE you're getting is just the reflection of the cookie's absence (and missing bits in your program).

So, you should check if the cookies and/or session exist (validate NPE), if you can't find any of them, then you won't be able to track your user (and should redirect him to your login page - if it applies).

megathor
  • 479
  • 3
  • 7
  • AFAIK there is no way to track. Remember that this occurs on the user browser, completely disconnected from your server. You can implement something like suggested on http://www.nakov.com/inetjava/lectures/part-3-webapps/InetJava-3.4-Servlet-lyfecycle-Sessions-Cookies.html item 3. But at the end is all about how you decide to implement it... – megathor Nov 19 '13 at 03:27
  • But what about some "standard architecture solution" for this kind of situation? Or having duplicate users is fine? Or how to walk around "duplicate users" issue? – user592704 Nov 19 '13 at 16:29