结果跳转ModelAndView
ModelAndView, 根据view的名称,和视图解析器调到指定的页面
页面= {视图解析器前缀}+viewName+{视图解析器后缀}
一个视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
对应Controller类
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "ControllerTest1");
modelAndView.setViewName("test");
return modelAndView;
}
}
1.ServletAPI实现重定向和跳转
通过设置原生的ServletAPI,不需要视图解析器, 我们也能够进行跳转,访问及重定向等操作
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletResponse进行转发
@Controller
public class ForwardController {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Hello,Spring by Servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setAttribute("msg","重定向啦");
//重定向
// 重定向就访问不了被保护的 WEB-INF 目录了!!!
// 由客户端发起二次请求,要带上项目路径!!!
resp.sendRedirect(req.getServletContext().getContextPath()+"/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//转发
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
}
2.springMVC实现重定向和跳转-无视图解析器
springMVC实现重定向和跳转, 无需视图解析器,测试前,需要将视图解析器注释掉
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
//转发
public String test1(Model model) {
model.addAttribute("msg","转发测试1,没有forward:");
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
//转发二
public String test2(Model model) {
model.addAttribute("msg","转发测试2,有!forward:");
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
//重定向
public String test3(Model model) {
model.addAttribute("msg","重定向测试,得加 redirect:");
// 重定向
// 这里和直接用 Servlet 不一样!SpringMVC 会自动补上项目路径!
return "redirect:/index.jsp";
}
}
spring mvc中,
"/index.jsp"前面的 “ / ”就代表是转发的意思
“forward:/index.jsp” 就是显示的告诉springmvc转发,这个时候使用的就是原生的HttpServletResponse
3.springMVC实现重定向和跳转-有视图解析器
重定向,不需要视图解析器,本质就是重新请求一个新地方,所以注意路径的问题,路径会变
视图解析器默认就是转发
可以重定向到另外一个请求实现
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
//springmvc默认输出字符串就是转发
public String test1() {
model.addAttribute("msg","转发测试1,没有forward:");
return "test";
}
@RequestMapping("/rsm/t3")
//重定向
public String test3() {
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do为另一个请求
}
}
总结
方法1和2 做实验了解一下即可,主要还是用有视图解析器的SpringMVC