Redirection of sum result in JSP servlet

0

I need to show the result of a sum in a redirected page, I tried a "setAttribute" after the "Redirect" but it does not work. The sum value would have to go to an "input" on the next page, or a simple " <h1> ". The part of the "request", where the summation begins, is all ok.

I have the following method:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try (PrintWriter out = response.getWriter()) {
        int soma = Integer.parseInt(request.getParameter("a")) + Integer.parseInt(request.getParameter("b"));

        response.sendRedirect("resultado.jsp");
        response.getContentType();
        request.setAttribute("result", soma);
    }
}

And the following code on the .jsp page:

<h1> Resultado da soma: <input type="number" name="result"> </h1>
    
asked by anonymous 17.09.2018 / 23:22

1 answer

2

Your doGet () method needs to be readjusted.

Here is a possible change:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        int a = Integer.parseInt(request.getParameter("a"));
        int b = Integer.parseInt(request.getParameter("b"));
        int soma = a + b;

        request.setAttribute("result", soma);
        request.getRequestDispatcher("resultado.jsp")
               .forward(request, response);
}
  

Using sendRedirect (), you are changing the flow at the client level. That is, you are asking the browser to make a new request for resultado.jsp. This way you lose the data: a, b and sum.

  

By using getRequestDispatcher (), you are changing the forward / bypass flow to result.jsp transfer to request (containing result attribute storing sum) and response without client nor notice. Like, shhhh in the migué ... does not tell him anything [client].

The result.jsp needs to be readjusted.

Here is a possible change:

<input type="number" name="result" value="${result}" />

    
18.09.2018 / 00:40