对象作为Apache CXF REST服务方法中的参数

时间:2016-05-22 13:56:34

标签: java web-services rest cxf

我需要做的是在Apache CXF中编写的REST API中使用Web服务方法来接受如下所示的请求(最好将自定义对象指定为参数类型)

{ "action":"read", "resource:"new resource" }

现在我的方法可以做同样的事情,但它会期望一个JSON字符串作为请求体。但是我需要服务来向客户端描述请求参数。这意味着在wadl定义中它应该显示应该从客户端发送的确切参数。理想的定义类似于

<resource path="by-attrib">
  <method name="GET">
    <request>
     <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>
   </request>
   <response>
    <representation mediaType="application/json">
      <param name="result" style="plain" type="xs:string"/>
    </representation>
   </response>
</method>
</resource>

CXF可以实现吗? 请注意,使用@FormParam不是我需要的,如果我使用form params,我在使用XML向同一方法发送请求时遇到问题

谢谢

2 个答案:

答案 0 :(得分:0)

实际上我找到了答案

使用bean注入

在他们的文档本身中描述,抱歉不是RTFM

http://cxf.apache.org/docs/jax-rs-basics.html

参数Bean下的

基本思想是使用java Bean(带有setter和getter的零参数构造函数)并将其添加到Web服务参数

但是,您需要指定一个@QueryParam @FormParam @PathParam才能使其正常工作

答案 1 :(得分:0)

CXF和杰克逊的例子

服务界面(使用POST,而不是GET)

@POST
@Path("/yourservice")
@Consumes({ MediaType.APPLICATION_JSON})
@Produces({
        MediaType.APPLICATION_JSON,
        MediaType.APPLICATION_XML})
public Result postYourService(YourData data) throws WebApplicationException;

服务impl(没什么特别的)

public Result postYourService(YourData data){
     Result r = new Result();
     r.setResult("result");
     return r; 
}

数据对象(使用jaxb简化json或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
}

CXF服务器和jackson的弹簧配置。 Jackson提供程序类取决于您使用的是哪个版本的CXF。因此,如果您的cxf包中没有JacksonJaxbJsonProvider,请查看文档

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

        <jaxrs:providers>
            <!--<ref bean="authenticationFilter" />-->
            <!--<ref bean="exceptionMapper" />-->
            <!-- <ref bean="corsFilter" /> -->
            <ref bean="jackson" />
        </jaxrs:providers>
    </jaxrs:server>

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

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

尝试部署并调用

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

我不知道WADL是否能够很好地生成,因为有时CXF会失败。好运!

相关问题