SpringMVC--@RequestMapping註解的使用


通過@RequestMapping註解可以定義不同的處理器映射規則。

URL路徑映射

之前我們也經常編寫URL路徑映射,大致可以寫爲:

@RequestMapping("/item"

    或者

    @RequestMapping(value="/item")

      value的值是數組,所以可以將多個url映射到同一個方法上。

      或者

      value=“佔位符”,@PathVariable是用來獲得請求url中的動態參數的
      @Controller
      @RequestMapping("page")
      public class PageController {
      
          @RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET)
          public String toPage(@PathVariable("userId") String userId,@PathVariable("roleId") String roleId) {
      
              System.out.println("User Id : " + userId);  
              System.out.println("Role Id : " + roleId); 
              return "hello";
          }
      }

      窄化請求映射

      在class上添加@RequestMapping(url)指定通用請求前綴, 限制此類下的所有方法請求url必須以請求前綴開頭,通過此方法對url進行分類管理。如下:@RequestMapping放在類名上邊,設置請求前綴。

      @Controller
      @RequestMapping("/item")
      public class ItemController {
      
          ...
      
      }

        然後在方法名上邊設置請求映射url,即@RequestMapping註解應放在方法名上邊,如下:

        @RequestMapping("/itemList")
        public ModelAndView getItemsList() {
            // 查詢商品列表
            List<Items> itemList = itemService.getItemList();
            // 把查詢結果傳遞給頁面
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("itemList", itemList); // addObject方法相當於放到request域上
            // 設置邏輯視圖
            modelAndView.setViewName("itemList"); 
            // 返回結果
            return modelAndView;
        }

          最後在瀏覽器中輸入地址進行訪問時,訪問地址應爲:http://localhost:8080/springmvc-web2/item/itemList.action

          請求方法限定

          • 限定GET方法:@RequestMapping(method = RequestMethod.GET)。
            如果通過post方式訪問則報錯:
            這裏寫圖片描述
            以例明示:

            @RequestMapping(value="/updateitem",method={RequestMethod.GET})
            • 限定POST方法:@RequestMapping(method = RequestMethod.POST)。
              如果通過get方式訪問則報錯:
              這裏寫圖片描述
              以例明示:

              @RequestMapping(value="/updateitem",method={RequestMethod.POST})
              • GET和POST都可以:@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})。
                以例明示:

                @RequestMapping(value="/updateitem",method={RequestMethod.POST,RequestMethod.GET})

                  注意,這兒可能有中文亂碼問題,大家須謹慎對待。

                發佈了51 篇原創文章 · 獲贊 15 · 訪問量 2萬+
                發表評論
                所有評論
                還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
                相關文章