SpringBoot中访问controller中的方法和访问网页的跳转和重定向 |
您所在的位置:网站首页 › 苹果手机不受控制自己跳转界面 › SpringBoot中访问controller中的方法和访问网页的跳转和重定向 |
学完一阵子的Springboot之后开始试着去做点东西出来了,之后,就是一阵的打击,最先面临的就是跳转的问题。不知道大家有没有碰到相同的问题,碰到controller跳转时,想要跳转到同类下的方法,却不知道如何下手。有时候想要实现跳转,却弹出 404。如果,你也遇到相同的情况可以看看这个文章。 正文开始!!! 遇到跳转问题时,一般都是以下几种情况: 1、 地址填写错误 2、 文件找不到 3、 跳转的不是想要的目录下文件 我根据我遇到的问题,总结了一下几种方法。 首先要提到的问题是**@RestController** 它的底层包含了@ResponseBody和@Controller 而@ResponseBody是以JSON的方式返回数据。 如果你使用了@ResponseBody 则 return 返回的字符串只能原样输出在网页上,如下: 所以要谨慎使用!!! 后面也会说使用了@RestController 如何实现跳转 1、return 跳转到界面 (默认访问:templates文件夹下) @RequestMapping("/findAll") public String findAll(){ return "list"; }跳转到 list.html 页面 SpringBoot和springMVC相同会通过视图解析器帮我们实现页面的跳转。 2、return 重定向(默认访问:static文件夹,) @RequestMapping("/findAll") public String findAll(){ return "redirect:test.html"; }与原生Servlet相同 @RequestMapping("/findAll") public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.sendRedirect("test.html"); return; }3、return 重定向到方法 @RequestMapping("/findAll") public String findAll(){ return "redirect:/hello"; } @RequestMapping("/hello") public String testHello(){ return "list"; }与原生Servlet相同 @RequestMapping("/findAll") public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.sendRedirect("/hello"); return; } @RequestMapping("/hello") public String testHello(){ return "list"; }如果你使用了@RestController 则可以使用ModelAndView来返回数据!! ** 4、ModelAndView 跳转到网页(默认访问:templates文件下文件) ** @RequestMapping("/findAll") public ModelAndView findAll() throws IOException { ModelAndView mav = new ModelAndView(); // 加不加后缀名(.html)都可以 mav.setViewName("list.html"); return mav; }** 5、 ModelAndView 跳转到方法** @RequestMapping("/findAll") public ModelAndView findAll() throws IOException { ModelAndView mav = new ModelAndView(); mav.setViewName("redirect:/hello"); return mav; } @RequestMapping("/hello") public String testHello(){ return "list"; }文章到这里就结束了,学习就是这样,很多时候的错误都是出在一些细节上面的处理,希望各位小伙伴,远离bug,生活高歌。 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |