Spring Data Rest验证混淆 [英] Spring Data Rest Validation Confusion

查看:21
本文介绍了Spring Data Rest验证混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻求有关正确处理验证错误的 Spring 数据剩余验证的帮助:

Looking for some help with Spring data rest validation regarding proper handling of validation errors:

我对这里关于 spring-data-rest 验证的文档很困惑:http://docs.spring.io/spring-data/rest/docs/current/reference/html/#validation

I'm so confused with the docs regarding spring-data-rest validation here: http://docs.spring.io/spring-data/rest/docs/current/reference/html/#validation

我正在尝试正确处理试图保存新公司实体的 POST 调用的验证

I am trying to properly deal with validation for a POST call that tries to save a new Company entity

我得到了这个实体:

@Entity
public class Company implements Serializable {

@Id
@GeneratedValue
private Long id;

@NotNull
private String name;

private String address;

private String city;

private String country;

private String email;

private String phoneNumber;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
private Set<Owner> owners = new HashSet<>();

public Company() {
    super();
}

...

还有这个 RestResource dao

and this RestResource dao

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RestResource;

import com.domain.Company;

@RestResource
public interface CompanyDao extends PagingAndSortingRepository<Company,   Long> {


}

向 api/公司发出 POST 请求:

POST Request to api/Companies:

{
  "address" : "One Microsoft Way",
  "city" : "Redmond",
  "country" : "USA",
  "email" : "info@microsoft.com",
  "phoneNumber" : "(425) 703-6214"

}

当我发出一个带有空名称的 POST 时,我得到以下带有 httpcode 500 的响应

When I issue a POST with a null name , I get the following rest response with httpcode 500

{"timestamp":1455131008472,"status":500,"error":"内部服务器错误","exception":"javax.validation.ConstraintViolationException","message":"类验证失败 [com.domain.Company] 在组的持续时间内 [javax.validation.groups.Default, ]\n约束违规列表:[\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=name, rootBeanClass=class com.domain.Company, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n]","path":"/api/companies/"}

{"timestamp":1455131008472,"status":500,"error":"Internal Server Error","exception":"javax.validation.ConstraintViolationException","message":"Validation failed for classes [com.domain.Company] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=name, rootBeanClass=class com.domain.Company, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n]","path":"/api/companies/"}

我尝试创建以下 bean,但它似乎什么也没做:

I tried creating the following bean, but it never seems to do anything:

@Component(value="beforeCreateCompanyValidator")
public class BeforeCreateCompanyValidator implements Validator{

@Override
public boolean supports(Class<?> clazz) {
    return Company.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object arg0, Errors arg1) {
    System.out.println("xxxxxxxx");


}

}

即使它确实有效,它如何帮助我使用正确的 http 代码和可理解的 json 响应开发更好的错误响应?

and even if it did work, how would it help me in developing a better error response with a proper http code and understandable json response ?

好纠结

使用 1.3.2.RELEASE

using 1.3.2.RELEASE

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

推荐答案


@马蒂亚斯似乎以下内容足以检查 jsr 303 注释并使其自动返回带有漂亮消息的 400 的 http 代码(我什至不需要 BeforeCreateCompanyValidator 或 BeforeSaveCompanyValidator 类):


@Mathias it seems the following is enough for jsr 303 annotations to be checked and for it to auto return a http code of 400 with nice messages (I dont even need BeforeCreateCompanyValidator or BeforeSaveCompanyValidator classes):

@Configuration
public class RestValidationConfiguration extends RepositoryRestConfigurerAdapter{

@Bean
@Primary
/**
 * Create a validator to use in bean validation - primary to be able to autowire without qualifier
 */
Validator validator() {
    return new LocalValidatorFactoryBean();
}


@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
    Validator validator = validator();
    //bean validation always before save and create
    validatingListener.addValidator("beforeCreate", validator);
    validatingListener.addValidator("beforeSave", validator);
}

}

400 响应:

{
    "errors": [{
        "entity": "Company",
        "message": "may not be null",
        "invalidValue": "null",
        "property": "name"
    }, {
        "entity": "Company",
        "message": "may not be null",
        "invalidValue": "null",
        "property": "address"
    }]
}

这篇关于Spring Data Rest验证混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆