spring boot 302跳转 spring boot 登录跳转 |
您所在的位置:网站首页 › springboot整合thymeleaf跳转html页面 › spring boot 302跳转 spring boot 登录跳转 |
初次做SpringBoot,要解决页面跳转的问题,这个问题我弄了大半天,弄好后,其实也不算个事,写出来给大家提个醒!其实不要使用spring boot的@RestController注解,直接使用spring原来的注解@Controller就可以了。示例如下: @Controller public class ActionController { @RequestMapping(value = "/action",method = RequestMethod.GET) public String index(){ return "login"; } } 如果你的项目如什么都没有配,那么你想跳到login.html时,语句必须是 return "login.html" ,否则它会报错 。因为找不到login文件。 为什么呢?因为@RestController注解,相当于@Controller+@ResponseBody两个注解的结合, @Responsebody后,返回结果直接写入HTTP response body中,不会被解析为跳转路径,所以你总是看到是打印字符串的效果,不是跳转效果。 ========================================================= 请看更详细的解答:SpringBoot里面没有我们之前常规web开发的WebContent(WebApp),它只有src目录,在src/main/resources下面有两个文件夹,[static]和[templates],springboot默认static中放静态页面,而templates中放动态页面,见下图:
静态页面: 静态页面可以直接访问。这里我们直接在static放一个hello.html,然后直接输入http://localhost:8080/hello.html便能成功访问(好像可以新建一个public文件夹,也可以放静态文件)。 也可以通过controller跳转: @Controller public class HelloController { @RequestMapping("/Hi") public String sayHello() { return "redirect:/hello.html"; } }如果不想返回视图,则用@RestController 如果用了静态模板你还想返回static中的页面,那么就要用重定向: 如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return "redirect:/hello.html"。
然后输入http://localhost:8080/Hi就可以成功访问 动态页面: 动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。 要在pom中要添加Thymeleaf组件 org.springframework.boot spring-boot-starter-thymeleaf
然后,在配置文件:application.yml或application.property中加配置: spring.thymeleaf.prefix:classpath: /templates/ spring.thymeleaf.suffix: .html
但你加上了上面的thymeleaf后,你必须重启工程,即使是你配置了热启动后,也要重启工程,才可以看到效果 。 我们先在tempates文件夹中也新建一个hello.html但内容不同,然后先试一下直接访问该页面。输入http://localhost:8080/hello.html:
结果显然访问的是静态文件夹里面的那个hello.html 然后我们现在再试一下用controller:
似乎无法访问到hello.html了。。。这是因为:静态页面的return默认是跳转到/static/index.html,当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/index.html,注意看两者return代码也有区别,动态有或没有html后缀都可以。 也就是我们要这样改controller: @Controller public class HelloController { @RequestMapping("/Hi") public String sayHello() { return "hello";//在没有配置的情况下,return "hello”; 或者return "hello"都可以,它们都会到templates/index.html去。 } }然后就可以成功跳转了 然后我们看看返回一点数据在前端利用Thyemleaf来拿: @Controller public class HelloController { @RequestMapping("/Hi") public ModelAndView sayHello() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("hello"); modelAndView.addObject("key", 12345); //System.out.println("test"); return modelAndView; } } --------------------- Templates/hello.html --------------------- Insert title here this is the hello.html in templates
效果:
如果不想返回视图,则用@RestController 如果用了静态模板你还想返回static中的页面,那么就要用重定向: 如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return "redirect:/index.html"。 几点tips: 1.拦截的url最后不要跟视图重合,否则会抛出Circular view path异常,我之前就是 @Controller public class HelloController { @RequestMapping("/hello") public String sayHello() { return "hello.html"; } }然后就报错说会有个循环视图的错误,反正以后注意就是。
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |