【SpringMVC】学习笔记04-结果跳转方式
2022/7/13 6:22:26
本文主要是介绍【SpringMVC】学习笔记04-结果跳转方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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"; }
这篇关于【SpringMVC】学习笔记04-结果跳转方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?