首页 > 解决方案 > 如果有错误,Spring Boot 中的 BindingResult 不返回任何内容

问题描述

我尝试在我的服务中测试字段的验证,但是当我将消息放入响应时,不会在邮递员中显示(消息和状态)

我在 Stackoverflow 中搜索了很多我的案例没有答案

实体:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    @NotNull
    private String clientName;

    @Column(name = "date_of_birth", nullable = false)
    @Temporal(TemporalType.DATE)
    /** @JsonFormat(pattern="dd/MM/yyyy") **/ 
    private Date dateOfBirth;

    @Column(nullable = false)
    @NotNull
    private String mobileNumber;

    @Column(nullable = false)
    @NotNull
    @Email(message = "Email should be valid")
    private String email;

    @Column(nullable = false)
    @NotNull
    private String address;

    @Column(nullable = false)
    @NotNull
    private String sex;

    @NotNull(message = "weight cannot be null")
    private Integer weight;

    @NotNull(message = "hight cannot be null")
    private Integer hight;

    @Column(nullable = false)
    @NotNull
    private String healthNote;

    @Column(nullable = false)
    @NotNull
    private String importantNote;

    @Column(nullable = false)
    @NotNull
    private String personToContact;

    @Column(nullable = false)
    @NotNull
    private String relation;

    @Column(nullable = false)
    @NotNull
    private String phoneNumber;

控制器:

    @PostMapping("/uploadProfileClient")
    public ResponseEntity<?> uploadMultipartFile(@Valid @RequestPart("addClient") String clientNew ,@Valid @RequestPart(value = "image")  MultipartFile image,BindingResult result) throws JsonParseException, JsonMappingException, IOException  {

    clientEntity client = null;
    Map<String,Object> response = new HashMap<>();

    if(result.hasErrors()) {
      List<String> errors = result.getFieldErrors().stream().map(err -> "The field '" + err.getField() +"' "+ err.getDefaultMessage()) .collect(Collectors.toList());   
      response.put("Errors",errors);
      return new ResponseEntity<Map<String,Object>>(response, HttpStatus.BAD_REQUEST);
        }
          ObjectMapper mapper = new ObjectMapper();
          client = mapper.readValue(clientNew, clientEntity.class);
          client.setImage(image.getBytes());

        try {
          clientService.save(client);
    } catch (  DataAccessException e) {
        response.put("message", "Error when inserting into the database");
        response.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
        return new ResponseEntity<Map<String,Object>>(response,HttpStatus.INTERNAL_SERVER_ERROR);
    }  
        response.put("message", "the client data has been created successfully!");
        response.put("client", client);     
        return new ResponseEntity<Map<String,Object>>(response,HttpStatus.CREATED);
    }

我会将数据作为 json 和文件发送,邮递员中没有显示响应,请我需要答案。

标签: spring-bootspring-data-jpaspring-datapostmanspring-validator

解决方案


问题很简单,Weight属性接受Integer但你正在发送"weight":"as",这就是你得到Deserialize问题纠正的原因。

试试下面的虚拟数据

{
   "clientName":"foo",
   "dateOfBirth":"2020-03-19",
   "mobileNumber":"9911",
   "email":"asd@email.com",
   "address":"sa",
   "sex":"m",
   "weight":"1",
   "hight":"12",
   "healthNote":"note",
   "importantNote":"imp",
   "personToContact":"myself",
   "relation":"single",
   "phoneNumber":"mynumber"
}

而且您不必手动stringEntity. ObjectMapperSpring可以处理这个所以改变控制器

@PostMapping("/uploadProfileClient")
public ResponseEntity<?> uploadMultipartFile(@Valid @RequestPart("addClient") ClientEntity clientNew ,@Valid @RequestPart(value = "image")  MultipartFile image,BindingResult result) throws JsonParseException, JsonMappingException, IOException  {
   //now you can save clientEntity directly

   client.setImage(image.getBytes());
   clientService.save(client);

  //your logic

} 

更新

如何请求PostMan

在此处输入图像描述


推荐阅读