如何通过springboot发送400/500/404响应错误

@PutMapping("/createUser")

public String createUser(@RequestBody User user) {

    User thisValue = repository.findByUsername(user.getUsername());

    if thisValue != null {

        sendResponseHeaders(400, -1); // wont work

        return "account exist";

    }

    sendResponseHeaders(200, -1); // wont work

    return "reached here";

}

我之前使用的 com.sun.httpserver 有一个 sendResponseheaders 方法,但我在 springboot 上找不到它。有什么办法可以实现这一点吗?基本上就是我想要的。如果我发送带有存在的用户名的 json 请求正文,则应发生 400 响应错误


万千封印
浏览 189回答 3
3回答

九州编程

您可以使用org.springframework.http.ResponseEntity.<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <version>x.x.x.RELEASE</version></dependency>像这样。@PutMapping("/createUser")public ResponseEntity createUser(@RequestBody User user) {    User thisValue = repository.findByUsername(user.getUsername());    if (thisValue != null) {        return ResponseEntity.badRequest().build();    }    return ResponseEntity.ok().build();}

LEATH

除了返回显式 之外ResponseEntity,您还可以抛出在类级别用 注释的异常(或允许异常转义)@ResponseStatus。默认的 Spring MVC 配置将拦截来自控制器方法的任何异常,如果没有注释,则返回 HTTP 500(一般“服务器错误”);如果有,则返回指定的状态。

catspeake

在普通控制器中:@PutMapping("/createUser")public ModelAndView createUser(@RequestBody User user) {&nbsp; &nbsp; ModelAndView mv= new ModelAndView("reached-here");&nbsp; &nbsp; User thisValue = repository.findByUsername(user.getUsername());&nbsp; &nbsp; if (thisValue != null) {&nbsp; &nbsp; &nbsp; &nbsp; model.setStatus(HttpStatus.BAD_REQUEST);&nbsp; &nbsp; &nbsp; &nbsp; model.setValueName("account-exist");&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; model.setStatus(HttpStatus.OK);&nbsp; &nbsp; }&nbsp; &nbsp; return mv;}在 REST 控制器中:@PutMapping("/createUser")public ResponseEntity<String> createUser(@RequestBody User user) {&nbsp; &nbsp; User thisValue = repository.findByUsername(user.getUsername());&nbsp; &nbsp; if (thisValue != null) {&nbsp; &nbsp; &nbsp; &nbsp; return new ResponseEntity<String>("account-exist", HttpStatus.BAD_REQUEST);&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; return new ResponseEntity<String>("reached here", HttpStatus.OK);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java