Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Jersey request based on form data

In Jersey 1.x, you can use ContainerRequest.getFormParameters() to do request filtering on the form data, but I don't see an obvious equivalent in Jersey 2.x. I've implemented the ContainerRequestFilter interface which gives me access to a ContainerRequestContext, but from there how can get the form data?

Jersey 1.x example:

public class MyFilter implements ContainerRequestFilter {
  public ContainerRequest filter(ContainerRequest request) {
    Form f = request.getFormParameters();

    // examine form data and filter as needed
  }
}

Jersey 2.x example:

public class MyFilter implements ContainerRequestFilter {
  public void filter(ContainerRequestContext context) {
    // how do I get to the Form data now?
  }
}
like image 797
Mike Avatar asked Aug 28 '14 20:08

Mike


1 Answers

After a ton of searching and trial and error, I have found a suitable way to do this in Jersey 2. You have to consume the request entity body manually, but you have to be careful to do it in a way that doesn't prevent subsequent filters and resources from also consuming it. Below is a simple example that reads the entity into a Form object:

@Provider
public class FormDataFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        if (requestContext instanceof ContainerRequest)
        {
            ContainerRequest request = (ContainerRequest) requestContext;

            if ( requestContext.hasEntity()
              && MediaTypes.typeEqual(MediaType.APPLICATION_FORM_URLENCODED_TYPE,request.getMediaType()))
            {
                request.bufferEntity();
                Form f = request.readEntity(Form.class);
            }
        }
    } 
}

The key is calling bufferEntity(). Without this, the entity is marked as closed and causes IllegalStateExceptions on any subsequent read attempt.

like image 58
Mike Avatar answered Sep 28 '22 07:09

Mike