如何从包含的servlet请求属性获取?

时间:2016-12-23 13:28:36

标签: java jsp servlets nullpointerexception

我在1个servlet中有以下代码:

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

这在第二个servlet中:

request.setAttribute("Successful", true);

但是,我一直在NullPointerException

上获得request.getAttribute("Successful")

1 个答案:

答案 0 :(得分:0)

您的代码执行此操作的唯一原因是因为您的LoginModel servlet未被调用(顺便说一句,您是否调试了它以进行检查?)。

发生NullPointerException是因为您试图将空引用转换为boolean(安全检查会解决此问题,但不解决此问题)。

参见一个正常工作的例子:

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);
    }
}

最终结果:

Success!