What is the preferred way to specify an HTTP “Location” Response Header in Spring MVC 3?

前端 未结 5 789
名媛妹妹
名媛妹妹 2020-12-28 12:29

What is the preferred way to specify an HTTP \"Location\" Response Header in Spring MVC 3?

As far as I can tell, Spring will only provide a \"Location\" in response

5条回答
  •  隐瞒了意图╮
    2020-12-28 13:16

    The following example is from spring tutorial:

    @RequestMapping(method = RequestMethod.POST)
    ResponseEntity add(@PathVariable String userId, @RequestBody Bookmark input) {
        this.validateUser(userId);
    
        return this.accountRepository
                .findByUsername(userId)
                .map(account -> {
                    Bookmark result = bookmarkRepository.save(new Bookmark(account,
                            input.uri, input.description));
    
                    URI location = ServletUriComponentsBuilder
                        .fromCurrentRequest().path("/{id}")
                        .buildAndExpand(result.getId()).toUri();
    
                    return ResponseEntity.created(location).build();
                })
                .orElse(ResponseEntity.noContent().build());
    
    }
    

    Take note that the following will compute the context path (URI) for you avoiding code duplication and making your application more portable:

    ServletUriComponentsBuilder
                        .fromCurrentRequest().path("/{id}")
    

提交回复
热议问题