|  | 
| 1 | 1 | package com.example; | 
| 2 | 2 | 
 | 
| 3 | 3 | import org.springframework.hateoas.Link; | 
| 4 |  | -import org.springframework.hateoas.mvc.ControllerLinkBuilder; | 
| 5 | 4 | import org.springframework.http.HttpHeaders; | 
| 6 |  | -import org.springframework.http.HttpStatus; | 
| 7 | 5 | import org.springframework.http.ResponseEntity; | 
| 8 | 6 | import org.springframework.web.bind.annotation.GetMapping; | 
| 9 | 7 | import org.springframework.web.bind.annotation.PathVariable; | 
| 10 | 8 | import org.springframework.web.bind.annotation.RequestMapping; | 
| 11 | 9 | import org.springframework.web.bind.annotation.RestController; | 
| 12 | 10 | 
 | 
|  | 11 | +import java.net.URI; | 
|  | 12 | +import java.net.URISyntaxException; | 
| 13 | 13 | import java.time.Clock; | 
| 14 | 14 | import java.time.LocalDateTime; | 
| 15 | 15 | 
 | 
| 16 |  | -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; | 
| 17 |  | - | 
| 18 | 16 | @RestController | 
| 19 | 17 | @RequestMapping("/message") | 
| 20 | 18 | public class MessageController { | 
| 21 | 19 | 
 | 
| 22 | 20 |     @GetMapping("/{id}") | 
| 23 |  | -    public ResponseEntity<MessageResource> get(@PathVariable Long id) { | 
|  | 21 | +    public ResponseEntity<MessageResource> get(@PathVariable Long id) throws URISyntaxException { | 
| 24 | 22 |         Message message = new Message(id, "hello", LocalDateTime.now(Clock.systemUTC())); | 
| 25 |  | -        MessageResource messageResource = message.toResource(); | 
| 26 |  | - | 
| 27 |  | -//        1) | 
| 28 |  | -//        Link link = new Link("http://localhost:8080/message/" + id); | 
| 29 |  | -//        2) | 
| 30 |  | -        ControllerLinkBuilder linkBuilder = linkTo(MessageController.class).slash(message); | 
| 31 |  | -        Link link = linkBuilder.withSelfRel(); | 
| 32 | 23 | 
 | 
| 33 |  | -        messageResource.add(link); | 
|  | 24 | +        MessageResourceAssembler assembler = new MessageResourceAssembler(); | 
|  | 25 | +        MessageResource resource = assembler.toResource(message); | 
| 34 | 26 | 
 | 
| 35 | 27 |         HttpHeaders headers = new HttpHeaders(); | 
| 36 |  | -        headers.setLocation(linkBuilder.toUri()); | 
| 37 |  | -        return new ResponseEntity<>(headers, HttpStatus.OK); | 
|  | 28 | +        headers.setLocation(new URI(resource.getLink(Link.REL_SELF).getHref())); | 
|  | 29 | +        return ResponseEntity.ok().headers(headers).body(resource); | 
| 38 | 30 |     } | 
| 39 | 31 | } | 
| 40 | 32 | 
 | 
0 commit comments