Search code examples
javaspringspring-web

Spring dynamic HttpStatus from a variable


I have an application where I am returning dynamic HttpStatus code from my controller by using ResponseEntity

return new ResponseEntity<String>("Unrecognised request.", HttpStatus.BAD_REQUEST);

The next requirement is that the response body and the status code will be loaded from database. and the code will looking something like

String msg = <<loaded from database>>;
String status = <<loaded from database>>; //type can be changed to int
return new ResponseEntity<String>(msg, <..what to do here ??..>);

Not the status code will be retrived from database as a string/integer. And as HttpStatus is an Enum, I didn't find any other way to do that.

Is there any solution to my requirement?


Solution

  • If the status code retrieved from the database is always defined as an integer/long/numeric value, you can do similar to this:

    HttpStatus.valueOf(myCoolStatusCode)
    

    Example:

    int someStatusFromDatabase = databaseService.getMeMyStatus();
    String myAwsomeMessage = databaseService.getMeMyStausMessage();
    return ResponseEntity.status(HttpStatus.valueOf(someStatusFromDatabase)).body(myAwsomeMessage);
    

    Hope this helps!