spring 如何从弹簧控制器返回未找到状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22536059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:36:44  来源:igfitidea点击:

how to return not found status from spring controller

springspring-mvcmodel-view-controllercontroller

提问by Sergey

I have following spring controller code and want to return not found status if user is not found in database, how to do it?

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

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

回答by wypieprz

JDK8 approach:

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
}

回答by Sotirios Delimanolis

Change your handler method to have a return type of ResponseEntity. You can then return appropriately

将您的处理程序方法更改为具有ResponseEntity. 然后你可以适当地返回

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable Long id) {
    User user = ...;
    if (user != null) {
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

Spring will use the same HttpMessageConverterobjects to convert the Userobject as it does with @ResponseBody, except now you have more control over the status code and headers you want to return in the response.

Spring 将使用与使用相同的HttpMessageConverter对象来转换User对象@ResponseBody,但现在您可以更好地控制要在响应中返回的状态代码和标头。

回答by cdesmetz

Javadoc ResponseEntity

Javadoc 响应实体

@GetMapping(value = "/user/{id}")
public ResponseEntity<User> getUser(@PathVariable final Long id) {
    return ResponseEntity.of(userRepository.findOne(id)));
}

public Optional<User> findOne(final Long id) {
    MapSqlParameterSource paramSource = new MapSqlParameterSource().addValue("id", id);
    try {
        return Optional.of(namedParameterJdbcTemplate.queryForObject(SELECT_USER_BY_ID, paramSource, new UserMapper()));
    } catch (DataAccessException dae) {
        return Optional.empty();
    }
}

回答by Rohit Naik

With the latest update you can just use

使用最新的更新,您可以使用

return ResponseEntity.of(Optional<user>);

The rest is handled by below code

其余由以下代码处理

    /**
     * A shortcut for creating a {@code ResponseEntity} with the given body
     * and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
     * {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of a
     * {@linkplain Optional#empty()} parameter.
     * @return the created {@code ResponseEntity}
     * @since 5.1
     */
    public static <T> ResponseEntity<T> of(Optional<T> body) {
        Assert.notNull(body, "Body mus`enter code here`t not be null");
        return body.map(ResponseEntity::ok).orElse(notFound().build());
    }

回答by Olivier Boissé

it could be shorter using Method Reference operator ::

使用方法引用运算符可能会更短 ::

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(@PathVariable Long id) {
   return Optional.ofNullable(userRepository.findOne(id))
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
}

回答by Aliaksandr Shpak

Need use ResponseEntity or @ResponseStatus, or with "extends RuntimeException"

需要使用 ResponseEntity 或 @ResponseStatus,或使用“extends RuntimeException”

@DeleteMapping(value = "")
    public ResponseEntity<Employee> deleteEmployeeById(@RequestBody Employee employee) {

        Employee tmp = employeeService.deleteEmployeeById(employee);

        return new ResponseEntity<>(tmp, Objects.nonNull(tmp) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
    }

or

或者

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="was Not Found")