的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
的回复。
正在显示System.out.println("")
的所有LoginServlet
仅限控制台,而非来自IncludeServlet
。
我也使用调试器,但这不会进入IncludeServlet.java
页面。
答案 0 :(得分:1)
在IncludeServlet
而不是覆盖doGet
方法覆盖doPost
,因为发布请求来自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
。