Tetaining session info between jsp page and servlet

Hey,
I have I website that contains both jsp pages and servlets. In one of my jsp pages I set a session variable using

session.setAttribute("emp_id",rs.getString("emp_id"));

This information is held fine when I'm just navigating between jsp pages but when I go to a servlet and use

HttpServletRequest req;
req.getAttribute("emp_id").toString();

I get a null pointer exception. Help greatly needed and hugely appreciated,

aka_damo
aka_damoAsked:
Who is Participating?
 
bloodredsunCommented:
You need this

HttpSession session = request.getSession() ;
String emp_id = session.getAttribute("emp_id");
0
 
aka_damoAuthor Commented:
Sorry,
That should be "Retaining session info between jsp page and servlet"
0
 
bloodredsunCommented:
In your example you are setting data into the session object and then trying to read it from the request object so it wil be null.( and there's a missed cast in my code)

setting JSP
---------------
session.setAttribute("emp_id",rs.getString("emp_id"));

getting JSP
---------------
String emp_id = (String)session.getAttribute("emp_id");//notice the cast to String as it actually returns an Object.

getting Servlet
---------------
HttpSession session = request.getSession() ;//get session object from the request object
String emp_id = (String)session.getAttribute("emp_id");//now as above


This is because the servlet container, such as tomcat, already provides you with the session object in the JSP so you don't need to worry about it.
0
 
aka_damoAuthor Commented:
Cheers bloodredsun,
That works fine. I spotted the missed cast alright but I just used

emp_id = session.getAttribute("emp_id").toString();

Thanks again
aka_damo
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.