java在未知属性上的PUT和POST失败会引发不同的行为
我正在使用Spring数据Rest存储库编写Spring引导应用程序,如果请求体包含具有未知属性的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数据Rest中的错误当具有未知属性的JSON被传递到应用程序时,无论请求方法是什么,我如何抛出错误
我通过修改http://spring.io/guides/gs/accessing-data-rest/复制了这种行为,我所做的唯一更改是Jackson2ObjectMapperBuilder
,此项目中没有其他控制器或存储库
共 (0) 个答案