I am not using JSON or anything like that. I have a simple form to upload a file and I want to read the parameters of the form. The code below is not working as expected. It will not show any parameters.
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("{appNum}/{docId}/file")
public Response uploadDocFile(
@PathParam("appNum") String appNum,
@PathParam("docId") String docId,
@Context HttpServletRequest req)
{
try {
log.info("POST Parameters:");
Enumeration e = req.getParameterNames();
while(e.hasMoreElements())
{
Object key = e.nextElement();
log.info("Key: " + key);
log.info("Val: " + req.getParameter(key.toString()));
}
} catch (Exception e) {
e.printStackTrace();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new StatusResponse(e)).build();
}
return Response.ok().build();
}
FYI, You need to use @FormParam. Also make sure INPUT HTML types are using name= not id=.
I have the same problem. Using @FormParam
annotation for individual parameters works, but reading them from HttpServletRequest
injected through @Context
doesn't. I also tried to get the request object/parameters through Guice using Provider<HttpServletRequest>
and @RequestParameters<Map<String, String[]>>
. In both cases there were no post parameters.
However, it is possible to get a map of parameters by adding a MultivaluedMap<String, String>
parameter to resource method. Example:
@POST
public void doSomething(MultivaluedMap<String, String> formParams) {
//...
}
If you are using Jersey RESTful API in JAVA you can look for Parameter Annotations (@*Param)
Example:
Dependency:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
Code:
package yourpack;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/path_to_data")
public class DataResource {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String urlparam) {
int ok = 200;
String result = "Jersey Data resource: " + urlparam;
return Response.status(ok).entity(result ).build();
}
}
List of annotations: @MatrixParam, @HeaderParam, @CookieParam, @FormParam, @QueryParam, @PathParam
At some point of time Jersey ContainerServlet (or other Jersey object during request processing) calls request.getInputStream() or request.getReader() which set 'usingInputStream' or 'usingReader' to TRUE. This state prevents populating of parameters map inside the request object. Something like this:
parseParameters() {
if (usingInputStream || usingReader) {
return;
} else {
parametersMap.putAll({actual parameters parsing from stream})
}
}
Map getParametersMap() {
return parametersMap;
}
Try putting a break point at the very first entry point (beginning of Jersey ServletContainer.service() method) of your application and evaluate request.getParametersMap() call. You'll get your parameters.