Skip to content

Commit da63ee6

Browse files
committed
Display posts list in /posts page
Adjust BlogController and index.html to display a list of posts when accessing `/posts`
1 parent ab7c032 commit da63ee6

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

myapp/src/main/java/com/example/myapp/BlogController.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,24 @@
22

33
import org.springframework.beans.factory.annotation.Autowired;
44
import org.springframework.stereotype.Controller;
5+
import org.springframework.ui.Model;
56
import org.springframework.web.bind.annotation.GetMapping;
67
import org.springframework.web.bind.annotation.PostMapping;
78
import org.springframework.web.bind.annotation.PatchMapping;
89
import org.springframework.web.bind.annotation.DeleteMapping;
910

11+
import java.util.List;
12+
1013
@Controller
1114
public class BlogController {
1215

1316
@Autowired
1417
private PostRepository postRepository;
1518

1619
@GetMapping("/posts")
17-
public String listPosts() {
20+
public String listPosts(Model model) {
21+
List<Post> posts = postRepository.findAll();
22+
model.addAttribute("posts", posts);
1823
return "blog/index";
1924
}
2025

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
1-
<p>List of Posts</p>
1+
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
2+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
3+
4+
<h1>Blog</h1>
5+
6+
<dl th:each="post : ${posts}">
7+
<dt>
8+
<span th:text="${post.title}">Title</span>
9+
</dt>
10+
11+
<dd>
12+
<span th:text="${post.content}">Content</span>
13+
</dd>
14+
</dl>
15+
16+
<a th:href="@{/posts/new}">Submit a new post</a>
17+

0 commit comments

Comments
 (0)