BAEL-4224: Hidden inputs with thymeleaf

This commit is contained in:
Michael Pratt 2020-08-24 09:56:00 -06:00
parent 93587c1ee5
commit c02caaac89
3 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung.thymeleaf.blog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Random;
@Controller
public class BlogController {
@GetMapping("/blog/new")
public String newBlogPost(Model model)
{
// Set a random ID so we can see it in the HTML form
BlogDTO blog = new BlogDTO();
blog.setBlogId(Math.abs(new Random().nextLong() % 1000000));
model.addAttribute("blog", blog);
return "blog/blog-new";
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.thymeleaf.blog;
import java.util.Date;
public class BlogDTO {
private long blogId;
private String title;
private String body;
private String author;
private String category;
private Date publishedDate;
public long getBlogId() {
return blogId;
}
public void setBlogId(long blogId) {
this.blogId = blogId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}

View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hidden Input Examples</title>
</head>
<body>
<h2>Hidden Input Example 1</h2>
<form action="#" method="post" th:action="@{/blog}" th:object="${blog}">
<input type="text" th:field="*{title}">
<input type="text" th:field="*{category}">
<textarea th:field="*{body}"></textarea>
<input type="hidden" th:field="*{blogId}" id="blogId">
<input type="submit">
</form>
<h2>Hidden Input Example 2</h2>
<form action="#" method="post" th:action="@{/blog}" th:object="${blog}">
<input type="text" th:field="*{title}">
<input type="text" th:field="*{category}">
<textarea th:field="*{body}"></textarea>
<input type="hidden" th:value="${blog.blogId}" th:attr="name='blogId'"/>
<input type="submit">
</form>
<h2>Hidden Input Example 3</h2>
<form action="#" method="post" th:action="@{/blog}" th:object="${blog}">
<input type="text" th:field="*{title}">
<input type="text" th:field="*{category}">
<textarea th:field="*{body}"></textarea>
<input type="hidden" th:value="${blog.blogId}" name="blogId"/>
<input type="submit">
</form>
</body>