【问题标题】:JSON Parameter not being accepted by Spring Data REST ControllerSpring Data REST Controller 不接受 JSON 参数
【发布时间】:2018-02-28 16:37:00
【问题描述】:

我正在创建一个模拟店面的程序。我正在尝试测试输入名称后返回供应商名称的搜索功能。我正在使用 swagger UI 输入返回预期响应的参数。

这里是源代码链接:https://github.com/opensource-io/training_storefront

我正在使用这个实体。我已经修剪了 getter 和 setter,因为它们不相关。

@Entity
@Component
@Scope("prototype")
@Table(name="VENDORS", schema = "TRAINING_STOREFRONT")
public class VendorEntity {

@Id
@Column(name="VENDOR_KEY")
@NotNull
private Integer vendorKey;

@Column(name="VENDOR_NAME")
@NotNull
private String vendorName;
. . .

我正在使用 Spring Data REST 创建 RESTful 存储库。这是我的 Spring Data REST JPA 接口。

@RepositoryRestResource(collectionResourceRel = "vendors", path = "vendors")
public interface VendorRepository extends JpaRepository<VendorEntity, Integer> {

Set<VendorEntity> findByVendorNameContainsIgnoreCase(@Param("vendorName") final String vendorName);

List<VendorEntity> findAllByOrderByVendorKeyAsc();

}

我正在使用 Swagger 记录和测试我的 API。当我使用 Swagger 或 curl 发送参数时:

{ "vendorName" : "Red Hat" }

卷曲

curl -X GET --header 'Content-Type: application/json' --header 'Accept: application/hal+json' -d 'red hat' 'http://localhost:8080/vendors/search/getVendorByVendorNameContainsIgnoreCase

这是返回的内容:

{
  "cause": {
    "cause": null,
    "message": "Value must not be null!"
  },
  "message": "Value must not be null!; nested exception is java.lang.IllegalArgumentException: Value must not be null!"
}

这是预期的:

{
  "content": [
    [
      {
        "vendorKey": 0,
        "vendorName": "string"
      }
    ]
  ],
  "links": [
    {
      "href": "string",
      "rel": "string",
      "templated": true
    }
  ]
}

【问题讨论】:

  • 您要调用什么 REST 方法?你可以发布例如你的 CURL 代码?
  • 它应该是一个带有 URL 参数的 GET 请求。 http://someUrl?vendorName=Red%20Hat
  • 我试图调用“findByVendorNameContainsIgnoreCase”方法。刚刚编辑了帖子以包含 curl 代码。我还尝试了 Alan 的 GET 请求,它奏效了。现在我只需要在我的 URL 中包含那个参数。

标签: java spring jpa spring-data-jpa spring-data-rest


【解决方案1】:

正如 Alan 在 cmets 中指出的那样,在 Spring Data REST 中调用搜索资源时,您应该直接在 URL 中提供搜索参数作为 GET 参数。

文档中没有直接说明,但您可以看到它,例如here.

您的 REST 调用返回此错误,因为您没有提供参数。

正确的 CURL 调用应该是这样形成的:

curl -X GET --header 'Content-Type: application/json' --header 'Accept: application/hal+json' 'http://localhost:8080/vendors/search/getVendorByVendorNameContainsIgnoreCase?vendorName=red%20hat'

不幸的是,Swagger 不能很好地与 Spring Data REST 配合,因此有时会生成令人困惑的示例。

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2021-12-01
    • 2017-02-21
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多