Skip to content

Lab13 full order

In this lab you'll allow the customer to specify the sweetener and creamer options using a DTO instead of individual model attributes.

A. Create DTO for Form

Create a new DTO, called CoffeeOrderForm that has the following properties (member variables with getters and setters) which are all Strings:

  • name
  • size
  • creamer
  • sweetener

B. Use DTO in POST Method

  1. In the CoffeeOrderWebController, modify the method signature for the POST-mapped method to accept the DTO instead of individual variables. For example, if you had this before:

    @PostMapping("/order-coffee")
    public String processOrderCoffee(@ModelAttribute("name") String name,
                                     @ModelAttribute("size") String size) {
    

    You can replace the ModelAttribute parameters with just the DTO that you created above.

  2. Now create a new CoffeeOrder based on all of the properties that are from the DTO and store it in the Repository.

C. Add Inputs to HTML

In this section, you'll modify the HTML form and add the additional properties that we want to get from the customer.

Thymeleaf Form Object Example

In order to easily use the DTO in the HTML, you'll use the th:object tag and the th:field tag using the *{} syntax. For example in this form:

<form th:action="@{/create-account}" 
      th:object="${createAccountForm}" 
      method="post">
  <p>Name: <input type="text" th:field="*{name}"/></p>
  `
  <p><input type="submit" value="Create Account"/></p>
</form>
  • The ${createAccountForm} refers to the DTO passed in to the model and defines that as the object that will be used for everything inside of the form.

  • The *{name} then refers to the name property from the DTO.

  • Similarly, the *{initialDeposit} refers to the initialDeposit property on the createAccountForm DTO.

Now You Try

Following the example above, modify your coffee-order-form.html to request all four properties using <input type="text"> elements.

Try creating new orders by going to localhost:8080/order-coffee and viewing them on the "All Orders" page.


Once you've completed the above steps,
check in with the instructor to review your code.