Spring CrudRepository save()没有POST,因为它认为它的参数为null

时间:2017-08-30 11:52:34

标签: spring-security spring-data-jpa spring-el spring-rest

我正在使用Spring Rest 4(spring-boot-starter-data-jpa,spring-boot-starter-data-rest,spring-boot-starter-security)并使用CrudRepository访问我的Org数据。 GET和PUT工作正常,但我的POST一直在浏览器中看到一个空对象。

以下是报告错误的删节版本:

2017-08-30 06:27:00.049 ERROR 1312 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.logicaltiger.exchangeboard.model.Org] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=userId, rootBeanClass=class com.logicaltiger.exchangeboard.model.Org, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=address1, rootBeanClass=class com.logicaltiger.exchangeboard.model.Org, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'}
    ...
] with root cause

javax.validation.ConstraintViolationException: Validation failed for classes [com.logicaltiger.exchangeboard.model.Org] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=userId, rootBeanClass=class com.logicaltiger.exchangeboard.model.Org, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=address1, rootBeanClass=class com.logicaltiger.exchangeboard.model.Org, messageTemplate='{org.hibernate.validator.constraints.NotEmpty.message}'}
    ...
]

以下是从浏览器(Javascript)发送内容的简略版本:

$("#OrgPostBtn").click(function() {
    $.ajax({
        url: "/org",
        type: "POST",
        data: JSON.stringify({  provider: true, name: 'Org NEW', address1: 'Address 24',  [SNIP],  userId: 2 }),
        contentType: "application/json; charset=utf-8",
        headers: createAuthorizationTokenHeader(),
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            console.log("success: data: " + data + ", textStatus: " + textStatus + ", jqXHR: " + jqXHR);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: jqXHR: " + jqXHR + ", textStatus: " + textStatus);
        }
    });
});

这是存储库:

@RepositoryRestResource(path="org")
public interface OrgRepository extends CrudRepository<Org, Long> {

    @Override
    @PostAuthorize("returnObject.userId == principal.id || hasRole('ROLE_ADMIN')")
    public Org findOne(@Param("id") Long id);

    @Override
    @PostFilter("filterObject.user_id == principal.id || hasRole('ROLE_ADMIN')")
    public Iterable<Org> findAll();

}

以下是Org的精简版:

@Entity
@Table(name="org")
public class Org implements Serializable {
    private static final long serialVersionUID = -2808050088097500043L;

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id = Utilities.INVALID_ID;

    @Column(name="provider", nullable=false)
    @NotNull
    private boolean provider;

    @Column(name="name", length=100, nullable=false)
    @NotEmpty
    @Size(max=100)
    private String name;

    @Column(name="address1", length=50, nullable=false)
    @NotEmpty
    @Size(max=50)
    private String address1;

    @Column(name="user_id", nullable=false)
    @NotNull
    private Long userId;

    [SNIP]
}

所以我没有对PUT或POST进行特殊处理,并且PUT处理正常。但我的POST数据无法识别。

这实际上是我原始问题的降级版本,即@PreAuthorize()或@PostAuthorize从以下位置看到了一个空的#entity:

@Override
@SuppressWarnings("unchecked")
@PreAuthorize("#entity.userId == principal.id || hasRole('ROLE_ADMIN')")
public Org save(@Param("entity") Org entity);   

所以......我正在注释保存参数(@Param),或者我根本没有覆盖save()。该程序认为我正在尝试POST一个空对象。

如何使用CrudRepository修复此问题?

提前致谢,

杰罗姆。

1 个答案:

答案 0 :(得分:0)

我已经弄清楚如何为PUT和POST配置此存储库。在授权后使用returnObject,如下所示:

@RepositoryRestResource(path="org")
public interface OrgRepository extends CrudRepository<Org, Long> {

    @Override
    @PostAuthorize("returnObject.userId == principal.id || hasRole('ROLE_ADMIN')")
    public Org findOne(@Param("id") Long id);

    @Override
    @PostFilter("filterObject.userId == principal.id || hasRole('ROLE_ADMIN')")
    public Iterable<Org> findAll();

    @Override
    @SuppressWarnings("unchecked")
    @PostAuthorize("reutrnObject.userId == principal.id || hasRole('ROLE_ADMIN')")

}

有了这个,我得到: 普通用户只能PUT他/她自己的组织记录(userId匹配)。 普通用户可以POST任何东西。 管理员可以PUT或POST任何东西。