This example describes how to use Spring to write controllers to build the model that your page ultimately uses.
-
Declare the annotated controller in its own Java bean. For example:
@Controller public class HotelsController { private TravelService travelService; @Autowired public HotelsController(TravelService travelService) { this.travelService = travelService; } @RequestMapping("/hotels") public void getHotels(SearchCriteria criteria, Model model) { List<Hotel> hotels = travelService.findHotels(criteria); model.addAttribute("hotelList", hotels); } }
This Java bean is annotated to inform Spring to bind to the incoming URL of /hotels. When the Spring MVC dispatcher servlet must identify the controller that can handle the incoming URL, it consults these annotations to find your bean. As you can see by the code, all the “heavy lifting” is done inside the bean. It calls out to the travelService to retrieve a list of hotel properties, places these into the model, and then returns it. In this example, you are populating the model in the controller. So far, this is all Spring Web MVC.
-
Adjust your Surf template to use this model data. For example:
<html> <body> <table> <#if hotelList?size == 0> <tr> <td colspan="2">No hotels found</td> </tr> <#else> <#list hotelList as hotel> <tr> <td>${hotel.name}</td> <td>${hotel.address}</td> </tr> </#list> </#if> </table> </body> </html>