Andrew Maddison

Flowerchild.

Jersey / Dropwizard Server.Transfer

I was looking for a way of doing something equivalent to ASP.Net’s Server.Transfer in DropWizard. Basically, while processing a page in a Jersey resource I want to abort processing the page the user requested and switch to processing a different page, (probably an error) with a different http response code (the easy bit) generated by a different Jersey resource. I’m not sure if this is the correct way to do it (feel free to comment), but all we ended up doing was simply to call the public method of the other resource, and return that from the method of our original resource/exception mapper. Something like the following (in an ExceptionMapper - but you could do something similar in a resource itself)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

public class ExampleExceptionMapper implements ExceptionMapper<SomeException> {
    private ErrorResource errorResource;

    public ExampleExceptionMapper(ErrorResource errorResource) {
        this.errorResource = errorResource;
    }

    @Override
    public Response toResponse(SomeException exception) {
        return errorResource.getSomeErrorResponse(exception.getRequestId());
    }
}
The only problem with doing the same from a resource, is that it will probably have to return a response, rather than a DropwizardView, so that you can set the http status which might muddy the intent of your resources.
1
2
3
4
5
6
7
8
9
10
11
12
13
@GET
    public Response getSomePage(@QueryParam("someIdParam") String id) {
        Response response;
        if (someRepository.contains(id)) {
            SomeView view;
            //Build up some view.
            response = Response.ok(SomeView).build();
        } else { //no record found
            ErrorView errorView = someErrorResource.getMissingRecordErrorPage(id);
            response = Response.status(Response.Status.NOT_FOUND).entity(errorView).build();
        }
        return response;
    }
PS .Net folks - the above code is Java - so don’t shout at me about the brace layouts - it’s the Java way.

Comments