January 03, 2013

Jersey : inject Form params into java custom object with @Inject

Working with Jersey, I had to handle search form parameters in a POST method.
Well, with the number of form parameters growing, adding @FormParam in the method signature isn't really a sustainable solution.

Starting to think about how to code this, and looking at how was jersey injecting stuff like Context objects, I was really happy to find out that this feature exists, but isn't really documented.

Yoryos Valotasios found this some times ago, saving me headaches, and published his home made solution that made him realize the feature already exist : http://blog.valotas.com/2011/01/resteasy-form-annotation-for-jersey.html

Thanks to him for saving me time !

Note, this is a Jersey feature, not a JSR 311 one.

So, to the point :

//Resource class
public class CustomerResource { 

  public Response addCustomer(@Inject CustomerFormParam customerForm) {
     // your code

// The handler object
public class CustomerFormParam {

  private String firstName;
  private String lastName;

Well... that's it !

Neat isn't it ?