Lab08 mvc create order
Goal¶
Using the POST-Redirect-GET pattern, display an HTML form to create a new coffee order.
Don't forget to run *all* tests to make sure everything is still working before continuing.
A. GET Form¶
-
Create an HTML template called
order-coffee-form.html
and put it in thetemplates
directory. The body of the HTML file is as follows:<body> <h1>New Coffee Order:</h1> <form action="/order-coffee" method="post"> <p>Name: <input type="text" name="name"/></p> <p>Size: <input type="text" name="size" value="SMALL"/></p> <p> <input type="submit" value="Order Coffee"/> <input type="reset" value="Clear"/> </p> </form> </body>
-
In the
CoffeeOrderWebController
, create a new method,orderCoffeeForm()
, that mapsGET
requests to/order-coffee
and returns the above html as the view. -
Try it from the browser by going to
locahost:8080/order-coffee
and you should see the form.
B. Process Form¶
Add a processOrderCoffee()
method to your web controller class that:
-
Has a
@PostMapping
annotation, mapping to/order-coffee
-
Takes a parameter
@ModelAttribute("name") String name
that will be the name for the order. -
Create a new
CoffeeOrder
instance with the incomingname
, and a default size ofSMALL
. -
Save the order to the repository and hold on to the
id
that was assigned. -
Redirect to the coffee order view page for this new order
NOTE: Instead of return the name of a view, you're returning a URL, e.g.:
return "redirect:/coffee-order/" + id;
where the
id
is the one assigned by the repository when you saved it.
Once you've completed the above steps,
check in with the instructor before moving on.
C. (optional) Handle Size from Form¶
The form has a field for "size" that you didn't use above. In this section, you'll need to figure out how to use that input to create a coffee with the given Size option.
-
Modify the
processOrderCoffee
method signature to get the size text as a parameter.- Look at how the
name
parameter was passed in
- Look at how the
-
Use the
size
parameter to create the coffee, but if the user chose an invalid size, then useSMALL
as the default.- What if the user types "large" in lower-case?