有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Spring数据REST控制器不接受java JSON参数

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

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

我正在使用这个实体。我已经修剪了接球手和二传手,因为它们不相关

@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;
. . .

我正在使用SpringDataREST创建RESTful存储库。这是我的Spring数据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
    }
  ]
}

共 (1) 个答案

  1. # 1 楼答案

    正如Alan在评论中指出的,当在SpringDataREST中调用搜索资源时,您应该在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数据REST,因此有时会生成令人困惑的示例