Вернуть ответные сообщения при весенней загрузке - PullRequest
0 голосов
/ 04 июля 2019

Я работаю с весенней загрузкой с базой данных h2. Я хотел бы вернуть сообщение 201, когда регистр успешно вставлен, и 400, когда дублирован. Я использую ResponseEntity для достижения этого, например, следующий метод создания из службы:

    @Override
    public ResponseEntity<Object> createEvent(EventDTO eventDTO) {
        if (eventRepository.findOne(eventDTO.getId()) != null) {
            //THis is a test, I am looking for the correct message
            return new ResponseEntity(HttpStatus.IM_USED);
        }
        Actor actor = actorService.createActor(eventDTO.getActor());
        Repo repo = repoService.createRepo(eventDTO.getRepo());
        Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
        eventRepository.save(event);
        return new ResponseEntity(HttpStatus.CREATED);
    }

Это мой контроллер:

    @PostMapping(value = "/events")
    public ResponseEntity addEvent(@RequestBody EventDTO body) {
        return eventService.createEvent(body);
    }

Но я не получаю никаких сообщений в браузере, я провожу различные тесты с почтальоном, и когда я консультируюсь со всеми событиями, результат верный, но каждый раз, когда я пишу сообщение, я не получаю никакого сообщения в браузер, я не совсем уверен, что является причиной этой проблемы. Есть идеи?

Ответы [ 2 ]

0 голосов
/ 04 июля 2019

Хорошо, мне действительно не очень приятно, что сервис отправляет ResponseEntity, но не Controller. Вы можете использовать классы @ResponseStatus и ExceptionHandler для этих случаев, как показано ниже.

Создать класс в exception пакете

GlobalExceptionHandler.java

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(DataIntegrityViolationException.class) // NOTE : You could create a custom exception class to handle duplications
    public void handleConflict() {
    }
}

Controller.java

@PostMapping(value = "/events")
@ResponseStatus(HttpStatus.CREATED) // You don't have to return any object this will take care of the status
public void addEvent(@RequestBody EventDTO body) {
   eventService.createEvent(body);
}

Теперь изменение службы будет выглядеть так:

Service.java

@Override
public void createEvent(EventDTO eventDTO) { // No need to return
   if (eventRepository.findOne(eventDTO.getId()) != null) {
        throw new DataIntegrityViolationException("Already exists"); // you have to throw the same exception which you have marked in Handler class
   }
   Actor actor = actorService.createActor(eventDTO.getActor());
   Repo repo = repoService.createRepo(eventDTO.getRepo());
   Event event = new Event(eventDTO.getId(), eventDTO.getType(), actor, repo, createdAt(eventDTO));
   eventRepository.save(event);
}
0 голосов
/ 04 июля 2019

Идеальный способ отправки ответа клиенту - создание DTO / DAO с ResponseEntity в контроллере

Controller.java

@PostMapping("/test")
        public ResponseEntity<Object> testApi(@RequestBody User user)
        {
            System.out.println("User: "+user.toString());
            return assetService.testApi(user);
        }

Service.java

public ResponseEntity testApi(User user) {  
        if(user.getId()==1)
            return new ResponseEntity("Created",HttpStatus.CREATED);
        else
            return new ResponseEntity("Used",HttpStatus.IM_USED);   
           // for BAD_REQUEST(400) return new ResponseEntity("Bad Request",HttpStatus.BAD_REQUEST);
    }

Проверено с почтальоном

Статус 201 Создан Created

Статус 226 IM Используется Status IMUSED

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