我目前正在学习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();
}
}
}
getSession(false)上的HTTPServletRequest将返回值。
HttpSession session = req.getSession(false); //will return null if no session object is found.
AddServelet get方法创建一个会话对象。这意味着您需要先点击此Get方法,然后再点击SqServlet HTTP URL。