0

如果不存在 id 错误,我想编写一个返回无内容正文的 DELETE 操作。如果 id 不存在,我想重定向到对应的 GET 视图。

控制器代码:

@RequestMapping(value = "/todo/delete/{id}", method = RequestMethod.GET)
public String getDeleteTodo(Model model, @PathVariable("id") String id)
{
    Optional<Todo> todo = todoRepository.findById(Long.decode(id));

    if (todo.isEmpty()) {
        model.addAttribute("msginfo", "ctl-todo.delete.msginfo.id-not-exist");
        model.addAttribute("requestedId", id);
    }
    else {
        model.addAttribute("todo", todo.get());
    }

    return "v-todo-delete";
}

@RequestMapping(value = "/todo/delete/{id}", method = RequestMethod.DELETE)
public String deleteTodo(@PathVariable String id, RedirectAttributes redirAttrs)
{
    boolean exists = todoRepository.existsById(Long.decode(id));

    if (exists) {
        todoRepository.deleteById(Long.decode(id));
        return ""; //here I want to return a no-content body response
    }
    else {
        redirAttrs.addFlashAttribute("msginfo", "ctl-todo.delete.msginfo.id-not-exist");
        redirAttrs.addFlashAttribute("requestedId", id);

        return "redirect:/todo/delete" + id;
    }
}

有关视图的更多信息:

GET 视图只是一个显示与 id 对应的 todo 实体的视图。删除是通过使用 ajax 调用 DELETE 方法的按钮进行的​​。然后响应返回为 204,正文中没有内容,我使用 javascript 将用户重定向到主页...如果 DELETE 方法中不存在 id,我想重定向到 GET 方法以显示错误消息。

如果有人有这样做的想法。提前致谢。

4

2 回答 2

1

尝试将返回类型作为ResponseEntity与任何响应主体以及响应状态一起使用。请参考以下代码更改:

@RequestMapping(value = "/todo/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity deleteTodo(@PathVariable String id, RedirectAttributes redirAttrs)
{
   boolean exists = todoRepository.existsById(Long.decode(id));

   if (exists) {
       todoRepository.deleteById(Long.decode(id));
       return new ResponseEntity(HttpStatus.NO_CONTENT); //This will return No Content status
   }
   else {
       redirAttrs.addFlashAttribute("msginfo", "ctl-todo.delete.msginfo.id-not-exist");
       redirAttrs.addFlashAttribute("requestedId", id);

       return new ResponseEntity( "redirect:/todo/delete" + id, HttpStatus.OK);
   }
}
于 2020-01-12T13:55:08.187 回答
0

我的最终答案:

@RequestMapping(value = "/todo/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteTodo(@PathVariable String id, RedirectAttributes redirAttrs)
{
   boolean exists = todoRepository.existsById(Long.decode(id));

   if (exists) {
       todoRepository.deleteById(Long.decode(id));
       return new ResponseEntity<>(HttpStatus.NO_CONTENT);
   }
   else {
       redirAttrs.addFlashAttribute("msginfo", "ctl-todo.delete.msginfo.id-not-exist");
       redirAttrs.addFlashAttribute("requestedId", id);
       /* I use CONFLICT here to explain that the entity was possibly deleted
          by another user between the moment the user give the view containing
          the DELETE ajax link and the moment he click on it. */
       return new ResponseEntity<String>( "redirect:/todo/delete" + id, HttpStatus.CONFLICT);
   }
}

感谢 Mandar Dharurkar 和 Jeethesh Kotian 的帮助;)

于 2020-01-12T14:46:08.127 回答