Robert Peach
Robert Peach

Reputation: 73

how to create cookies for custom user database in GAE java?

I understand that using the user service that google app engine offers then cookies are automatically created in the background and I would never have to deal with them. However, for my specific project I need to create a custom user database - How would I go about knowing that a user is logged in or out? Would I have to create cookies for the users browser etc?

Cheers, Rob

Upvotes: 2

Views: 640

Answers (1)

Jan Dörrenhaus
Jan Dörrenhaus

Reputation: 6717

No, you don't. All you need to do is enabling sessions, by adding

<sessions-enabled>true</sessions-enabled>

to your appengine-web.xml file. See documentation..

Essentially, GAE is a servlet container. So you can make use of pretty much all the mechanics any standard Java servlet container has. Sessions are one of these mechanics.

So what you would do, is this:

  1. Call request.getSession(true) to get the current session, or create a new one if that hasn't been done, yet.
  2. Do something like session.getAttribute("userId"). Note that "userId" is just an example, it is essentially a string-object-map, in which you can store pretty much anything.
  3. If the above call returns null, it has not been set yet, so the user is not logged in yet. Make him log in:
    • Get username and password, resolve in the datastore, do session.setAttribute("userId", user.getId())
    • Since the session attribute "userId" is now set, the user is logged in.
  4. If the above call returns an id, you can resolve it in the data store to get the currently logged in user.

Try it out! It is really a breeze, everything is done for you, no need to handle cookies, session tokens or anything yourself.

Upvotes: 3

Related Questions