Skip to content

Commit 415ed6d

Browse files
committed
Create a new post
Add a form to blog/new.html containing Post fields (title and content) and adjust blog controller to handle its creation using JPA Repository.
1 parent 1f6170f commit 415ed6d

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.example.myapp;
22

3+
import org.springframework.beans.factory.annotation.Autowired;
34
import org.springframework.stereotype.Controller;
45
import org.springframework.web.bind.annotation.GetMapping;
56
import org.springframework.web.bind.annotation.PostMapping;
@@ -8,6 +9,10 @@
89

910
@Controller
1011
public class BlogController {
12+
13+
@Autowired
14+
private PostRepository postRepository;
15+
1116
@GetMapping("/posts")
1217
public String listPosts() {
1318
return "blog/index";
@@ -19,9 +24,9 @@ public String newPost() {
1924
}
2025

2126
@PostMapping("/posts")
22-
public String createPost() {
23-
//TODO: logic responsible for saving a post
24-
return null;
27+
public String createPost(Post post) {
28+
postRepository.save(post);
29+
return "redirect:/posts";
2530
}
2631

2732
@GetMapping("/posts/{postId}")
Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
1-
<p>New Post</p>
1+
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
2+
3+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
4+
<body>
5+
<p>New Post</p>
6+
<form method="POST" action="/posts">
7+
<label for="title">Title:</label>
8+
<input type="text" name="title" size="50"></input><br/>
9+
<label for="content">Content:</label><br/>
10+
<textarea name="content" cols="80" rows="5">
11+
</textarea><br/>
12+
<input type="submit"></input>
13+
</form>
14+
</body>
15+
</html>

0 commit comments

Comments
 (0)