Arturo Arturo - 2 months ago 7
Java Question

Receiving unknown parameter name on POST request in Java (JAX-RS)

I have the following POST response in JAX-RS.

@POST
@Path("/save")
public Response saveS(@FormParam(key) String value) throws SQLException {
return Response.ok("TODO", MediaType.APPLICATION_JSON).build();
}


The parameter that is received could be called
name
or
age
or many other things. I have identified it as
key
in the code (obviously it doesn't work).

How can I retrieve the name of that parameter?

Thanks

Answer

The parameter that is received could be called name or age or many other things. I have identified it as key in the code (obviously it doesn't work).

As you already found out it doesn't work that way because the @FormParam is expecting the name of a form parameter as it is defined in the corresponding HTML form. That means you should know which form parameter you want to assign to the param (value in this case) of the method.

Here is the definition of the @FormParam annotation extracted from the JAX-RS specification:

FormParam Parameter

Specifies that the value of a method parameter is to be extracted from a form parameter in a request entity body. The value of the annotation identifies the name of a form parameter. Note that whilst the annotation target allows use on fields and methods, the specification only requires support for use on resource method parameters.

And in addition to that you should add the @Consumesannotation to your resource method as follows:

@POST
@Path("/save")
@Consumes("application/x-www-form-urlencoded")
public Response saveS(@FormParam(key) String value) throws SQLException {           
    return Response.ok("TODO", MediaType.APPLICATION_JSON).build();
}

Update: I haven't tried myself, but you can try and tell me if it works. Here you should get all the params so that you can parse all the form fields:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
   // parse the map here
}
Comments