Thursday, 8 August 2013

How to get form parameters in request filter

How to get form parameters in request filter

I'm trying to get the form parameters of a request in a request filter:
@Override
public ContainerRequest filter(final ContainerRequest request) {
final Form formParameters = request.getFormParameters();
//logic
return request;
}
However, the form always seems to be empty. The
HttpRequestContext.getFormParameters() documentation says:
Get the form parameters of the request entity.
This method will ensure that the request entity is buffered such that it
may be consumed by the applicaton.
Returns: the form parameters, if there is a request entity and the content
type is "application/x-www-form-urlencoded", otherwise an instance
containing no parameters will be returned.
My resource is annotated with
@Consumes("application/x-www-form-urlencoded"), although it won't have
been matched until after the request filter - is that why this isn't
working?
I tried doing some research but couldn't find any conclusive evidence of
whether this is possible. There was this 4-year old discussion, in which
Paul Sandoz says:
If you are working in Jersey filters or with the HttpRequestContext you
can get the form parameters as follows: [broken link to Jersey 1.1.1
HttpRequestContext.getFormParameters]
I also found this 3-year-old discussion about how to get
multipart/form-data form fields in a request filter. In it, Paul Sandoz
uses the following code:
// Buffer
InputStream in = request.getEntityInputStream();
if (in.getClass() != ByteArrayInputStream.class) {
// Buffer input
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ReaderWriter.writeTo(in, baos);
} catch (IOException ex) {
throw new ContainerException(ex);
}
in = new ByteArrayInputStream(baos.toByteArray());
request.setEntityInputStream(in);
}
// Read entity
FormDataMultiPart multiPart = request.getEntity(FormDataMultiPart.class);
I tried emulating that approach for just form params, but the result of
request.getEntityInputStream() is always an empty stream. What am I doing
wrong here, or is this impossible (and why)?

No comments:

Post a Comment