Skip to content

Allow @Controller methods to produce a response with no body and custom headers by returning an HttpHeaders instance [SPR-11129] #15755

@spring-projects-issues

Description

@spring-projects-issues

Andy Wilkinson opened SPR-11129 and commented

Currently, a RESTful create method may be implemented something like this:

@RequestMapping(method = RequestMethod.POST, value = "")
ResponseEntity<Void> create() {
    …

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(…);

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}

I'd like to be able to implement it without having to use ResponseEntity:

@RequestMapping(method = RequestMethod.POST, value = "")
@ResponseStatus(HttpStatus.CREATED)
HttpHeaders create() {
    …

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(…);
        
    return headers;
}

It tried this and was a little surprised to learn that it rendered the headers as the body of a x-www-form-urlencoded response:

MockHttpServletResponse:
              Status = 201
       Error message = null
             Headers = {Content-Type=[application/x-www-form-urlencoded], Content-Length=[43]}
        Content type = application/x-www-form-urlencoded
                Body = Location=http%3A%2F%2Flocalhost%2Fgames%2F1
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

It's often the case that a create method will be the only place where ResponseEntity is needed (see Ben Hale's RESTful API design example for example) so it would be nice for that need to be removed. Secondly, it allows the response status to be declarative making it possible to auto-generate accurate API documentation.

A workaround that enables API documentation generation is to continue using ResponseEntity but to duplicate the response status:

@RequestMapping(method = RequestMethod.POST, value = "")
@ResponseStatus(HttpStatus.CREATED)
ResponseEntity<Void> create() {
    …

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(…);

    return new ResponseEntity<>(headers, HttpStatus.CREATED);
}

Affects: 3.2.5

1 votes, 5 watchers

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions