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?
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With