Skip to content

Ease creating Location headers in REST controllers [SPR-8020] #12675

Closed
@spring-projects-issues

Description

@spring-projects-issues

Oliver Drotbohm opened SPR-8020 and commented

With it's annotation model Spring MVC provides a convenient way to write REST based server side components. Unfortunately creating fully-qualified URLs for the Location header (for POST requests especially) requires us to have HttpServletRequest and HttpServletResponse in the controller methods signature just to hand it to a helper method to copy the static part of the request URL (everything up to the servlet context) into a String and piping it back to the response.

So as HttpHeaders already has a setLocation(URI uri) method, I wonder whether Spring MVC could simply "expand" this URI to prepend the path up to the servlet context in case the URI does not start with a protocol string. Beyond that, having a @ResponseHeaders annotation which allows you to bind the response headers to a controller method parameter of type HttpHeaders would round of the support. This way a controller could look something like this:

@Controller
public class CustomerController {

  private static final String CUSTOMERS = "/customers";
  private static final String CUSTOMER = CUSTOMERS + "/{id}";

  @ResponseStatus(HttpStatus.CREATED)
  @RequestMapping(value = CUSTOMERS, method = RequestMethod.POST)
  public void createCustomer(@RequestBody Customer customer, @ResponseHeaders HttpHeaders headers) {
    Customer result = repository.save(customer);
    headers.setLocation(new UriTemplate(CUSTOMER).expand(result.getId()));
  }

  @RequestMapping(value = CUSTOMER, method = RequestMethod.GET)
  public @ResponseBody Customer customer(@PathVariable("id") Long id) {
    return repository.findOne(id);
  }
}

Affects: 3.0.5, 3.1 M1

Referenced from: commits 60ee0bb

3 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