Sum result redirect in JSP Servlet

Asked

Viewed 157 times

0

I need to show the result of a sum on a redirected page, I tried a "setAttribute" after "Redirect" but it doesn’t work. The sum value would have to go to an "input" on the next page, or on an "<h1>" simple. The "request" part where the sum starts 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>
  • I think it is enough just to receive on the page the attribute "result", <input type="number" name="result" value="{$result}">

1 answer

2


Your doGet() method needs to be readjusted.

Following a possible amendment:

@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 re-request for result.jsp. This way you lose the data: a, b and sum.

Using getRequestDispatcher(), you are changing the server-level flow (forward/bypass) to result.jsp transferring a request (containing the result attribute storing the sum) and replay without the customer not even noticing. Type, shhhh on the mouse... does not tell him anything [client].

The.jsp result needs to be readjusted.

Following a possible amendment:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.