JAX-RS异常:用资源的GET注释,该类未被识别为有效的资源方法

JAX-RS异常:用资源的GET注释,该类未被识别为有效的资源方法,第1张

JAX-RS异常:用资源的GET注释,该类未被识别为有效的资源方法

JAX-RS无法自动将@PathParam(它是一个字符串值)转换为Employee对象。可以从@PathParam自动创建的对象的要求是:

  1. 字符串(事实上,因为数据已经是字符串)
  2. 具有接受(单个)字符串作为参数的构造函数的对象
  3. 具有静态valueOf(String)方法的对象
    对于情况2和3,将需要该对象解析字符串数据并填充其内部状态。通常不会这样做(因为这会迫使您对数据的内容类型进行假设)。对于您的情况(刚开始学习JAX-RS),最好只接受传入的@PathParam数据作为String(或Integer或Long)。
@GET@Path("/emp/{id}")public Response getEmpDetails(@PathParam("id") String empId) {    return Response.status(200).entity(empId).build();}

用GET方法将复杂的对象表示传递给REST服务没有多大意义,除非将其用作例如搜索过滤器。根据您的反馈,这就是您想要做的。实际上,我之前已经在一个项目上执行过此 *** 作(搜索过滤器的通用实现),其中一个警告是您需要严格定义搜索数据的格式。因此,让我们将JSON定义为可接受的格式(您可以根据需要将示例修改为其他格式)。“搜索对象”将作为称为的查询参数传递到服务filter。

@GET@Path("/emp")public Response getEmployees(@QueryParam("filter") String filter) {    // The filter needs to be converted to an Employee object. Use your    // favorite JSON library to convert. I will illustrate the conversion    // with Jackson, since it ships with Jersey    final Employee empTemplate = new ObjectMapper().readValue(filter, Employee.class);    // Do your database search, etc, etc    final String id = getMatchingId(empTemplate);    // return an appropriate response    return Response.status(200).entity(id).build();}

在客户类中:

final String json = new ObjectMapper().writevalueAsString(emp);service    .path("rest")    .path("emp")    .queryParam("filter", json)    .accept(emp, MediaType.TEXT_PLAIN)    .get(String.class)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5093067.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存