【发布时间】:2016-04-05 09:36:33
【问题描述】:
我正在使用 Spring Data Rest 存储库编写 Spring Boot 应用程序,如果请求正文包含具有未知属性的 JSON,我想拒绝访问资源。简化实体和存储库的定义:
@Entity
public class Person{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
/* getters and setters */
}
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends CrudRepository<Person, Long> {}
我使用 Jackson 的反序列化功能来禁止 JSON 中的未知属性。
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(){
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.failOnUnknownProperties(true);
return builder;
}
当我发送 POST 请求时,一切都按预期工作。当我使用有效字段时,我会得到正确的响应:
curl -i -x POST -H "Content-Type:application/json" -d '{"firstName": "Frodo", "lastName": "Baggins"}' http://localhost:8080/people
{
"firstName": "Frodo",
"lastName": "Baggins",
"_links": {...}
}
当我发送带有未知字段的 JSON 时,应用程序会抛出预期的错误:
curl -i -x POST -H "Content-Type:application/json" -d '{"unknown": "POST value", "firstName": "Frodo", "lastName": "Baggins"}' http://localhost:8080/people
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "unknown" (class Person), not marked as ignorable (2 known properties: "lastName", "firstName")
使用有效 JSON 时的 PUT 方法也会返回正确的响应。但是,当我发送带有未知字段的 PUT 请求时,我希望 Spring 会抛出错误,但 Spring 会更新数据库中的对象并返回它:
curl -i -x PUT -H "Content-Type:application/json" -d '{"unknown": "PUT value", "firstName": "Bilbo", "lastName": "Baggins"}' http://localhost:8080/people/1
{
"firstName": "Bilbo",
"lastName": "Baggins",
"_links": {...}
}
只有当数据库中没有给定id的对象时才会抛出错误:
curl -i -x PUT -H "Content-Type:application/json" -d '{"unknown": "PUT value", "firstName": "Gandalf", "lastName": "Baggins"}' http://localhost:8080/people/100
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "unknown" (class Person), not marked as ignorable (2 known properties: "lastName", "firstName")
是 Spring Data Rest 中的预期行为还是错误?无论请求方法是什么,当将具有未知属性的 JSON 传递给应用程序时,如何抛出错误?
我通过修改 http://spring.io/guides/gs/accessing-data-rest/ 重现了这种行为,我所做的唯一更改是 Jackson2ObjectMapperBuilder ,此项目中没有其他控制器或存储库。
【问题讨论】:
-
你是如何尝试这个解决方案的? http://stackoverflow.com/a/14343479/3710490
-
嗯,现在即使有
POST请求,它也不会抛出异常,我猜它只适用于控制器,我必须添加一些其他 bean 才能使其适用于存储库。我试试看。
标签: java spring spring-data-rest