Home > Net >  Returns different response codes on java spring boot controller
Returns different response codes on java spring boot controller

Time:12-06

I have a controller and I want to return status code 205 if we meet a requirements instead of 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);

}

Right now it only returns 200 on successful request

CodePudding user response:

You can return different http status code by using ResponseEntity. Here is how to do it

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

}
  • Related