Tetaining session info between jsp page and servlet

Posted on 2005-04-11
Last Modified: 2010-04-01
I have I website that contains both jsp pages and servlets. In one of my jsp pages I set a session variable using


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

HttpServletRequest req;

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

Question by:aka_damo

    Author Comment

    That should be "Retaining session info between jsp page and servlet"
    LVL 29

    Accepted Solution

    You need this

    HttpSession session = request.getSession() ;
    String emp_id = session.getAttribute("emp_id");
    LVL 29

    Expert Comment

    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

    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.

    Author Comment

    Cheers bloodredsun,
    That works fine. I spotted the missed cast alright but I just used

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

    Thanks again

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now