File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Session tracking in servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Session tracking in servlets" Watch "Session tracking in servlets" New topic

Session tracking in servlets

jill Na

Joined: Dec 05, 2010
Posts: 11

I have very simple - probably silly too - question.
I am trying to add session variable in my application for using the userName of the logged in user.
I know if I were to use it in jsp - I could simply do session.setAttribute("userName", userName);

but here is what I am doing -
Jsp page sends information to a servlet, which queries for that user's info. Based on this I want to fetch the userName from the database and put it in a variable which should be available through out the application for the valid session. How should I be doing that?

If you think there is any other better / alternate way , then pleaase let me know (along with the above question.)
Nikhil Pasupukuntla

Joined: Jun 04, 2009
Posts: 21
Hi Jill,

You can store the username as a session attribute in the servlet .

Nikhil Pasupukuntla
SCJP 1.5 | OCPJWCD 1.5
Sergey Baranov

Joined: Aug 27, 2005
Posts: 18

You can set session attribute as in code snippet below:

String userName = someDaoClass.getUserName();
HttpSession session = request.getSession();
session.setAttribute("userName", userName);

And then get access to variable "userName":
HttpSession session = request.getSession();
String userName = session.getAttribute("userName");

userName attribute will be available unless and until session will be valid.

Is it what you need?

Sergey Baranov
jill Na

Joined: Dec 05, 2010
Posts: 11
yeah thanks I was not getting the same option on java page for some reason .... but yeah setAttribute worked embarassing ;) though
parampreet sethi

Joined: Aug 03, 2009
Posts: 27

The another way to do it is, store the information in a cookie on client side and grab the value from the cookie whenever it should be shown on frontend.

You can check if the cookie is not present or value is null, grab the value from the database and store it in the cookie.

I agree. Here's the link:
subject: Session tracking in servlets
It's not a secret anymore!