In our api we are using spring Jackson http message converter to automatically convert java object to json. I am enjoying that feature,but what I personally feel is that I've lost control over the response http status code.if I want to return the response with different status codes ,I have the choice of using @responsestatus(httpstatus),but I cannot specify the status dynamically,as annotation is expecting a enum const expression. The other choice is http server response.set status(),but I don't like that.spring's responseentity(jsonstring,statuscode) is a great thing to solve but if I want to use Jackson httpmessageconverter is any way to configure the response status code dynamically.
1 Answer
You can return ResponseEntity<MyObject> from your controller method and it will still use the configured message converters, example:
@RestController
@RequestMapping("/foo")
public class FooController {
@RequestMapping
public ResponseEntity<MyObject> foo() {
MyObject myObject = new MyObject();
// You can dynamically set the status based on your needs
HttpStatus status = HttpStatus.OK;
return new ResponseEntity<>(myObject, status);
}
}
2 Comments
Sai Surya Kattamuri
logical answer,but is this a standard way of doing?any way to dynamically specify varying code in @responsestatus annotation?
Bohuslav Burghardt
@SaisuryaKattamuri No, at least as far as I know. Parameter of any annotation must be a constant expression, that's given by Java programming language. However if you wanted to retun different status codes in case of exception you could define
@ExceptionHandler method for each exception with @ResponseStatus set appropriately for each one. Based on what do you need to set the status exactly?