Enter Latest Reading

Cannot enable servlet response 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); 

    }

}

      

When I run the above project, only the response is shown in the browser LoginServlet

, I cannot enable the response IncludeServlet.java

.

All System.out.println("")

of are LoginServlet

displayed only in the console, not from IncludeServlet

.

I also use a debugger, but that doesn't happen on the page IncludeServlet.java

.

+3


source to share


1 answer


In IncludeServlet

instead of overriding, doGet

override the method doPost

as the Post request comes fromHTML

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 servlets so that your html written in out.print

is executed differently, your output will look like <br><br>Please pay the bill amount before 5th of every month to avoid penalty and disconnection

.

+1


source







All Articles