ModelAndView mv = new ModelAndView(); mv.addObject("msg","ControllerTest1"); mv.setViewName("test");
@Controller public class ControllerTest2 { @RequestMapping("/hello2") public String test1(Model model){ model.addAttribute("msg","ControllerTest2"); return "test"; } }
前两种都是视图解析器帮我们做了页面路径解析:
?
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
SpringMVC的Dispatcher Servlet就是继承了Servlet
虽然使用SpringMVC的过程中我们没有取得Request和Response对象,但是其实也可以使用
@Controller public class ModelTest { ? @RequestMapping("/m1") public String test1(HttpServletRequest req, HttpServletResponse resp){ HttpSession session = req.getSession(); System.out.println(session.getId()); ? return "test"; } }
测试:
我们一样获得了session的id。
我们可以和Servlet一样使用Response实现重定向和Request的转发。这种情况下不需要配置视图解析器。但是不推荐使用。
@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); }
直接return全限定名--转发
?
//直接return全限定名 @Controller public class ModelTest { @RequestMapping("/m1") public String test1(Model model){ model.addAttribute("msg","ModelTest1"); return "/WEB-INF/jsp/test.jsp"; //也可以用这种写法 //return "forward:/WEB-INF/jsp/test.jsp"; } }
测试结果:可以看出URI没有变化,是转发。
这个方法在配置视图解析器的时候也能使用,也就是说配置了视图解析器如果要重定向,就是用这个写法。
@Controller public class ModelTest { @RequestMapping("/m1") public String test1(Model model){ model.addAttribute("msg","ModelTest1"); return "redirect:/index.jsp"; } } ?
原文:https://www.cnblogs.com/renzhongpei/p/12693715.html