1

getParameterMap() of HttpServletRequest returns both the query params and posted form data.

I am able to fetch the query parameters alone from UriInfo.getQueryParameters().

But I need the form parameters separately as a MultivaluedMap similar to query parameters, is there a way to fetch it?

EDITED:

I apologize for not making this clear. I am trying to fetch the form parameters in the filter/interceptor.

user2761431
  • 925
  • 2
  • 11
  • 26

1 Answers1

0

You can put the MultivaluedMap as a parameter in the resource method. This will be the body of the request. JAX-RS will put all the parameters in the map for you.

@POST
@Consumes("application/x-www-form-urlencoded")
public Response post(@Context UriInfo uriInfo, MultivaluedMap params) {}

UPDATE (to edited post)

So if you want to get the parameters in a filter, you can get the body from the ContainerRequestContext. With Jersey, instead of getting the InputStream with context.getEntityStream(), you can cast the ContainerRequestContext to Jersey's ContainerRequest implementation. This will give you access to the methods bufferEntity() and readEntity(). These methods will allow you do easily get the form parameters. You will need to buffer the entity so that it can be read later when it needs to be passed on to your resource method.

@Provider
public class MyFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext context) throws IOException {
        if (MediaTypes.typeEqual(MediaType.APPLICATION_FORM_URLENCODED_TYPE, context.getMediaType())) { {
            return;
        }
        ContainerRequest request = (ContainerRequest) context;
        request.bufferEntity();
        Form form = request.readEntity(Form.class);
        MultivaluedMap params<String, String> = form.asMap();
        MultivaluedMap<String, String> query = context.getUriInfo().getQueryParameters();
    }
}

If you want to use the filter only with specific resource methods, then you can use Name Binding or Dynamic Binding.

If for some reason the readEntity() returns an empty map (I've seen rare occurrences of people having this problem), you can try to retrieve the Form through an internal property

Object formProperty = request.getProperty(InternalServerProperties.FORM_DECODED_PROPERTY);
if (formProperty != null) {
    Form for = (Form) formProperty;
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720