在javaspring-boot控制器上返回不同的响应代码



我有一个控制器,如果满足要求,我想返回状态代码205,而不是200

@RequestMapping(value = "/profiles/me", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public UserDto updateProfile(@RequestBody @Validated(ProfileValidation.class) UserDto userDto)
throws Exception {
user = userService.updateProfile(userDto);
token = authenticatedService.getToken();
if(user.getAccountStatus == "NOT_ACTIVATED"){
token = authenticationService
.generateNewSession(new UserAuth.Builder().userId(user.getAcquirerId())
.accountStatus(user.getAccountStatus()).role(user.getRole()).build());
// if this happens, I need to return status code 205
}
return DtoAssembler.assemble(user, token);
}

现在它只在成功请求时返回200

您可以使用ResponseEntity返回不同的http状态代码。以下是如何做到

@RequestMapping(value = "/profiles/me", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDto> updateProfile(@RequestBody @Validated(ProfileValidation.class) UserDto userDto)
throws Exception {
user = userService.updateProfile(userDto);
token = authenticatedService.getToken();
HttpStatus httpSttaus = HttpStatus.OK;
if(user.getAccountStatus == "NOT_ACTIVATED"){
token = authenticationService
.generateNewSession(new UserAuth.Builder().userId(user.getAcquirerId())
.accountStatus(user.getAccountStatus()).role(user.getRole()).build());
httpSttaus = HttpStatus.RESET_CONTENT;
// if this happens, I need to return status code 205
}
UserDto userDto = DtoAssembler.assemble(user, token);
return new ResponseEntity<UserDto>(userDto,httpSttaus);
}

最新更新