Search code examples
javaservletsrequestdispatcher

When I'm using RequestDispatcher and using forward to send my my request and response to a new servlet I'm getting error


When I'm running this program on the server I'm getting multiple errors. Added the XML code too, I think something is wrong with that.

As in the picture


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    id="WebApp_ID" version="4.0">

    <servlet>
        <servlet-name>abc</servlet-name>
        <servlet-class>com.shlok.AddServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>pqr</servlet-name>
        <servlet-class>com.shlok.SqServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/sq</url-pattern>
    </servlet-mapping>

</web-app>
public class AddServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        int i = Integer.parseInt(req.getParameter("num1"));
        int j = Integer.parseInt(req.getParameter("num2"));

        int k = i + j;

        req.setAttribute("k", k);
        RequestDispatcher rd = req.getRequestDispatcher("sq");
        rd.forward(req, res);   
    }
}
public class SqServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

        int k = (int) req.getAttribute("k");
        k = k * k;

        PrintWriter out = res.getWriter();
        out.println("Result is : " + k);
    }
}

Solution

  • There is a mistake in the following mapping:

    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/sq</url-pattern>
    </servlet-mapping>
    

    It should be

    <servlet-mapping>
        <servlet-name>pqr</servlet-name>
        <url-pattern>/sq</url-pattern>
    </servlet-mapping>
    

    I have replaced abc with pqr which maps to com.shlok.SqServlet.

    Instead of mapping the servlets in web.xml, you could also do it using annotation as follows:

    @WebServlet("/add")
    public class AddServlet extends HttpServlet {
        //...
    }
    
    @WebServlet("/sq")
    public class SqServlet extends HttpServlet {
        //...
    }
    

    Note: Make sure to pass the value of num1 and num2 as request parameters while calling AddServlet as shown below; otherwise, you will face java.lang.NumberFormatException: null.

    enter image description here