Search code examples
javajspservletsrequestdispatcher

Multiple Request Response Forward


I am currently passing some ArrayList's from my servlet to my JSP page using the below code.

    RequestDispatcher rd = null;
    request.setAttribute("date",al);
    request.setAttribute("bau",al1);
    request.setAttribute("project",al2);
    rd = request.getRequestDispatcher("ResourceChart.jsp");
    rd.forward(request,response);

The problem is when I click refresh on the page, the same date is passed again and I end up with odd results. Should I be forwarding to the JSP page as well to avoid the servlet regenerating the variables and passing them?

Whats the best way to implement this?


Solution

  • You're apparently refreshing a POST request and ignoring/confirming the browser's builtin warning that the data would be resent. In that case, the doPost() method will indeed be re-executed with the previously submitted data which would only end up in duplicate entries in the DB.

    The canonical approach to avoid the double submit on a refresh of a POST request is to send a redirect after POST request. A redirect implicitly creates a new GET request. Refreshing would then result in only the GET request being re-executed which is totally harmless.

    To achieve that, replace all in the question shown lines of the doPost() by the following single line

    response.sendRedirect(request.getContextPath() + "/ResourceChart");
    

    (assuming that your servlet is mapped on an URL pattern of /ResourceChart)

    and create a new doGet() method wherein you put all those removed lines back, along with the necessary logic to prepare the lists. The only change which you need to make is to put the JSP file in /WEB-INF folder to avoid endusers from being able to open it directly by entering/guessing its URL without calling the servlet's doGet() first.

    request.getRequestDispatcher("/WEB-INF/ResourceChart.jsp").forward(request, response);
    

    See also: