0

I have the following code in 1 servlet:

dispatcher = request.getRequestDispatcher("LoginModel");
dispatcher.include(request, response);
if ((boolean) request.getAttribute("Successful")) {}

and this in the 2nd servlet:

request.setAttribute("Successful", true);

However, I keep getting a NullPointerException on the request.getAttribute("Successful")

diogo
  • 3,769
  • 1
  • 24
  • 30
Charlie Hardy
  • 175
  • 1
  • 3
  • 14

1 Answers1

0

The only reason why your code is doing this is because your LoginModel servlet is not being called (BTW, have you debugged it to check?).

The NullPointerException happens because you're trying to cast a null reference to a boolean (a safe-check would resolve this, but not the call itself).

See one example, which is working properly:

Servlet 1:

@WebServlet(urlPatterns = "/serv")
public class Serv extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        RequestDispatcher dispatcher = request.getRequestDispatcher("serv2");
        dispatcher.include(request, response);
        if (request.getAttribute("Successful") != null
                && (boolean) request.getAttribute("Successful")) {
            System.out.println("Success!");
        } else {
            System.out.println("No success!");
        }
    }
}

Servlet 2:

@WebServlet(urlPatterns = "/serv2")
public class Serv2 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute("Successful", true);
    }
}

Final result:

Success!
diogo
  • 3,769
  • 1
  • 24
  • 30
  • Hi, It appears as though that it was a catch in the second servlet that was causing the NPE, Now just got to solve why the catch is occurring! – Charlie Hardy Dec 23 '16 at 17:38