Learn Java for Web Development

(Tina Meador) #1
CHAPTER 5: Building Java Web Applications with Spring Web MVC 243

   Lines 25 to 28: This bean declaration tells the framework how to find physical
JSP files according to logical view names returned by the controllers, by
attaching the prefix and the suffix to a view name. For example, if a controller’s
method returns home as logical view name, then the framework will find a
physical file home.jsp under the /WEB-INF/views directory.
 Line 30: <context:component-scan .../> tells the framework which packages
to be scanned when using an annotations-based strategy. Here the framework
will scan all classes under the package com.apress.helloworld. When the
application grows, you can add more configurations for business beans, DAOs,
transactions, and so on.

Now that we have the infrastructure in place to detect the controller that will handle the request,
it’s time to look at the controller.


Note Prior to Spring 2.5, one of the interface-based controllers was used. As of Spring 3.0, the interface-based
controllers have been deprecated in favor of annotated classes.

Listing 5-38 illustrates the code of the controller class HomeController generated by STS.


Listing 5-38. HomeController of the Hello World Application



  1. package com.apress.helloworld;



  2. import java.text.DateFormat;

  3. import java.util.Date;

  4. import java.util.Locale;



  5. import org.slf4j.Logger;

  6. import org.slf4j.LoggerFactory;

  7. import org.springframework.stereotype.Controller;

  8. import org.springframework.ui.Model;

  9. import org.springframework.web.bind.annotation.RequestMapping;

  10. import org.springframework.web.bind.annotation.RequestMethod;



  11. /**



    • Handles requests for the application home page.



  12. */

  13. @Controller

  14. public class HomeController {



  15. private static final Logger logger = LoggerFactory.getLogger(HomeController.class);



  16. /**



    • Simply selects the home view to render by returning its name.



  17. */

  18. @RequestMapping(value = "/", method = RequestMethod.GET)

  19. public String home(Locale locale, Model model) {

Free download pdf