1.设置ModelAndView对象。根据View的名称,和视图解析器跳转到哦指定的页面。
页面:视图解析器的前缀+viewname+视图解析器的后缀
转发方式
@Override
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse resp) throws Exception {
ModelAndView mv = new ModelAndView();
//封装要显示到视图中的数据
mv.addObject("msg","hello springmvc");
//视图名
mv.setViewName("hello"); //WEB-INF/jsp/hello.jsp
return mv;
}2.通过ServletAPI对象来实现,不需要视图解析器。
通过HttpServletResponse来进行输出。
@RequestMapping("/hello")//映射
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException{
resp.getWriter().println("hello spring mvc use httpservlet api");
} 通过HttpServletResponse实现重定向转发
@RequestMapping("/hello")//映射
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException{
//resp.getWriter().println("hello spring mvc use httpservlet api");
//实现重定向
resp.sendRedirect("index.jsp");
} 通过HttpServletRequest实现转发
@RequestMapping("/hello")//映射
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
//resp.getWriter().println("hello spring mvc use httpservlet api");
//实现重定向
//resp.sendRedirect("index.jsp");
//实现转发
req.setAttribute("msg", "sevlet api forward");
req.getRequestDispatcher("index.jsp").forward(req,resp);
} 3.通过spring mvc 来实现转发和重定向----没有视图解析器
转发的实现1
@RequestMapping("/hello1")
public String hello(){
//转发
return "index.jsp";
}转发的实现2
@RequestMapping("/hello1")
public String hello(){
//转发1
//return "index.jsp";
//转发2
System.out.println("转发2");
return "forward:index.jsp";
}实现重定向
@RequestMapping("/hello1")
public String hello(){
//转发1
//return "index.jsp";
//转发2
//return "forward:index.jsp";
//重定向
return "redirect:index.jsp";
}4.通过spring mvc 来实现转发和重定向----有视图解析器
转发方式
@RequestMapping("/hello2")
public String hello2(){
return "hello";
}注意:
重定向 return "redirect:index.jsp";不需要视图解析器
return "redirect:hello.do";//定向到hello.do
原文地址:http://sdqdwc.blog.51cto.com/11678553/1829588