首页 > 解决方案 > 在 Spring Boot 中返回响应消息

问题描述

我正在使用带有 h2 数据库的 spring boot。我想在成功插入寄存器时返回 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);
    }

但是我在浏览器中没有收到任何消息,我正在与邮递员进行不同的测试,当我咨询所有事件时,结果是正确的,但每次我发帖时,我都没有在浏览器中收到任何消息,我不太确定这个问题的原因是什么。有任何想法吗?

标签: spring-boothttp-status-codes

解决方案


好的,我真的觉得发送ResponseEntity但不发送的服务不太好Controller。您可以在这些情况下使用@ResponseStatusExceptionHandler类,如下所示。

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() {
    }
}

控制器.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);
}

现在改变服务看起来像,

服务.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);
}

推荐阅读