设置ModelAndView对象,根据view的名称,和视图解析器跳转到指定的页面。
页面:{视图解析器前缀}+viewName+{视图解析器后缀}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
对应的conctroller类
public class HelloController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //ModelAndView 模型和视图 ModelAndView mv=new ModelAndView(); //调用业务层 //封装对象,放到ModelAndView中。Model mv.addObject("msg","HelloSpringMVC!"); //封装要跳转的视图,放在ModelAndView中 mv.setViewName("hello");// /WEB-INF/jsp/hello.jsp return mv; } }
通过设置ServletAPI , 不需要视图解析器 .
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletResponse实现转发
@Controller public class ResultGo { @RequestMapping("/result/t1") public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.getWriter().println("Hello,Spring BY servlet API"); } @RequestMapping("/result/t2") public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException { rsp.sendRedirect("/index.jsp"); } @RequestMapping("/result/t3") public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception { //转发 req.setAttribute("msg","/result/t3"); req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp); } }
//转发的话 url不会发生变化 @RequestMapping("/m1/t2") public String test20(Model model){ model.addAttribute("msg","不用视图解析器实现抓发"); //转发方式一 return "/WEB-INF/jsp/hello.jsp"; } @RequestMapping("/m1/t3") public String test03(Model model){ model.addAttribute("msg","不适用视图解析器实现转发:forward"); return "forward:/WEB-INF/jsp/hello.jsp"; } @RequestMapping("/m1/t4") public String test04(Model model){ model.addAttribute("msg","不使用视图解析器实现重定向:redirect"); return "redirect:/index.jsp"; }
重定向,不需要视图解析器,本质上就是重新请求一个新地方,所以注意路径问题。
可以重定向到另一个请求实现。
@RequestMapping("/m1/t5") public String test05(Model model){ //转发 model.addAttribute("msg","使用视图解析器实现转发"); return "hello"; } @RequestMapping("/m1/t6") public String test06(Model model){ //重定向 model.addAttribute("msg","使用视图解析器实现重定向"); return "redirect:/index.jsp"; }