Question

I have a few variables as @PathParam. I want to put them in a Bean and accept all of them in one.

public void show( @PathParam("personId"> String personId, 
                  @PathParam("addressId") String addressId 
                  @Context HttpRequest request) {
       // Code
}

Now I would like to put all of the parameters in a Bean/VO with @Form argument. My class:

class RData {
    private String personId;
    private String addressId;
    private InputStream requestBody;

    @PathParam("personId")
    public void setPersonId(String personId) {
         this.personId = personId;
    }

    @PathParam("addressId")
    public void setAddressId(String addressId) {
         this.addressId = addressId;
    }

    // NOW HERE I NEED TO BIND HttpRequest Context object  to request object in my VO.
    // That is @Context param in the original method.
}

My method would change to:

public void show( @Form RData rData) {
       // Code
}

My VO class above contains what I need to do. So I need to map @Context HttpRequest request to HttpRequest instance variable in my VO. How to do that? Because it does not have an attribute name like @PathParam.

Was it helpful?

Solution

You can inject @Context values into properties just like the form, path, and header parameters.

Example Resource Method:

@POST
@Path("/test/{personId}/{addressId}")
public void createUser(@Form MyForm form)
{
    System.out.println(form.toString());
}    

Example Form Class:

public class MyForm {

    private String personId;
    private String addressId;
    private HttpRequest request;

    public MyForm() {

    }

    @PathParam("personId")
    public void setPersonId(String personId) {
         this.personId = personId;
    }

    @PathParam("addressId")
    public void setAddressId(String addressId) {
         this.addressId = addressId;
    }

    public HttpRequest getRequest() {
        return request;
    }

    @Context
    public void setRequest(HttpRequest request) {
        this.request = request;
    }

    @Override
    public String toString() {
        return String.format("MyForm: [personId: '%s', addressId: '%s', request: '%s']", 
                this.personId, this.addressId, this.request);
    }
}

Url:

http://localhost:7016/v1/test/1/1

Output:

MyForm: [personId: '1', addressId: '1', request: 'org.jboss.resteasy.plugins.server.servlet.HttpServletInputMessage@15d694da']

OTHER TIPS

I thought I would add an answer for those that are using pure JAX-RS not not RestEasy specifically. Faced with the same problem, and surprised that JAX-RS doesn't have out-of-box support for http Form binding to Java Objects, I created a Java API to marshal/unmarshal java objects to forms, and then used that to create a JAX-RS messagebody reader and writer.

https://github.com/exabrial/form-binding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top