转载

java – PUT和POST失败的未知属性Spring不同的行为

我正在使用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> {}

我使用杰克逊的反序列化功能来禁止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,这个项目中没有其他控制器或存储库.

我认为你所观察到的行为是设计的.当您发布POST时,您正在创建资源,所以JSON被反序列化为您的实体类型,而且Jackson正在执行此任务.

在春季数据休息中,PUT的工作方式不同.有趣的部分在PersistentEntityResourceHandlerMethodArgumentResolver.readPutForUpdate中处理.

json被读入一个JsonNode,实体是从数据存储中读取的,然后在DomainObjectReader.doMerge中执行遍历json字段.它将json应用于实体,并将其保存在控制器实现中.它还会丢弃持久性实体中不存在的所有字段:

if (!mappedProperties.hasPersistentPropertyForField(fieldName)) {
    i.remove();
    continue;
}

这是我从阅读代码中的理解.我想你可以认为这是一个bug.您可以尝试在spring data rest`s jira – https://jira.spring.io/browse/DATAREST 上报告.据我所知,没有办法自定义此行为.

http://stackoverflow.com/questions/34545997/put-and-post-fail-on-unknown-properties-spring-different-behavior

原文  https://codeday.me/bug/20181015/289329.html
正文到此结束
Loading...