@RequestMapping("/itemEdit")
public String itemEdit(HttpServletRequest request, Model model) {
//從Request中取id
String strId = request.getParameter("id");
Integer id = null;
//如果id有值則轉換成int類型
if (strId != null && !"".equals(strId)) {
id = new Integer(strId);
} else {
//出錯
return null;
}
Items items = itemService.getItemById(id);
//創建ModelAndView
//ModelAndView modelAndView = new ModelAndView();
//向jsp傳遞數據
//modelAndView.addObject("item", items);
model.addAttribute("item", items);
//設置跳轉的jsp頁面
//modelAndView.setViewName("editItem");
//return modelAndView;
return "editItem";
}
要根據id查詢商品數據,需要從請求的參數中把請求的id取出來。Id應該包含在Request對象中。可以從Request對象中取id。
如果想獲得Request對象只需要在Controller方法的形參中添加一個參數即可。Springmvc框架會自動把Request對象傳遞給方法。
1.1.1 默認支持的參數類型
處理器形參中添加如下類型的參數處理適配器會默認識別並進行賦值。
1.1.1.1 HttpServletRequest
通過request對象獲取請求信息
1.1.1.2 HttpServletResponse
通過response處理響應信息
1.1.1.3 HttpSession
通過session對象得到session中存放的對象
1.1.1.4 Model/ModelMap
ModelMap是Model接口的實現類,通過Model或ModelMap向頁面傳遞數據,如下:
//調用service查詢商品信息 Items item = itemService.findItemById(id); model.addAttribute("item", item);
頁面通過${item.XXXX}獲取item對象的屬性值。
使用Model和ModelMap的效果一樣,如果直接使用Model,springmvc會實例化ModelMap。
如果使用Model則可以不使用ModelAndView對象,Model對象可以向頁面傳遞數據,View對象則可以使用String返回值替代。不管是Model還是ModelAndView,
其本質都是使用Request對象向jsp傳遞數據。
