SpringBoot跳转页⾯详解+thymeleaf
初次做SpringBoot,要解决页⾯跳转的问题,这个问题我弄了⼤半天,弄好后,其实也不算个事,写出来给⼤家提个醒!其实不要使⽤spring boot的@RestController注解,直接使⽤spring原来的注解@Controller就可以了。⽰例如下:
@Controller
public class ActionController {
@RequestMapping(value = \"/action\ 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中放动态页⾯,见下图:
静态页⾯:
也可以通过controller跳转:@Controller
public class HelloController { @RequestMapping(\"/Hi\") public String sayHello() { return \"redirect:/hello.html\"; }}
如果不想返回视图,则⽤@RestController
如果⽤了静态模板你还想返回static中的页⾯,那么就要⽤重定向:
如果在使⽤动态页⾯时还想跳转到/static/index.html,可以使⽤重定向return \"redirect:/hello.html\"。
动态页⾯:
动态页⾯需要先请求服务器,访问后台应⽤程序,然后再转向到页⾯,⽐如访问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后,你必须重启⼯程,即使是你配置了热启动后,也要重启⼯程,才可以看到效果 。
结果显然访问的是静态⽂件夹⾥⾯的那个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\ //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\"; } }
然后就报错说会有个循环视图的错误,反正以后注意就是。