Skip to content

Commit 096826c

Browse files
authored
Merge pull request eugenp#4451 from cdjole/thymeleaf_list_example
BAEL-1661 - Binding a List in Thymeleaf
2 parents 293d4bc + c62b0a1 commit 096826c

12 files changed

Lines changed: 421 additions & 0 deletions

File tree

‎spring-mvc-forms-thymeleaf/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
7070
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
7171
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
72+
<start-class>com.baeldung.sessionattrs.SessionAttrsApplication</start-class>
7273
</properties>
7374

7475
</project>
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.baeldung.listbindingexample;
2+
3+
public class Book {
4+
5+
private long id;
6+
7+
private String title;
8+
9+
private String author;
10+
11+
public long getId() {
12+
return id;
13+
}
14+
15+
public void setId(long id) {
16+
this.id = id;
17+
}
18+
19+
public String getTitle() {
20+
return title;
21+
}
22+
23+
public void setTitle(String title) {
24+
this.title = title;
25+
}
26+
27+
public String getAuthor() {
28+
return author;
29+
}
30+
31+
public void setAuthor(String author) {
32+
this.author = author;
33+
}
34+
35+
@Override
36+
public int hashCode() {
37+
final int prime = 31;
38+
int result = 1;
39+
result = prime * result + ((author == null) ? 0 : author.hashCode());
40+
result = prime * result + (int) (id ^ (id >>> 32));
41+
result = prime * result + ((title == null) ? 0 : title.hashCode());
42+
return result;
43+
}
44+
45+
@Override
46+
public boolean equals(Object obj) {
47+
if (this == obj)
48+
return true;
49+
if (obj == null)
50+
return false;
51+
if (getClass() != obj.getClass())
52+
return false;
53+
Book other = (Book) obj;
54+
if (author == null) {
55+
if (other.author != null)
56+
return false;
57+
} else if (!author.equals(other.author))
58+
return false;
59+
if (id != other.id)
60+
return false;
61+
if (title == null) {
62+
if (other.title != null)
63+
return false;
64+
} else if (!title.equals(other.title))
65+
return false;
66+
return true;
67+
}
68+
69+
@Override
70+
public String toString() {
71+
return "Book [id=" + id + ", title=" + title + ", author=" + author + "]";
72+
}
73+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import java.util.List;
4+
5+
public interface BookService {
6+
7+
List<Book> findAll();
8+
9+
void saveAll(List<Book> books);
10+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class BooksCreationDto {
7+
8+
private List<Book> books;
9+
10+
public BooksCreationDto() {
11+
this.books = new ArrayList<>();
12+
}
13+
14+
public BooksCreationDto(List<Book> books) {
15+
this.books = books;
16+
}
17+
18+
public List<Book> getBooks() {
19+
return books;
20+
}
21+
22+
public void setBooks(List<Book> books) {
23+
this.books = books;
24+
}
25+
26+
public void addBook(Book book) {
27+
this.books.add(book);
28+
}
29+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.core.Ordered;
6+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
7+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
8+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
9+
import org.thymeleaf.templatemode.TemplateMode;
10+
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
11+
import org.thymeleaf.templateresolver.ITemplateResolver;
12+
13+
@EnableWebMvc
14+
@Configuration
15+
public class Config implements WebMvcConfigurer {
16+
17+
@Override
18+
public void addViewControllers(ViewControllerRegistry registry) {
19+
registry.addViewController("/").setViewName("index");
20+
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
21+
}
22+
23+
@Bean
24+
public ITemplateResolver templateResolver() {
25+
ClassLoaderTemplateResolver resolver
26+
= new ClassLoaderTemplateResolver();
27+
resolver.setPrefix("templates/books/");
28+
resolver.setSuffix(".html");
29+
resolver.setTemplateMode(TemplateMode.HTML);
30+
resolver.setCharacterEncoding("UTF-8");
31+
return resolver;
32+
}
33+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import org.springframework.stereotype.Service;
4+
5+
import java.util.ArrayList;
6+
import java.util.HashMap;
7+
import java.util.List;
8+
import java.util.Map;
9+
import java.util.function.Function;
10+
import java.util.stream.Collectors;
11+
12+
@Service
13+
public class InMemoryBookService implements BookService {
14+
15+
static Map<Long, Book> booksDB = new HashMap<>();
16+
17+
@Override
18+
public List<Book> findAll() {
19+
return new ArrayList(booksDB.values());
20+
}
21+
22+
@Override
23+
public void saveAll(List<Book> books) {
24+
long nextId = getNextId();
25+
for (Book book : books) {
26+
if (book.getId() == 0) {
27+
book.setId(nextId++);
28+
}
29+
}
30+
31+
Map<Long, Book> bookMap = books.stream()
32+
.collect(Collectors.toMap(
33+
Book::getId, Function.identity()));
34+
35+
booksDB.putAll(bookMap);
36+
}
37+
38+
private Long getNextId(){
39+
return booksDB.keySet().stream()
40+
.mapToLong(value -> value)
41+
.max()
42+
.orElse(0) + 1;
43+
}
44+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6+
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
7+
8+
@SpringBootApplication(
9+
exclude = {SecurityAutoConfiguration.class,
10+
DataSourceAutoConfiguration.class})
11+
public class ListBindingApplication {
12+
13+
public static void main(String[] args) {
14+
SpringApplication.run(ListBindingApplication.class, args);
15+
}
16+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.listbindingexample;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.stereotype.Controller;
5+
import org.springframework.ui.Model;
6+
import org.springframework.web.bind.annotation.GetMapping;
7+
import org.springframework.web.bind.annotation.ModelAttribute;
8+
import org.springframework.web.bind.annotation.PostMapping;
9+
import org.springframework.web.bind.annotation.RequestMapping;
10+
11+
import java.util.ArrayList;
12+
import java.util.List;
13+
14+
@Controller
15+
@RequestMapping("/books")
16+
public class MultipleBooksController {
17+
18+
@Autowired
19+
private BookService bookService;
20+
21+
@GetMapping(value = "/all")
22+
public String showAll(Model model) {
23+
model.addAttribute("books", bookService.findAll());
24+
25+
return "allBooks";
26+
}
27+
28+
@GetMapping(value = "/create")
29+
public String showCreateForm(Model model) {
30+
BooksCreationDto booksForm = new BooksCreationDto();
31+
32+
for (int i = 1; i <= 3; i++) {
33+
booksForm.addBook(new Book());
34+
}
35+
36+
model.addAttribute("form", booksForm);
37+
38+
return "createBooksForm";
39+
}
40+
41+
@GetMapping(value = "/edit")
42+
public String showEditForm(Model model) {
43+
List<Book> books = new ArrayList<>();
44+
bookService.findAll().iterator().forEachRemaining(books::add);
45+
46+
model.addAttribute("form", new BooksCreationDto(books));
47+
48+
return "editBooksForm";
49+
}
50+
51+
@PostMapping(value = "/save")
52+
public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) {
53+
bookService.saveAll(form.getBooks());
54+
55+
model.addAttribute("books", bookService.findAll());
56+
57+
return "redirect:/books/all";
58+
}
59+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<html xmlns:th="http://www.thymeleaf.org">
2+
<head>
3+
<title>All Books</title>
4+
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
5+
</head>
6+
<body>
7+
<div class="container">
8+
<div class="row">
9+
<div class="col-md-12">
10+
<h1> Books </h1>
11+
</div>
12+
</div>
13+
<div class="row">
14+
<div class="col-md-6">
15+
<table class="table">
16+
<thead>
17+
<tr>
18+
<th> Title </th>
19+
<th> Author </th>
20+
</tr>
21+
</thead>
22+
<tbody>
23+
<tr th:if="${books.empty}">
24+
<td colspan="2"> No Books Available </td>
25+
</tr>
26+
<tr th:each="book : ${books}">
27+
<td><span th:text="${book.title}"> Title </span></td>
28+
<td><span th:text="${book.author}"> Author </span></td>
29+
</tr>
30+
</tbody>
31+
</table>
32+
</div>
33+
<div class="col-md-6">
34+
<a class="btn btn-success" href="#" th:href="@{/books/create}"> Add Books </a>
35+
<a class="btn btn-primary" href="#" th:href="@{/books/edit}" th:classappend="${books.empty} ? 'disabled' : ''"> Edit Books </a>
36+
</div>
37+
</div>
38+
</div>
39+
</body>
40+
</html>
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<html xmlns:th="http://www.thymeleaf.org">
2+
<head>
3+
<title>Add Books</title>
4+
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
5+
</head>
6+
<body>
7+
<div class="container">
8+
<div class="row">
9+
<div class="col-md-12">
10+
<h1> Add Books </h1>
11+
</div>
12+
</div>
13+
<div class="row">
14+
<div class="col-md-6">
15+
<a class="btn btn-info" href="#" th:href="@{/books/all}"> Back to All Books </a>
16+
<form action="#" class="form-horizontal"
17+
th:action="@{/books/save}"
18+
th:object="${form}"
19+
method="post">
20+
<fieldset>
21+
<span class="pull-right">
22+
<input type="submit" id="submitButton" class="btn btn-success" th:value="Save">
23+
<input type="reset" id="resetButton" class="btn btn-danger" th:value="Reset"/>
24+
</span>
25+
<table class="table">
26+
<thead>
27+
<tr>
28+
<th> Title</th>
29+
<th> Author</th>
30+
</tr>
31+
</thead>
32+
<tbody>
33+
<tr th:each="book, itemStat : *{books}">
34+
<td><input th:placeholder="Title + ' ' + ${itemStat.count}" th:field="*{books[__${itemStat.index}__].title}" required/></td>
35+
<td><input th:placeholder="Author + ' ' + ${itemStat.count}" th:field="*{books[__${itemStat.index}__].author}" required/></td>
36+
</tr>
37+
</tbody>
38+
</table>
39+
</fieldset>
40+
</form>
41+
</div>
42+
</div>
43+
</div>
44+
</body>
45+
</html>

0 commit comments

Comments
 (0)