当我使用 RequestDispatcher 并使用 forward 将我的请求和响应发送到新的 servlet 时,出现错误

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

当我在服务器上 运行 这个程序时,我遇到了多个错误。 也添加了 XML 代码,我认为其中有问题。


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

以下映射有误:

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

应该是

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

我已将 abc 替换为 pqr,映射到 com.shlok.SqServlet

除了在 web.xml 中映射 servlet,您还可以使用注释来完成它,如下所示:

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

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

注意:确保在调用AddServlet时将num1和num2的值作为请求参数传递,如下所示;否则,你将面临java.lang.NumberFormatException: null.