Skip to content
JakeHoward edited this page Jul 16, 2015 · 1 revision

Post/Redirect/Get

In order to make a back button work properly after form submission and to prevent duplicate form submissions we can use the | Post/Redirect/Get pattern. Utterlyidle has a built-in Redirector object you can use to implement it.

@Path("path/{id}")
public class PostRedirectGet {
    private final Redirector redirector;

    // Redirector is already in the container, injected by the library
    public PostRedirectGet(Redirector redirector) {
        this.redirector = redirector;
    }

    @POST
    public Response post(@PathParam("id") String id) {
        // some logic
        return redirector.seeOther(method(on(PostRedirectGet.class).get(id)));
    }

    @GET
    public String get(@PathParam("id") String id) {
        return id;
    }
}

First, a user sends a POST request with the id parameter. Once we handle the parameter (e.g. persist it in a database) we want to return the following response to the user:

HTTP/1.1 303 See Other
Location: /path/user_specified_id

This response tells our user's HTTP client to issue another request (HTTP GET /path/user_specified_id). We could've created this response using ResponseBuilder, but Utterlyidle provides much more convenient utility class that can do the job. Please note that we defined a dependency on the Redirector in our constructor. It will be automatically injected to our resource. Redirector saves us from having to handcraft URLs. If we ever need to change a path value, there's no need to worry about breaking the redirection logic. Redirector uses a class name and a method name which are verified at compile time.

TODO:

  • base URI handling
  • uri of
  • absolute uri of

Clone this wiki locally