如何将java对象作为参数传递给restful webservice

Registration_BE包含许多变量,如myvariable 。 我想在这里获得reg_be所有变量。 像这样我必须通过我的对象。

servlet的:

 http://192.168.1.1:8084/UnionClubWS/webresources/customerregistration/?reg_be="+reg_be 

网络服务:

 public String getText(@PathParam("reg_be") Registration_BE reg_be ) { System.out.println("websevice:" +reg_be.myvariable); return reg_be.myvariable; } 

上面的代码抛出此exception:

 com.sun.jersey.spi.inject.Errors$ErrorMessagesException..... 

我怎么解决这个问题?

您可以使用三种典型选项。

将对象变量传递给请求

如果您没有大量变量,或者只需要填充Registration_BE中的一部分字段,这将非常有用。

如果要将变量作为典型的POST传递给请求,则需要进行一些处理以首先构造复杂的Registration_BE对象:

 public String getText(@RequestParam("reg_be.myvariable") String myvariable) { Registration_BE reg_be = new Registration_BE(myvariable); System.out.println("websevice:" +reg_be.myvariable); return reg_be.myvariable; } 

你可以用它来调用它:

 http://192.168.1.1:8084/UnionClubWS/webresources/customerregistration/?reg_be.myvariable=myvalue 

或者通过传入一组变量:

 public String getText(@RequestParam("reg_be.myvariable") String[] myvariables) { Registration_BE reg_be = new Registration_BE(myvariables); System.out.println("websevice:" +reg_be.myvariable); return reg_be.myvariable; } 

你可以用它来调用它:

 http://192.168.1.1:8084/UnionClubWS/webresources/customerregistration/?reg_be.myvariable=myvalue1&reg_be.myvariable=myvalue2 

使用通用数据交换格式

第二个选项是将注册对象作为JSON(或XML)传递。 为此,您需要启用Jackson消息转换器并确保Jackson库在您的类路径中:

     

你的方法不会改变:

 public String getText(@RequestParam("reg_be") Registration_BE reg_be ) { System.out.println("websevice:" +reg_be.myvariable); return reg_be.myvariable; } 

你现在可以用以下方式调用它:

 http://192.168.1.1:8084/UnionClubWS/webresources/customerregistration/?reg_be={"myvariable":"myvalue"} 

自定义消息转换器

您的第三个也是最复杂的选择是创建自己的消息转换器。 这将为您提供最大的灵活性(您的请求可以采用您喜欢的任何forms),但会涉及更多的样板开销以使其工作。

除非您对如何构建请求数据包有非常具体的要求,否则我建议您选择上述选项之一。

如果要将对象paas为path-param或query-param,则需要将其作为字符串传递。 为此,将对象转换为JSON字符串并将其作为查询参数传递。 为此,这是使用JSON的更好方法。

另一个更好的选择是让你的请求发布。 并将您的对象提交给POST方法。 请阅读@FormParam