4、重定向、转发
4.1、ModelAndView方式
设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到(转发)指定的页面
页面 : {视图解析器前缀
} + viewName
+{视图解析器后缀
}
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
4.2、ServletAPI方式
通过设置ServletAPI , 不需要视图解析器
- 通过
HttpServletResponse
进行输出;结果直接输出到客户端页面
@RequestMapping("/test1")
public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().print("hello");
}
-
通过
HttpServletResponse
实现重定向地址栏会发生变化;不能指向WEB-INF目录下
@RequestMapping("/test2")
public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 重定向:地址栏会发生变化;不能指向WEB-INF目录下
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
-
通过
HttpServletRequest
实现转发地址栏不会发生变化,会携带request,response;可以指向WEB-INF目录下
@RequestMapping("/test3")
public void test3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 转发:地址栏不会发生变化,会携带request,response;可以指向WEB-INF目录下
request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
}
4.3、SpringMVC方式
1)无视图解析器
- 转发
forward
,默认形式,可以省略forward关键字;地址栏不会发生变化;可以指向WEB-INF目录下
@RequestMapping("/test4")
public String test4(){
// 转发
return "/index.jsp";
}
@RequestMapping("/test5")
public String test5(){
// 转发
return "forward:/index.jsp";
}
- 重定向
redirect
;地址栏会发生变化;不能指向WEB-INF目录下
@RequestMapping("/test6")
public String test6(){
// 重定向
return "redirect:/index.jsp";
}
2)有视图解析器
-
转发
直接return “目标页面”,不用加
forward
,默认形式;地址栏不会发生变化;可以指向WEB-INF目录下因为有视图解析器,转发的页面可以省略前缀、后缀
@RequestMapping("/test7")
public String test7(){
// 转发
return "hello";
}
-
重定向
redirect
;地址栏会发生变化;不能指向WEB-INF目录下不需要视图解析器;
可以重定向到另一个页面(不能指向WEB-INF目录下),也可以重定向到另一个请求
@RequestMapping("/test8")
public String test8(){
// 重定向
// 另一个页面
return "redirect:/index.jsp";
// 另一个请求
//return "redirect:/test7";
}