在之前的项目中,我们在Controller中设置ModelAndView对象来进行结果的跳转。其实除了这一种方式以外,我们还有其他的方式可以跳转结果。
1.设置ModelAndView对象。
虽然之前已经用过了,但为了巩固一下,我们还是简单提一提吧。
根据View的名称和视图解析器跳转到指定的页面。
@RequestMapping("/hello")
public ModelAndView hello(HttpServletRequest req, HttpServletResponse res) {
ModelAndView mv=new ModelAndView();
mv.addObject("msg","hello annotation");
mv.setViewName("hello");
return mv;
}
复制代码
2.通过ServletAPI对象实现
用ServletAPI来实现跳转的话,我们就不需要视图解析器了。
a)用HttpServletResponse来进行输出
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("use httpservlet api");
}
复制代码
b)用HttpServletResponse实现重定向
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.sendRedirect("index.jsp");
}
复制代码
我们要注意的是在maven项目中index.jsp文件是在webapp文件夹中,而Web项目中是在WebRoot文件夹中。
c)通过HttpServletRequest实现转发
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.setAttribute("msg", "use req send message");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
复制代码
3.通过springmvc实现转发和重定向---不使用视图解析器
实现转发
//第一种转发方式
@RequestMapping("/hello1")
public String hello() {
return "index.jsp";
}
//第二种转发方式
@RequestMapping("/hello1")
public String hello() {
return "forward:index.jsp";
}
复制代码
实现重定向
@RequestMapping("/hello1")
public String hello() {
return "redirect:index.jsp";
}
复制代码
4.通过springmvc实现转发和重定向---使用视图解析器
实现转发
@RequestMapping("/hello2")
public String hello2() {
return "hello";
}
复制代码
实现重定向
@RequestMapping("/hello2")
public String hello2() {
//return "hello";
return "redirect:hello.do";
}
复制代码
注:重定向"redirect:index.jsp
"不需要视图解析器
我们看到的是我们重定向到的是一个hello.do,而不是用重定向的方式去跳转到hello.jsp文件。也就是说我们重定向到的是一个index.jsp文件。
重定向是不会用到视图解析器的。所以用springmvc实现重定向,不管你有没有视图解析器都是没有意义的,因为根本就没有用过。
接下来,就是一个我遇到的小问题,如果我们return一个这个"redirect:hello"
,也就是不加.do
,我们可不可以跳转到index.jsp文件呢?答案是不行。不知道大家记不记得我们在web.xml文件里面配置映射加了一个<url-pattern>*.do</url-pattern>
,没错,就是这个拦截了我们的请求。
那么我们关于结果跳转方式的介绍就完成了。