无法使用 requestDispathser 包含 servlet 响应

Unable to include servlet response by using requestDispathser

Index.jsp

<form method="post" action="serv">
Enter Latest Reading <input type="text" name="t1"> <br>
Enter Previous Reading <input type="text" name="t2"> <br>
<input type="submit" value="SEND">  
</form>

LoginServlet.java

@WebServlet("/serv")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    PrintWriter out = res.getWriter();   
    out.println("<u>Following are your Bill Particulars</u><br><br>");   
    req.setAttribute("unitRate", new Double(8.75));

    req.getRequestDispatcher("/Test").include(req, res); 
    out.println("<br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection");   
    out.close();

    }

}

IncludeServlet.java

@WebServlet("/Test")

public class IncludeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        PrintWriter out = res.getWriter();   
        int latestReading = Integer.parseInt(req.getParameter("t1"));   
        int previousReading = Integer.parseInt(req.getParameter("t2"));   
        Object obj = req.getAttribute("unitRate");
        Double d1 = (Double) obj; 
        double rate = d1.doubleValue();   
        int noOfUnits = latestReading-previousReading; 
        double amountPayable = noOfUnits * rate;   
        out.println("Previous reading: " + previousReading); out.println("<br>Current reading: " + latestReading); 
        out.println("<br>Bill Amount Rs." + amountPayable); 

    }

}

当我运行上面的项目时,在浏览器中只显示LoginServlet的响应,我无法包含IncludeServlet.java的响应。

LoginServlet 的所有 System.out.println("") 仅在控制台显示,而非来自 IncludeServlet

我也使用调试器,但这不会进入 IncludeServlet.java 页面。

在你的 IncludeServlet 而不是覆盖 doGet 方法覆盖 doPost ,因为 Post 请求来自 HTML

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  // do Whatever you want to do .
}

更新: 还要在两个 servlet 中写入 res.setContentType("text/html");,以便在 out.print 中编写的 html 执行,否则您的输出将看起来像 <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection.