Issue
I am currently learning Servlets. I am getting NullPointerException
when using the code below. It is returning null value whenever getAttribute()
function is called in SqServlet
to fetch value in k. Can anyone please tell me where I am going wrong? Thanks.
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();
}
}
}
Solution
You are setting the "k" in request then getting it from session
in AddServelet ,you should do : session.setAttribute("k", k);
rather than req.setAttribute("k", k);
Answered By - Chanfir
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)