controller方法的返回值

1、返回值为ModelAndView

需要方法接受时,定义ModelAndView,将model和view分别进行设置

@RequestMapping("/queryItems")
public ModelAndView queryItems() throws Exception{
    //调用service查询数据库,查询商品列表
    List itemsList = itemsService.findItemsList(null);    
    //返回ModeAndView
    ModelAndView modelAndView = new ModelAndView();
    //相当于request的setAttribute方法,在jsp页面中通过itemsList取数据
    modelAndView.addObject("itemsList", itemsList);                    
    //指定视图
    modelAndView.setViewName("items/itemsList");             
    return modelAndView;
}


2、返回值为String
如果controller方法返回String,
2.1、表示返回逻辑视图名。

真正的视图(jsp路径)= 前缀 + 逻辑视图名 + 后缀

@RequestMapping(value="/editItems", method={RequestMethod.POST, RequestMethod.GET})
public String editItems(Model model) throws Exception{
    ItemsCustom itemsCustom = itemsService.findItemsById(1);
    model.addAttribute("itemsCustom", itemsCustom);
    return "items/editItems";
}
     2.2、redirect重定向
redirect重定向特点:浏览器地址栏中额的url会变化。修改提交的request数据无法传到重定向的地址。因为重定向后就重新进行request(request无法共享)
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit() throws Exception{
    //重定向
    return "redirect:queryItems.action";
}

2.3、forword页面转发
forword进行页面转发特点:浏览器地址栏中额的url不变。request可以共享 。
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit() throws Exception{
    //页面转发
    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串");






你可能感兴趣的:(java-Spring)