Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @FormParam if form elements are dynamically created

Tags:

rest

jersey

Since html form elements are dynamically created in this application, the number of elements are not known. How does one obtain element information using @FormParam annotation? For example, the below code obtains information for two form elements:

    @POST
    @Path("/newpage")
    @Produces("text/html")
    public String func(@FormParam("element1") String firstElement,
                       @FormParam("element2") String secondElement) throws IOException 
    {
         // your code goes here
    }

This is not possible as we don't know the number of elements.

like image 659
vdep Avatar asked Mar 18 '23 15:03

vdep


2 Answers

I can't think of a way to do this using @FormParam but you can use @Context to access the HttpServletRequest (which references a map of all form parameters):

// you can make this a member of the Resource class and access within the Resource methods
@Context
private HttpServletRequest request;

@POST
@Path("/newpage")
@Produces("text/html")
public String func() throws IOException 
{
    // retrieve the map of all form parameters (regardless of how many there are)
    final Map<String, String[]> params = request.getParameterMap();

    // now you can iterate over the key set and process each field as necessary
    for(String fieldName : params.keySet())
    {
        String[] fieldValues = params.get(fieldName);

        // your code goes here
    }
}
like image 71
endeavor Avatar answered Apr 06 '23 05:04

endeavor


The correct answer is actually to use a MultivaluedMap parameter to capture the body (tested using Jersey):

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String post(MultivaluedMap<String, String> formParams)
{
 ... iterate over formParams at will
like image 41
Jason Chown Avatar answered Apr 06 '23 05:04

Jason Chown