How to set respond header values in Spring Boot rest service method?

前端 未结 4 956
情书的邮戳
情书的邮戳 2020-12-28 18:44

Newbie question... I\'m building my first Spring Boot restful service. My restful service design requires some data to be returned in the response header.

How do I

4条回答
  •  暖寄归人
    2020-12-28 19:17

    I was looking for an answer, and I don't like to have to create a response entity. I found the solution on the spring-forums, so credits to the writer.

    In short, you can request the response in the method-declaration, so this can be populated.

    A simple example:

    @RequestMapping(value="/car/{carId}", method = RequestMethod.Get)
    @ResponseBody
    public Car getCarById(@PathVariable("carId") String Id, HttpServletResponse response) {
    
        response.setHeader("X-Special-Header", myCar.getEcoLabel());
        //get the car
        return myCar;
    }
    

    Hope this helps others as well.

    http://forum.spring.io/forum/spring-projects/web-services/102652-setting-header-values-with-spring-rest-controller

提交回复
热议问题