dev@jersey.java.net

Improved parameter handling suggestion

From: Adam Walczak <ja_at_adamwalczak.info>
Date: Wed, 24 Nov 2010 08:33:25 +0100

Hello,

In this letter I have a suggestion on how to improve parameter
handling. I thought about it when I was developing we portal I
mentioned earlier.

If you use JAX-RS as your web framework you'll notice really soon that
you have a problem with standard form handling.

For example empty params and numbers. I have a simple form like this:

<form action="bussinesMethod" method="POST">
...
Age (optional): <input type="text" name="age" />
</form>

and a method

@Path("bussinesMethod")
@POST
public void bussinesMethod(..., @FormParam("age") Integer age) {
...
}

I have no elegant way to handle this age parameter as optional.
Because the form will always give an empty param like "age=" I'll get
a 404 code and a NumberParseException.
I have three ways do go around this but all are a little dirty to me:

1. Change the age parameter to String and parse it my self. No fun if
you use this method also outside JAX-RS.

2. Make a class that extends Integer and has a valueOf method that
returns null if the string is empty and use it for the age param. This
makes the API look strange if you use those classes not only in JAX-RS
because you'll have params like MyInteger, MyDate, MyDouble, etc. To
me this is a hidden API dependency to JAX-RS and is unusable outside
it.

3. Use AJAX to construct params. Additional work.

The above issues are also valid for Date's, Double's, etc.


First of all shouldn't we handle all empty params as null ? what else
could they mean ?
I can only think of situations where it could mean something else for
the Boolean param like http://url/action?doFast but no other.


My suggestion to overcome this it to add an additional provider
interface to Jersey that can override the default parameter
instantiation mechanism.

For the Integer it could look like this:

@Provider
class IntegerCreator implements ParameterCreator<Integer> {

@Override
public Integer create(String value) {
if(value.isEmpty) {
return null;
} else {
return Integer.valueOf(value);
}
}

For the Date param this would be a real life-saver :)

-- 
Adam Walczak
www.adamwalczak.info
+48 604 188 992