天天看點

使用 @RequestMapping 來映射 Request 請求與處理器使用 @RequestMapping 來映射 Request 請求與處理器

使用 @RequestMapping 來映射 Request 請求與處理器

         可以使用@RequestMapping 來映射URL 到控制器類,或者是到Controller 控制器的處理方法上。當@RequestMapping 标記在Controller 類上的時候,裡面使用@RequestMapping 标記的方法的請求位址都是相對于類上的@RequestMapping 而言的;當Controller 類上沒有标記@RequestMapping 注解時,方法上的@RequestMapping 都是絕對路徑。這種絕對路徑和相對路徑所組合成的最終路徑都是相對于根路徑“/ ”而言的。

Java代碼  

使用 @RequestMapping 來映射 Request 請求與處理器使用 @RequestMapping 來映射 Request 請求與處理器
  1. @Controller  
  2. public class MyController {  
  3.     @RequestMapping ( "/showView" )  
  4.     public ModelAndView showView() {  
  5.        ModelAndView modelAndView = new ModelAndView();  
  6.        modelAndView.setViewName( "viewName" );  
  7.        modelAndView.addObject( " 需要放到 model 中的屬性名稱 " , " 對應的屬性值,它是一個對象 " );  
  8.        return modelAndView;  
  9.     }  
  10. }   

在這個控制器中,因為MyController 沒有被@RequestMapping 标記,是以當需要通路到裡面使用了@RequestMapping 标記的showView 方法時,就是使用的絕對路徑/showView.do 請求就可以了。

使用 @RequestMapping 來映射 Request 請求與處理器使用 @RequestMapping 來映射 Request 請求與處理器
  1. @RequestMapping ( "/test" )  

   這種情況是在控制器上加了@RequestMapping 注解,是以當需要通路到裡面使用了@RequestMapping 标記的方法showView() 的時候就需要使用showView 方法上@RequestMapping 相對于控制器MyController上@RequestMapping 的位址,即/test/showView.do 。