Sure! Thymeleaf is a powerful template engine for Java-based applications which integrates well with Spring Boot. Let's create a form that allows for saving multiple cells of multiple lines in a table where each line represents a pizza.
Here's the general structure of your application:
Entity: Define a Pizza class.
Controller: Define a Spring controller to handle form submission.
HTML Form: Use Thymeleaf to create a form with a table.
1. Define the Pizza Entity
First, create a Pizza class to represent the pizza entity:
java
import java.math.BigDecimal;
public class Pizza {
private String name;
private String size;
private BigDecimal price;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSize() { return size; }
public void setSize(String size) { this.size = size; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
}
2. Define the Controller
Next, create a Spring Boot controller to handle the form:
java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/pizzas")
public class PizzaController {
@GetMapping("/new")
public String showForm(Model model) {
List<Pizza> pizzas = new ArrayList<>();
pizzas.add(new Pizza());
pizzas.add(new Pizza());
model.addAttribute("pizzas", pizzas);
return "pizzaForm";
}
@PostMapping("/save")
public String savePizzas(@ModelAttribute("pizzas") List<Pizza> pizzas, Model model) {
// Process the pizzas list
for (Pizza pizza : pizzas) {
System.out.println(pizza.getName() + " - " + pizza.getSize() + " - " + pizza.getPrice());
}
model.addAttribute("message", "Pizzas saved successfully!");
return "pizzaFormSuccess";
}
}
3. HTML Form with Thymeleaf
Finally, create the pizzaForm.html Thymeleaf template for the form:
Note: Ensure you have included the Thymeleaf namespace (xmlns:th="http://www.thymeleaf.org") in your HTML tag.
Form Success Page
Here's the pizzaFormSuccess.html template for the success page:
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Pizza Form Success</title>
</head>
<body>
<h1 th:text="${message}">Success message will be displayed here</h1>
</body>
</html>
Summary
We set up an entity class Pizza.
We created a PizzaController to handle form display and submission.
We used a Thymeleaf template to create a form with a table where each row represents a pizza.
This setup will display a form with multiple rows (each row for a pizza) and allows for the submission of this data to the server. Make sure your project is properly configured with Thymeleaf and Spring Boot.