0

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 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

logical answer,but is this a standard way of doing?any way to dynamically specify varying code in @responsestatus annotation?
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.