0

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();
        }
    }
}
marstran
  • 26,413
  • 5
  • 61
  • 67

2 Answers2

0

HTTPServletRequest on getSession(false) will return value.

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

AddServelet get method create one session object. That means you need to hit this Get method first and then SqServlet HTTP URL.

Preferably modify your code to handle null check and return user if no session is found.

  • Get method of AddServelet is called from index.html page I have created. So there is no problem in creation of session in AddServelet. Problem is that this session is not getting continued in SqServlet and it is returning null. Gettin hold of the session created in AddServelet is the major problem. – Arpit Awasthi May 16 '20 at 15:44
  • Below is the code of my index.html file and corressponding .xml file. ```
    Enter 1st number:
    Enter 2nd number:
    ```
    – Arpit Awasthi May 16 '20 at 15:47
  • Since you are redirecting after the session set, you need to do something so that cookies are set at the client-side. ince you are using HTML, it won't be set. You need to use jsp or some templating engine. https://stackoverflow.com/questions/13461838/preserving-session-in-java-with-sendredirect – Dharmendra Vishwakarma May 16 '20 at 16:13
0

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

Chanfir
  • 73
  • 2
  • 7