结果显示到页面上--跳转结果方式

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

页面:视图解析器的前缀+view name+视图解析器的后缀

ModelAndView mav = new ModelAndView();
//封装要显示到视图中的数据
mav.addObject("msg", "hello springmvc");
//视图名
mav.setViewName("hello");//web-inf/jsp/hello.jsp

 

2.如果servletAPI对象来实现--不需要视图解析器的配置

 

  //通过HttpServletResponse来进行输出。
    @RequestMapping("/hello")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        resp.getWriter().println("hello spring mvc use httpservlet api");
    }
  //通过HttpServletResponse实现重定向
    @RequestMapping("/hello")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        resp.sendRedirect("index.jsp");
    }
  //通过HttpServletRequest实现转发
    @RequestMapping("/hello")
    public void hello(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        req.setAttribute("msg", "servlet api forward");
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

3.通过springmvc实现转发和重定向-没有视图解析器

 

//转发的实现1:
@RequestMapping("/hello1")
    public String hello(){
        return "index.jsp";
    }
//转发的实现2:
@RequestMapping("/hello2")
    public String hello(){
        return "forward:index.jsp";
    }
//重定向:
    @RequestMapping("/hello2")
    public String hello(){
        return "redirect:index.jsp";
    }

 

4.通过springmvc实现转发和重定向-有视图解析器

 

//转发:
    @RequestMapping("/hello2")
    public String hello(){
        return "hello";
    }
    //注意:重定向"redirect:index.jsp"不需要视图解析器

 

 

 

 

 

 

 

posted @ 2017-01-28 19:25  Realvie  阅读(286)  评论(0编辑  收藏  举报