#SpringMVC返回值有三种情况
返回类型 | 常用注解 |
---|---|
void | |
String | @ResponseBody |
ModelAndView | @ResponseBody |
1.void
返回值为void时,将经过视图解析武器,此时视图解析器将会使用拼接Controller的映射形成页面地址如下生成地址为:void.jsp。一般页面名称不会用映射地址来命名。所以找不到该页面,报错。
所以需要在Controller方法内完成页面的转发和重定向
@RequestMapping("/void")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("void");
//页面转发
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
//页面重定向
response.sendRedirect("/index.jsp");
}~
2.String
返回String时,将经过视图解析器,产生物理地址,将资源发送给浏览器
@RequestMapping("/string")
public String testString(){
System.out.println("string");
// 经过视图解析器解析
// return "success";
// 页面转发,不经过视图解析器
// return "forward:/WEB-INF/pages/success.jsp";
// 页面重定向,不经过视图解析器
return "redirect:/index.jsp";
}~
3.ModelAndView
经过视图解析器找到该资源,完成数据填充,将资源返回到浏览器
@RequestMapping("/modelAndView")
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("hello","world");
modelAndView.setViewName("success");
return modelAndView;
}~