Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I've written a number of articles about using Jersey over the past few months covering various aspects of RESTful services. This article is about passing in an array of values to your Resource from a form.

I'm not going to cover how to set up your application to use with Jersey as I've already covered it here.

So lets get straight into it. The Resource should be set up as follows...
 REST Service Resource
@Path("myresource")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class MyResource {
@POST
@Path("test")
public void testArray(@FormParam("array") List<String> array) {
/* do something with the input array */
for (String s : array) {
System.out.println(s);
}
}


Note that the @Consumes is set to MediaType.APPLICATION_FORM_URLENCODED and the resource uses @POST on the method/path we're exposing to consume an array of values. The @POST is strictly not necessary but it's a better practice to use POST to submit a form rather than GET.

Now that's the Jersey side done, there's actually not much to it.

In order to make this work on the client side you need to be sure that each of your form inputs that you wish to be in the same array have the same name attribute. For example:
 HTML form
<form method="POST" action="/myresource/test">
<input name="array" type="text" />
<input name="array" type="text" />
<input name="array" type="text" />
<input name="array" type="text" />
<input name="array" type="text" />
...
</form>




When this form is submitted, the body of the request will be something like this (with some dummy values substituted):
 POST request
array=This&array=is&array=a&array=cool&array=Blog


Then if you look at the System.out output from the service, it will be something like this:
 System.out
This
is
a
cool
Blog


That's all there is to it. Just get your form method and parameter names right and it should 'just work'.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.