BindingResult при загрузке Spring не возвращает ничего, если происходит - PullRequest
0 голосов
/ 09 июля 2019

Я пытаюсь проверить валидацию в моем сервисе для полей, но когда я добавляю сообщение для ответа, не отображать (сообщение и статус) в почтовом человеке

Я много раз искал в Stackoverflow, нет ответа для моегоcase

Entity:

    @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 и файл, ответ не отображается в почтальоне, пожалуйста, мне нужен ответ.

1 Ответ

1 голос
/ 09 июля 2019

Проблема довольно проста, атрибут 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"
}

А также вам не нужно вручную преобразовывать string в Entity, используя ObjectMapper. Пружина справится с этим, поэтому смените контроллер

@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

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...