Version: Next
  1. 结果跳转方式
  2. 重定向
  3. 转发

结果跳转方式

ModelAndView

设置ModelAndView对象,根据view的名称,和视图解析器跳转到指定页面

页面:{视图解析器前缀} + viewName + {视图解析器后缀}

原生Servlet

  • 页面响应
  • 重定向
  • 转发
@Controller
public class RESTFulController {
@RequestMapping(path = "/result/t1")
public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().print("Print through Servlet API");
}
@RequestMapping(path = "/result/t2")
public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect("/index.jsp");
}
@RequestMapping(path = "/result/t3")
public void test3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setAttribute("msg","t3");
request.getRequestDispatcher("WEB-INF/jsp/test.jsp").forward(request,response);
}
}

SpringMVC

无视图解析器

通过SpringMVC实现转发和重定向,无需视图解析器

需要将视图解析器注释掉

@Controller
public class RESTFulController {
@RequestMapping(path = "/result/t1")
public String test1() {
//在前面加一个`/`实现转发
return "/index.jsp";
}
@RequestMapping(path = "/result/t2")
public String test2() {
//加上forward:表示转发
return "forward:/index.jsp";
}
@RequestMapping(path = "/result/t3")
public String test3() {
//重定向
return "redirect:/index.jsp";
}
}

有视图解析器

info

重定向不会走视图解析器

@Controller
public class RESTFulController {
@RequestMapping(path = "/result/t1")
public String test1() {
//转发
return "test";
}
@RequestMapping(path = "/result/t2")
public String test2() {
//重定向
//重定向不会走视图解析器拼接
return "redirect:/index.jsp";
}
}