Unable to include servlet response by using requestDispathser

55 views Asked by At

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

    }

}

When I run the above project, only the response of LoginServlet is displayed in a browser, I'm unable to include the response of IncludeServlet.java.

All System.out.println("") of LoginServlet is being display is console only, non from IncludeServlet.

I also use debugger, but this is not going into IncludeServlet.java page.

1

There are 1 answers

1
Neeraj Jain On BEST ANSWER

In your IncludeServlet instead of overriding doGet method override doPost , Since Post request is coming from HTML

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

Update: Also write res.setContentType("text/html"); in both servlet so that your html written in out.print executes otherwise your output will look like <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection.