Lab11 mvc view all orders
In this lab, you'll create a page that will show a summary of all coffee orders.
Latest Code
If you want to grab the solutions through this point, you can find it at https://github.com/spiral-learning/cvm. You can clone into a new directory and start from there.
A. Create HTML Template¶
-
Create an HTML template, named
all-coffee-orders.html
, in thesrc/main/resources/templates
folder:<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" > <head> <meta charset="UTF-8"> <title>Coffee Orders</title> </head> <body> <table> <tr> <th>Name</th> <th>Price</th> </tr> <tr> <td>Megan</td> <td>225</td> </tr> </table> </body> </html>
-
Templatize it by adding Thymeleaf text substitution attributes (e.g.,
th:each
andth:text
) to the<tr>
and<td>
tags so that it will pull the content from the list of coffee orders, using the attribute name ofcoffeeOrders
.An Example
For example, if we were working with a collection of
products
:<tr th:each="product : ${products}"> <td th:text="${product.name}">Onions</td> <td th:text="${product.price}">2.41</td> </tr>
In this example, Thymeleaf iterates over the "products" collection that it got from Spring's Model, and for each item, it will assign it to the
product
variable. This is similar to Java's "for each" loop structure.
B. Add Mapping to Web Controller¶
-
Open the
CoffeeOrderWebController
, create a GET mapped method to/coffee-orders
that displays all of the orders:- Add a
Model model
as your parameter to the method signature - Get the list of
CoffeeOrder
s from theCoffeeOrderRepository
viafindAll()
- Iterate through the list, converting the
CoffeeOrder
objects toCoffeeOrderResponse
objects - Use
model.addAttribute()
method to add the list ofCoffeeOrderResponse
objects with the name"coffeeOrders"
- Return a
String
with the name of the html template you created above.
- Add a
-
If you access
localhost:8080/coffee-orders/
you should see all of the coffee orders as a two-column table.
Once you've completed the above steps,
check in with the instructor to review your code.