static和templates部分参考博客:https://blog.csdn.net/wangb_java/article/details/71775637html
热部署参考博客:https://www.cnblogs.com/cx-code/p/8686453.html前端
SpringBoot里面没有咱们以前常规web开发的WebContent(WebApp),它只有src目录java
在src/main/resources下面有两个文件夹,static和templates springboot默认 static中放静态页面,而templates中放动态页面web
静态页面:spring
这里咱们直接在static放一个hello.html,而后直接输入http://localhost:8080/hello.html便能成功访问springboot
(好像能够新建一个public文件夹,也能够放静态文件)服务器
也能够经过controller跳转:app
@Controller public class HelloController { @RequestMapping("/Hi") public String sayHello() { return "hello.html"; } }
而后输入http://localhost:8080/Hi就能够成功访问spring-boot
动态页面:this
动态页面须要先请求服务器,访问后台应用程序,而后再转向到页面,好比访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来作动态页面。
如今pom中要添加Thymeleaf组件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
咱们先在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"; } }
而后就能够成功跳转了
而后咱们看看返回一点数据在前端利用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; } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Insert title here</title> </head> <body> <h1>this is the hello.html in templates</h1> <span th:text="${key}"></span> </body> </html>
效果:
若是不想返回视图,则用@RestController
若是用了静态模板你还想返回static中的页面,那么就要用重定向:
若是在使用动态页面时还想跳转到/static/index.html,可使用重定向return "redirect:/index.html"。
return "redirect:hello.html";
几点tips:
1.拦截的url最后不要跟视图重合,不然会抛出Circular view path异常,我以前就是
@Controller public class HelloController { @RequestMapping("/hello") public String sayHello() { return "hello.html"; } }
而后就报错说会有个循环视图的错误,反正之后注意就是。
2.每次改完都要从新中止应用,再从新启动很烦~但springboot有个叫热部署的东西,就是说在项目中修改代码能够不用从新中止应用再从新启动,能够自动重启,这里咱们用的是devtools:
具体见博客:https://www.cnblogs.com/cx-code/p/8686453.html