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

时间:2014-03-20 14:30:11

标签: spring spring-mvc model-view-controller controller

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

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

6 个答案:

答案 0 :(得分:21)

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
}

答案 1 :(得分:19)

将处理程序方法更改为返回类型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将使用相同的HttpMessageConverter对象转换User对象,就像使用@ResponseBody一样,除非您现在可以更好地控制要返回的状态代码和标头回应。

答案 2 :(得分:2)

使用方法引用运算符::

可能会更短
@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());
}

答案 3 :(得分:0)

enter image description here

@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();
    }
}

答案 4 :(得分:0)

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

public function handleCallback()
    {
        try {
            $user = Socialite::driver('google')->user();
        } catch (\Exception $e) {
            return redirect('/login');
        }
        // only allow users with @company.com to login
        if (explode("@", $user->email)[1] !== 'company.com') {
            return redirect()->to('/');
        }
        // check if they're an existing user
        $existingUser = User::where('email', $user->email)->first();
        if ($existingUser) {
            // log them in
            auth()->login($existingUser, true);
        } else {
            // create a new user
            $newUser                  = new User;
            $newUser->name            = $user->name;
            $newUser->email           = $user->email;
            $newUser->google_id       = $user->id;
            $newUser->avatar          = $user->avatar;
            $newUser->avatar_original = $user->avatar_original;
            $newUser->save();
            auth()->login($newUser, true);
        }
        return redirect()->to('/home');
    }

@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);
    }

答案 5 :(得分:0)

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

return ResponseEntity.of(Optional<user>);

其余部分由以下代码处理

    /**
     * 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());
    }