|
3 | 3 | import org.springframework.beans.factory.annotation.Autowired; |
4 | 4 | import org.springframework.stereotype.Controller; |
5 | 5 | import org.springframework.ui.Model; |
6 | | -import org.springframework.web.bind.annotation.GetMapping; |
7 | | -import org.springframework.web.bind.annotation.PostMapping; |
8 | | -import org.springframework.web.bind.annotation.PatchMapping; |
9 | | -import org.springframework.web.bind.annotation.DeleteMapping; |
| 6 | +import org.springframework.web.bind.annotation.*; |
10 | 7 |
|
11 | 8 | import java.util.List; |
12 | 9 |
|
@@ -40,14 +37,27 @@ public String showPost() { |
40 | 37 | } |
41 | 38 |
|
42 | 39 | @GetMapping("/posts/{postId}/edit") |
43 | | - public String editPost() { |
| 40 | + public String editPost(@PathVariable("postId") long id, Model model) { |
| 41 | + Post post = postRepository.findById(id) |
| 42 | + .orElseThrow(() -> new IllegalArgumentException("Invalid Post Id:" + id)); |
| 43 | + |
| 44 | + model.addAttribute("post", post); |
| 45 | + |
44 | 46 | return "blog/edit"; |
45 | 47 | } |
46 | 48 |
|
47 | | - @PatchMapping("/posts/{postId}") |
48 | | - public String updatePost() { |
49 | | - //TODO: logic responsible for updating a post |
50 | | - return null; |
| 49 | + @PostMapping("/posts/{postId}") |
| 50 | + public String updatePost(@PathVariable("postId") long id, Model model, Post post) { |
| 51 | + Post recordedPost = postRepository.findById(id) |
| 52 | + .orElseThrow(() -> new IllegalArgumentException("Invalid Post Id:" + id)); |
| 53 | + |
| 54 | + recordedPost.setTitle(post.getTitle()); |
| 55 | + recordedPost.setContent(post.getContent()); |
| 56 | + postRepository.save(recordedPost); |
| 57 | + |
| 58 | + model.addAttribute("posts", postRepository.findAll()); |
| 59 | + return "blog/index"; |
| 60 | + |
51 | 61 | } |
52 | 62 |
|
53 | 63 | @DeleteMapping("/posts/{postId}") |
|
0 commit comments