【Mybatis升级版-03】Controller方法的返回值

本文介绍了Spring MVC中Controller方法的返回值类型,包括返回ModelAndView,返回String(逻辑视图名、重定向、页面转发)以及返回void,并详细解析了各种返回方式的用法和特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码还是之前章节的代码,这里不再赘述。

Controller的方法返回值,主要有以下三种:

【1】返回ModelAndView

         需要方法结束时,定义ModelAndView,将model和view分别进行设置,如下code:

@RequestMapping("/item/queryItems")
public ModelAndView queryItems() throws Exception {

    //调用service查找数据库,查询商品列表
    List<ItemsCustom> itemsList = itemsService.findItemsList(null);
    //返回modelAndView
    ModelAndView modelAndView = new ModelAndView();
    // 相当 于request的setAttribute,在jsp页面中通过itemsList取数据
    modelAndView.addObject("itemsList", itemsList);
    // 指定视图
    // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
    // modelAndView.setViewName("/WEB-INF/jsp/item/itemsList.jsp");
    // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
    modelAndView.setViewName("item/itemsList");
    return modelAndView;
}

【2】返回string

如果controller方法返回string,

 2.1 表示返回逻辑视图名

 真正视图(jsp路径)=前缀+逻辑视图名+后缀,code如下:

@RequestMapping("item/editItem")
public String editItem(Model model, @RequestParam(value="id") Integer items_id) throws Exception {

    //调用service根据商品id查询商品信息
    ItemsCustom itemsCustom = itemsService.findItemsById(items_id);

    //通过形参中的model将model数据传到页面
    //相当于modelAndView.addObject方法
    model.addAttribute("itemsCustom", itemsCustom);
    return "item/editItem";
}

2.2 redirect重定向

需求:商品修改提交后,重定向到商品查询列表。

 redirect重定向特点:浏览器地址栏中的url会变化

修改提交的request数据无法传到重定向的地址。因为重定向后重新进行request(request无法共享

//商品信息修改后提交
  @RequestMapping("item/editItemsSubmit")
  public String editItemsSubmit() throws Exception {

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

2.3 forward页面转发

 通过forward进行页面转发,浏览器地址栏url不变,request可以共享。

//商品信息修改后提交
@RequestMapping("item/editItemsSubmit")
public String editItemsSubmit(HttpServletRequest request) throws Exception {

    //重定向到商品查询列表
    //return "redirect:queryItems.action";
    //页面转发
    return "forward:queryItems.action";
}

【3】返回void

在controller方法形参上可以定义request和response,使用request或response指定响应结果:

3.1 使用request转向页面,如下:

request.getRequestDispatcher("页面路径").forward(request,response);

 

3.2 也可以通过response页面重定向:

response.sendRedirect("url")

 

3.3 也可以通过response指定响应结果,例如响应json数据如下:

response.setCharacterEncoding("utf-8");

response.setContentType("application/json;charset=utf-8");

response.getWriter().write("json串");



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值