Session Tracking in Servlet

K

kssk

I have got a jsp form which consist of name, phone, email, etc.
I want to use session tracking in servlet:

In servlet my code are like:


String gn=session.setAttribute("gn",request.getParameter("givenname"));
String email=session.setAttribute("em","email");
..
..
..
..
and so on and In jsp

I get session value by

String given=session.getAttribute("gn");

My program work properly but I would like to reduce the code as I have
to write setAttribute for all the detail.

Does anyone help me?
 
B

Babu Kalakrishnan

kssk said:
I have got a jsp form which consist of name, phone, email, etc.
I want to use session tracking in servlet:

In servlet my code are like:


String gn=session.setAttribute("gn",request.getParameter("givenname"));
String email=session.setAttribute("em","email");
.
.
.
.
and so on and In jsp

I get session value by

String given=session.getAttribute("gn");

My program work properly but I would like to reduce the code as I have
to write setAttribute for all the detail.

The usual practice is to use an Object that encapsulates all these
details, and store it in the session. For instance in your case you
could have a User class with the parameters "name", "email" etc as its
instance variables - and store an instance of "User" in the session
using a single attribute. e.g. Your servlet code could be :

User user = new User();
user.setName(request.getParameter("name"));
user.setEmail(request.getParameter("email"));
...... // populate all fields of user from parameters received
request.getSession().setAttribute("user",user);

Now in your JSP you could get the "user" object from the session once,
and then access its instance variables (using getter methods that you
provide). Or if you're using tag libraries (which is generally a good
thing to do in JSPs), you could access them using expressions such as
"${user.name}" or "${user.email}"

BK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top