我有以下spring控制器代码,并且如果在数据库中找不到用户,想返回not found状态,该怎么办?

@Controller
public class UserController {
  @RequestMapping(value = "/user?${id}", method = RequestMethod.GET)
  public @ResponseBody User getUser(@PathVariable Long id) {
    ....
  }
}

最佳答案

JDK8的方法:

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable Long id) {
    return Optional
            .ofNullable( userRepository.findOne(id) )
            .map( user -> ResponseEntity.ok().body(user) )          //200 OK
            .orElseGet( () -> ResponseEntity.notFound().build() );  //404 Not found
}

09-11 03:50
查看更多