0

I need a method which must check if the session has a specific attribute or not. The problem is that when I want to check if the session has the attribute I get a null pointer exception. I think that I get this error because the session object is not initialized properly. I need this method because I want to render the page base on this attribute (if the user is logged in he must to show the button logout and vice versa). What I am doing wrong in my code?

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionTest extends HttpServlet{
    HttpSession session;


    @PostConstruct
    public void init(HttpServletRequest request) {
        session = request.getSession(true);
        session.setAttribute("user", "username");
    }

    public boolean getParamer(String user) {
        return session.getAttribute(user) == null;
    }

    public static void main(String[] args) {
        System.out.println(new SessionTest().getParamer("user"));
    }


}
Kukeltje
  • 12,223
  • 4
  • 24
  • 47
John R.
  • 420
  • 4
  • 14
  • Please add the complete stacktrace. Also a main in a serlet doesn't make sence – Jens Feb 09 '19 at 09:00
  • I don't think it's a duplication question of one which is marked. Please understand the question before marking it duplicate. – Deepak Kumar Feb 09 '19 at 09:02
  • The request object creation and init method call is done by the servlet container. In your case, as you are calling it from the main method. The initialization of servlet will not be done. Your class `SessionTest` is treated as a normal class. As the init method is never getting called, `session` will be pointing to null in the `getParamer` method. And the `session.getAttribute(user)` will result into `NullPointerException` – Deepak Kumar Feb 09 '19 at 09:09
  • Deploy the same servlet in some web server, it will work fine. – Deepak Kumar Feb 09 '19 at 09:11
  • Please remove the [duplicate], it's wrong. John needs to understand the lifecycle of JEE CDI Managed Beans rather than beeing advised to learn Java. – Marc Dzaebel Feb 09 '19 at 09:50

0 Answers0