ManZzup ManZzup - 1 year ago 155
Java Question

Objects as parameters in Apache CXF REST service method

What Exactly i need to do is to have a web service method in a REST API written in Apache CXF to accept a request like the following (preferably specifying a custom object as a parameter type)

"resource:"new resource"

For now my method can do the same but it would expect a JSON string as the request body. But I need the service to describe the request parameters to the client. Meaning that in the wadl definition it should show the exact parameters that should be sent from the client. The ideal definition would be something similar to

<resource path="by-attrib">
<method name="GET">
<param name="Accept" style="header" type="xs:string"/>
<param name="Auth_Type" style="header" type="xs:string"/>
<param name="Authorization" style="header" type="xs:string"/>
<representation mediaType="application/json">
<param name="action" style="plain" type="xs:string"/>
<param name="resource" style="plain" type="xs:string"/>
<representation mediaType="application/json">
<param name="result" style="plain" type="xs:string"/>

Is this possible with CXF?
Please note that using @FormParam is not what I need, if I use form params, I get issues in sending a request using XML to the same method

Thank You

Answer Source

Example with CXF and jackson

The service interface (use POST, not GET)

@Consumes({ MediaType.APPLICATION_JSON})
public Result postYourService(YourData data) throws WebApplicationException;

The service impl (nothing special)

public Result postYourService(YourData data){
     Result r = new Result();
     return r; 

The data objects (Using jaxb to simplify encoding/decoding of json or xml)

@XmlRootElement(name = "YourData")
public class YourData {
    private String action;
    private String resource;
    //getter & setters

@XmlRootElement(name = "Result")
public class Result {
    private String result;
    //getter & setters

The spring configuration of CXF server and jackson. Jackson provider class depends on which version of CXF are you using. Therefore if the JacksonJaxbJsonProvider is not on your cxf package, look at the documentation

<jaxrs:server id="yourServiceREST" address="/services">
            <ref bean="yourService" />

            <!--<ref bean="authenticationFilter" />-->
            <!--<ref bean="exceptionMapper" />-->
            <!-- <ref bean="corsFilter" /> -->
            <ref bean="jackson" />

<bean id="yourService" class="YourServiceImpl">

<bean id="jackson" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />

Try to deploy and invoke to

POST /services/yourservice
{  "action":"read", "resource:"new resource"}

I do not know if WADL is going to be well generated because sometimes CXF fails. Be lucky!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download