ModelAndView
设置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
通过设置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); } }
SpringMVC实现转发和重定向-无需视图解析器
//转发的话 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";
}
重定向,不需要视图解析器,本质上就是重新请求一个新地方,所以注意路径问题。
通过SpringMVC来实现转发和重定向-有视图解析器
@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"; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。