Skip to content

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

  1. Create an HTML template, named all-coffee-orders.html, in the src/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>
    
  2. Templatize it by adding Thymeleaf text substitution attributes (e.g., th:each and th:text) to the <tr> and <td> tags so that it will pull the content from the list of coffee orders, using the attribute name of coffeeOrders.

    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

  1. 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 CoffeeOrders from the CoffeeOrderRepository via findAll()
    • Iterate through the list, converting the CoffeeOrder objects to CoffeeOrderResponse objects
    • Use model.addAttribute() method to add the list of CoffeeOrderResponse objects with the name "coffeeOrders"
    • Return a String with the name of the html template you created above.
  2. 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.