jsp

Redirect back to original URI


I have a page with some results. The user can click an item and edit it. I want after editing the user to be able to return back to the results. Back isn't broken but if he submits the form for update he would have to click back 2 times I think and may have problem.

I have tried header("Referer") but this doesn't work in Internet Explorer.

I am trying to implement a solution. Any ideas? My idea is to save url and move around an ID of that url. And when I want to return back get the url from ID. Storing it in the session is not a solution because the user may have opened multiple windows.


Solution

  • The best way is to pass it around as a request parameter. On the edit link or button, just pass the current URI (not URL!) along as request parameter. Here's an example with a link:

    <a href="/login?from=${pageContext.request.requestURI}">edit</a>
    

    Or if it's a button to submit a form, then rather pass it as hidden input value in the same form:

    <input type="hidden" name="from" value="${pageContext.request.requestURI}">
    

    In the page with the edit form, transfer it to the subsequent request as hidden input value of the form:

    <input type="hidden" name="from" value="${param.from}">
    

    In the action method, just redirect to that URI after finishing the action:

    String from = request.getParameter("from");
    
    if (from != null && from.startsWith("/")) {
        response.sendRedirect(from);
    }
    

    Do note that it checks whether it starts / in order to ensure it's an URI and not an URL so it doesn't allow a CSRF trap.