0

Anyone knows why the code throw an exception on this line?

        HttpSession session = request.getSession();
        UserFactory userFactory = UserFactory.getInstance();
        int userNum = (int)session.getAttribute("userID");
        User user = userFactory.getUserByID(userNum);

Exactly on the third line, I used this lines of code other times in the project but never had this exception.

  • Didn't work, and NetBeans suggest me to change it with a cast Integer.parseInt((String) session.getAttribute("userID")); – Matteo Reccia Jun 09 '18 at 11:51
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Rcordoval Jun 09 '18 at 12:16

1 Answers1

1

Although you saved an int, method expects an Object. Therefore, your int will become an Integer (read on auto-boxing). Below should work fine!

int userid = (Integer) session.getAttribute("userID");

Chiran K.
  • 406
  • 3
  • 16
  • It always stopped there, throwing an exception java.lang.NullPointerException. When I'm logged in the JSP shows the page correctly, but if I'm not don't. So I think the problem is not the cast, but something else – Matteo Reccia Jun 09 '18 at 11:53
  • session.getAttribute("userID") should be returning null. check if you have specified the attribute name properly. Further, Make sure that you have a try catch to check if it is a null object – Chiran K. Jun 09 '18 at 11:56
  • Just checked, userID is null. Thank you. – Matteo Reccia Jun 09 '18 at 12:07