import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.apress.prospring3.ch17.domain.Contact;
import com.apress.prospring3.ch17.service.ContactService;
@RequestMapping("/contacts")
@Controller
public class ContactController {
final Logger logger = LoggerFactory.getLogger(ContactController.class);
@Autowired
private ContactService contactService;
@RequestMapping(method = RequestMethod.GET)
public String list(Model uiModel) {
logger.info("Listing contacts");
List<Contact> contacts = contactService.findAll();
uiModel.addAttribute("contacts", contacts);
logger.info("No. of contacts: " + contacts.size());
return "contacts/list";
}
}
As shown in Listing 17-11, the annotation @Controller is applied to the class, indicating that it's a
Spring MVC controller. The @RequestMapping annotation at the class level indicates the root URL that will
be handled by the controller. In this case, all URLs with the prefix /ch17/contacts will be dispatched to
this controller. In the list() method, the @RequestMapping annotation is also applied, but this time the
method is mapped to the HTTP GET method. This means that the URL /ch17/contacts with the HTTP
GET method will be handled by this method. Within the list() method, the list of contacts are retrieved
and saved into the Model interface passed in to the method by Spring MVC. Finally, the logical view name
contacts/list is returned. In the DispatcherServlet configuration, the InternalResourceViewResolver is
configured as the view resolver, and the file has the prefix /WEB-INF/views/ and the suffix .jspx. As a result,
Spring MVC will pick up the file /WEB-INF/views/contacts/list.jspx as the view.
Implement the Contact List View
The next step is to implement the view page for displaying the contact information, which is the file
/src/main/webapp/WEB-INF/views/contacts/list.jspx. Listing 17-12 shows the page content.
Listing 17-12. The Contact List View
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:joda="http://www.joda.org/joda/time/tags"
version="2.0">
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home