简体   繁体   中英

Java getAttribute() method error in the servlet

I am Facing an issue while trying to get sum element in one servlet from the other by using Request Dispatcher.

But the getAttribute() method in S2.java is giving error while accessing the sum from Request_Dispatcher_example.java.

I have tried this using HttpSession as well but the same error is occurred there

  **Error:**
    
    Cannot invoke "java.lang.Integer.intValue()" because the return value of "javax.servlet.http.HttpServletRequest.getAttribute(String)" is null

Type Exception Report Message Cannot invoke "java.lang.Integer.intValue()" because the return value of "javax.servlet.http.HttpServletRequest.getAttribute(String)" is null Exception java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "javax.servlet.http.HttpServletRequest.getAttribute(String)" is null com.servlet.S2.doGet(S2.java:22) javax.servlet.http.HttpServlet.service(HttpServlet.java:655) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Code

1. Request_Dispatcher_example.java

public class Request_Dispatcher_example extends HttpServlet

{
    public void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
    {
        String i = req.getParameter("n1");
        String j = req.getParameter("n2");
        
        int nn1= Integer.parseInt(i);
        int nn2 = Integer.parseInt(j);
        
        int s = nn1 + nn2;
        
        req.setAttribute("sum", s);
        
        
        RequestDispatcher rd = req.getRequestDispatcher("s2");
        rd.forward(req, res);
        
    }
}

2. S2.java

public class S2 extends HttpServlet 
{
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        
        
        int nn1  = Integer.parseInt(req.getParameter("n1"));
        int nn2  = Integer.parseInt(req.getParameter("n2"));

        int p = nn1*nn2;
        int sum = (Integer) req.getAttribute("sum");
        
        PrintWriter out = res.getWriter();
        out.println("Sum : "+sum);
        out.println("Product : "+p);
        
    }
}

Got the solution for this error:

In this case, I did not map my first java servlet file Request_Dispatcher_example.java in an xml file.

But now after mapping it in xml it is working fine and giving the proper results.

Specifically: we need to map our all the servlet files to xml to overcome this issue

Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM