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

来源:互联网 发布:解毒丹 知乎 编辑:程序博客网 时间:2024/06/08 02:30

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

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串");



原创粉丝点击