Is @ModelAtribute optional in Spring framework?

I’m learning about Spring framework and I want to know if @ModelAttribute is an optional annotation? I ask that because I have this code and I thought that I need to use @ModelAttribute if I want to bind a method parameter with an object from a JSP form. But in this example there is no @ModelAttribute.

The JSP:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Complete Reservation</title>
</head>
<body>
<h2>Complete Reservation</h2>
Airline: ${flight.operatingAirlines}<br/>
Departure City: ${flight.departureCity}<br/>
Arrival City: ${flight.arrivalCity}<br/>

<form action="completeReservation" method="post"/>
<pre>
<h2>Passenger Details:</h2>
First Name:<input type="text" name="passengerFirstName"/>
Last Name:<input type="text" name="passengerLastName"/>
Email:<input type="text" name="passengerEmail"/>
Phone:<input type="text" name="passengerPhone"/>

<h2>Card Details:</h2>
Name on the card:<input type="text" name="nameOnTheCard"/>
Card No:<input type="text" name="cardNumber"/>
Expiry Date:<input type="text" name="expirationDate"/>
Three Digit Sec Code:<input type="text" name="securityCode"/>

<input type="hidden" name="flightId" value="${flight.id}"/>
<input type="submit" value="confirm"/>
</pre>
</form>
</body>
</html>

The controller:

@PostMapping("/completeReservation")
public String completeReservation(ReservationRequest request, ModelMap modelMap) {

    Reservation reservation = reservationService.bookFlight(request);
    modelMap.addAttribute("msg", "Reservation created successfully and the id is " + reservation.getId());

    return "reservationConfirmation";
}

So how does Spring know to bind the object from the form with the method parameter ReservationRequest request? There is no @ModelAttribute in the controller. Thank you!

Leave a Reply

avatar
  Subscribe  
Notify of