0
点赞
收藏
分享

微信扫一扫

Controller 方法的返回值


返回ModelAndView

方法体内需要定义ModelAndView,对Model和view分别进行设置
@RequestMapping(value="editItems.action",method={RequestMethod.GET,RequestMethod.POST})//限制http请求方法
public ModelAndView editItems()throws Exception{

//调用Service根据id查询商品
ItemsCustomer itemsCustomer = itemsService.findItemsCustomerById(1);


//返回 modelAndView
ModelAndView modelAndView = new ModelAndView();

//将商品信息放到model
modelAndView.addObject("itemsCustomer", itemsCustomer);

//商品修改页面
modelAndView.setViewName("/items/editItems");
return modelAndView;

}


返回String

case one

此时String表示的是逻辑视图名,而数据则通过形参中的model传送到页面
@RequestMapping(value="editItems.action",method={RequestMethod.GET,RequestMethod.POST})//限制http请求方法
public String editItems(Model model)throws Exception{

//调用Service根据id查询商品
ItemsCustomer itemsCustomer = itemsService.findItemsCustomerById(1);

model.addAttribute("itemsCustomer", itemsCustomer);
//将商品信息放到model

return "/items/editItems";

}

什么是逻辑视图名:真正视图(jsp路径)=前缀+逻辑视图名+后缀

case two

redirect重定向
重定向特点:浏览器地址发生变化,修改提交的request数据无法重新出传递到重定向的地址,因为request无法共享
//商品信息修改提交
@RequestMapping("editItemsSubmit.action")
public String editItemsSubmit()throws Exception{

//调用Service更新商品信息,页面需要传递商品信息过来

//重定向到商品查询列表
return "redirect:findItemsList.action";
}


case three

forward 转发
forward特点:浏览器地址不变,request可以共享
//商品信息修改提交
@RequestMapping("editItemsSubmit.action")
public String editItemsSubmit(HttpServletRequest request)throws Exception{

//调用Service更新商品信息,页面需要传递商品信息过来

//重定向到商品查询列表
return "forward:findItemsList.action";
}

测试request共享

//商品查询
@RequestMapping("/findItemsList.action")//建议将url与方法名一致。实现的是方法findItemsList与url进行映射
public ModelAndView findItemsList(HttpServletRequest request)throws Exception{
//测试forwardrequest共享
String id = request.getParameter("id");
System.out.println(id+"==============");

List<ItemsCustomer> itemsList = itemsService.findItemsList(null);
ModelAndView modelAndView = new ModelAndView();
//类似于request的setAttribute
modelAndView.addObject("itemsList", itemsList);
//指定视图

modelAndView.setViewName("/items/itemsList");
return modelAndView;
}


返回void
Controller 方法的返回值_springmvc


举报

相关推荐

0 条评论