spring boot Thymeleaf 环境搭建

最近后台项目拆分,由于之前APP后台拆分时用的spring-boot,而且一些公用的都以独立模块分离(web、auth、datasource、orm等等),所以后台也用spring-boot,把需要的模块通过maven引入进来就可以了,可以省很多事;前端瞅了瞅,看Thymeleaf不错,跟spring-boot集成也比较好,就选它了。

1、创建一个maven工程,这个应该都会
2、pom文件加入下面内容即可(版本号自己改)

  
    org.springframework.boot
    spring-boot-starter-parent
    1.3.6.RELEASE
  

  
    
      org.springframework.boot
      spring-boot-starter-thymeleaf
    
  

3、写一个入口类(偷懒,控制器也写这里了)

@Controller
@SpringBootApplication
public class Application {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @RequestMapping("/")
    public String toIndex() {
        return "index";
    }
}

4、写个index.html

  • spring boot默认加载文件的路径是
    • /META-INF/resources/
    • /resources/
    • /static/
    • /public/

由于习惯上静态资源还是放到 static下,所以在工程的resources目录下建立一个static目录,static下面可以再建css、js等等目录

  • Thymeleaf是需要写模板,自然也需要一个路径,而它的路径也是在resources下,只需建一个templates文件夹即可

  • 在templates新建一个index.html文件,内容如下:




    首页
    
    
    
    
    


    hi


5、通过前面写的Application入口类运行程序
浏览器输入:http://localhost:8080/
即可看到结果

下面是一些额外配置

在工程的resources目录下创建一个application.properties文件,这个文件是spring-boot用来配置一些工程属性用的

# 配置服务器端口,默认是8080,可以不用配置
server.port=8080
# 模板配置
# 这个开发配置为false,避免改了模板还要重启服务器
spring.thymeleaf.cache=false
# 这个是配置模板路径的,默认就是templates,可不用配置
spring.thymeleaf.prefix=classpath:/templates/
# 这个可以不配置,检查模板位置
spring.thymeleaf.check-template-location=true
# 下面3个不做解释了,可以不配置
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

# 模板的模式
spring.thymeleaf.mode=HTML5

这个mode有6种(2.1版本):

  • XML
  • Valid XML
  • XHTML (默认)
  • Valid XHTML
  • HTML5
  • Legacy HTML5

一般常用的是最后两个,第一个没啥好说的,第二个为了兼容之前的代码,便于向Thymeleaf过度。

官方文档关于这个说明:
除了Legacy HTML5之外,其他模式都必须是闭合的(标签),也就是说不支持不规范的HTML标签写法 (有人说这个是Thymeleaf的坑,其实人家文档开始就说明了)

不规范的写法 such as standalone (not closed) tags, tag attributes without a value or not written between quotes

对于配置了Legacy HTML5模式的情况,Legacy HTML5先转换为规范写法的H5,so官方建议使用H5的代码来写模板

Thymeleaf will first perform a transformation that will convert your files to well-formed XML files which are still perfectly valid HTML5 (and are in fact the recommended way to create HTML5 code)

配置为Legacy HTML5模式,还需要额外引入一个包用来处理代码


      net.sourceforge.nekohtml
      nekohtml
      1.9.22

不知道对那段英文的理解是否有偏差


Thymeleaf 3.0版本有些区别(分为以下几种):

  • HTML (默认)
  • XML
  • TEXT
  • JAVASCRIPT
  • CSS
  • RAW

其中默认是mode是HTML。配置为HTML支持: HTML, HTML5, HTML4 和 XHTML。
无需添加nekohtml包


参考代码

你可能感兴趣的:(spring boot Thymeleaf 环境搭建)