使用HttpSession时获取空指针异常

问题描述 投票:-1回答:1

我目前正在学习Servlet。使用以下代码时,我得到了NullPointerException。每当在getAttribute()中调用SqServlet函数以获取k中的值时,它将返回空值。谁能告诉我我要去哪里错了?谢谢。

public class AddServelet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        try {
            int i = Integer.parseInt(req.getParameter("num1"));
            int j = Integer.parseInt(req.getParameter("num2"));
            int k = i + j;

            PrintWriter out = res.getWriter();
            HttpSession session = req.getSession();

            req.setAttribute("k", k);
            res.sendRedirect("sq");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

public class SqServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        try {
            HttpSession session = req.getSession(false);
            int k = (int)session.getAttribute("k");

            k = k * k;
            PrintWriter out = res.getWriter();
            out.println("Square of sum: " + k);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
java servlets session-management
1个回答
0
投票

getSession(false)上的HTTPServletRequest将返回值。

 HttpSession session = req.getSession(false); //will return null if no session object is found.

AddServelet get方法创建一个会话对象。这意味着您需要先点击此Get方法,然后再点击SqServlet HTTP URL。

© www.soinside.com 2019 - 2024. All rights reserved.