Default request mapping method

Every Controller class can have one default request mapping method. What is the default request mapping method? If we simply don't specify any request path value in the @RequestMapping annotation of a Controller's method, that method is designated as the default request mapping method for that class. So whenever a request URL just ends up with the Controller's class level request path value without any further relative path down the line, then Spring MVC will invoke this method as a response to that request.

Tip

If you specify more than one default mapping method inside a Controller, you will get IllegalStateException with the message Ambiguous mapping found. So a Controller can have only one default request mapping method at most.

Why not change the welcome method to the default request mapping method for our HomeController class?

  1. In the HomeController class, add the following annotation on top of the class:
          @RequestMapping("/") 
    
  2. And from the welcome method's @RequestMapping annotation, remove the value attribute completely, so now the welcome method will have a plain @RequestMapping annotation without any attributes, as follows:
          @RequestMapping 
          public String welcome(Model model) { 
    
  3. Now you can access the same welcome page under http://localhost:8080/webstore/.

Pop quiz - class level request mapping

If you imagine a web application called Library with the following request mapping on a Controller class level and in the method level, which is the appropriate request URL to map the request to the productDetails method?

@RequestMapping("/books") 
public class BookController { 
... 
 
@RequestMapping(value = "/list") 
public String books(Model model) { 
... 
  1. http://localhost:8080/library/books/list
  2. http://localhost:8080/library/list
  3. http://localhost:8080/library/list/books
  4. http://localhost:8080/library/

Similarly, suppose we have another handler method called bookDetails under BookController as follows, what URL will map to that method?

@RequestMapping 
public String details(Model model) { 
... 
  1. http://localhost:8080/library/books/details
  2. http://localhost:8080/library/books
  3. http://localhost:8080/library/details
  4. http://localhost:8080/library/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.234.114