springboot整合thymeleaf+tiles示例

网上关于此框架的配置实在不多,因此想记录下来以防忘记

因为公司框架基于上述(公司采用gradle构建项目,楼主采用的是maven),所以楼主能少走些弯路;

1.创建springboot-maven项目(具体创建步骤自行研究)

2.接下来配置引入相关jar包 如下贴出本项目所有maven依赖

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0"
  3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelVersion>4.0.0</modelVersion>
  6     <groupId>com.xxx</groupId>
  7     <artifactId>spring-boot</artifactId>
  8     <version>1.0-SNAPSHOT</version>
  9     <parent>
 10         <groupId>org.springframework.boot</groupId>
 11         <artifactId>spring-boot-starter-parent</artifactId>
 12         <version>1.5.6.RELEASE</version>
 13         <relativePath/> <!-- lookup parent from repository -->
 14     </parent>
 15 
 16     <properties>
 17         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 19         <java.version>1.8</java.version>
 20     </properties>
 21 
 22     <dependencies>
 23         <!--spring boot 整合 mybatis 依赖-->
 24         <dependency>
 25             <groupId>org.mybatis.spring.boot</groupId>
 26             <artifactId>mybatis-spring-boot-starter</artifactId>
 27             <version>1.3.0</version>
 28         </dependency>
 29         <!--spring boot web依赖,,必须的-->
 30         <dependency>
 31             <groupId>org.springframework.boot</groupId>
 32             <artifactId>spring-boot-starter-web</artifactId>
 33         </dependency>
 34         <!--spring boot 测试依赖-->
 35         <dependency>
 36             <groupId>org.springframework.boot</groupId>
 37             <artifactId>spring-boot-starter-test</artifactId>
 38             <scope>test</scope>
 39         </dependency>
 40         <!--数据库连接jdbc依赖-->
 41         <dependency>
 42             <groupId>org.springframework.boot</groupId>
 43             <artifactId>spring-boot-starter-jdbc</artifactId>
 44         </dependency>
 45         <!--mysql数据库驱动-->
 46         <dependency>
 47             <groupId>mysql</groupId>
 48             <artifactId>mysql-connector-java</artifactId>
 49             <version>5.1.40</version>
 50         </dependency>
 51         <!-- 数据库连接池 -->
 52         <dependency>
 53             <groupId>com.alibaba</groupId>
 54             <artifactId>druid</artifactId>
 55             <version>1.1.0</version>
 56         </dependency>
 57         <!--thymeleaf模板-->
 58         <dependency>
 59             <groupId>org.springframework.boot</groupId>
 60             <artifactId>spring-boot-starter-thymeleaf</artifactId>
 61         </dependency>
 62         <dependency>
 63             <groupId>nekohtml</groupId>
 64             <artifactId>nekohtml</artifactId>
 65             <version>1.9.6.2</version>
 66         </dependency>
 67         <!--集成redis-->
 68         <dependency>
 69             <groupId>org.springframework.boot</groupId>
 70             <artifactId>spring-boot-starter-redis</artifactId>
 71             <version>1.4.5.RELEASE</version>
 72         </dependency>
 73         <dependency>
 74             <groupId>org.springframework.session</groupId>
 75             <artifactId>spring-session-data-redis</artifactId>
 76         </dependency>
 77         <!--添加tiles布局模板支持 -->
 78         <dependency>
 79             <groupId>org.thymeleaf.extras</groupId>
 80             <artifactId>thymeleaf-extras-tiles2-spring4</artifactId>
 81             <version>2.1.1.RELEASE</version>
 82         </dependency>
 83         <!--添加jstl -->
 84         <dependency>
 85             <groupId>javax.servlet</groupId>
 86             <artifactId>jstl</artifactId>
 87         </dependency>
 88         <!--添加对jsp的支持 -->
 89         <dependency>
 90             <groupId>org.apache.tomcat.embed</groupId>
 91             <artifactId>tomcat-embed-jasper</artifactId>
 92             <scope>provided</scope>
 93         </dependency>
 94         <dependency>
 95             <groupId>org.springframework.session</groupId>
 96             <artifactId>spring-session</artifactId>
 97             <version>1.3.0.RELEASE</version>
 98         </dependency>
 99     </dependencies>
100     <build>
101         <plugins>
102             <plugin>
103                 <groupId>org.springframework.boot</groupId>
104                 <artifactId>spring-boot-maven-plugin</artifactId>
105             </plugin>
106         </plugins>
107     </build>
108 </project>
View Code

接下来配置thymeleaf在application-dev.yml中

 1 spring:
 2     #redis服务器相关配置
 3     redis:
 4         sentinel:
 5           master:
 6           nodes:
 7         host: 127.0.0.1
 8         password:
 9         port: 6379
10         pool:
11           min-idle: 20
12           max-idle: 20
13           max-active: 100
14           max-wait: -1
15         timeout: 1000
16         #通过@Cacheable代理的缓存默认失效时间(单位:秒)
17         cacheableDefaultExpSec: 12000
18     session:
19         store-type:
20           none
21     datasource:
22         dialect: mysql
23         url: 'root'
24         username: 'root'
25         password: 'root'
26         driver-class-name: 'com.mysql.jdbc.Driver'
27         type: com.alibaba.druid.pool.DruidDataSource
28         initialSize: 1
29         minIdle : 5
30         maxActive: 10
31         maxWait: 60000
32         timeBetweenEvictionRunsMillis: 60000
33         minEvictableIdleTimeMillis: 300000
34         validationQuery: SELECT 'x'
35         testWhileIdle: true
36         testOnBorrow: false
37         testOnReturn: false
38         poolPreparedStatements: true
39         maxPoolPreparedStatementPerConnectionSize: 20
40         filters: stat,wall,slf4j
41         connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
42         useGlobalDataSourceStat: true
43         monitorUserName: admin
44         monitorPassword: admin
45         resetEnable: false
46         allow:
47         deny:
48         exclusions:
49     thymeleaf:
50         # tiles 定义文件所在的位置,多个用逗号隔开如"classpath:/templates/tiles-defs-member.xml,classpath:/templates/tiles-defs-order.xml"
51         tilesDefLocations: "classpath:/templates/tiles-defs.xml*"
52         excludedViewNames: [merchant/*]
53         cache: false
54         mode: LEGACYHTML5
55 mybatis:
56   mapperLocations: classpath:sqlmaps/**/*.xml
57   typeAliasesPackage: com.chenpt.model
58 server:
59   #会话超时时间,原则上要略大于redis session生效时间
60   port: 8080
61   sessionTimeout: 300000
62   contextPath: /
63   # Tomcat特性相关
64   tomcat:
65     accessLogEnabled: false
66     protocolHeader: x-forwarded-proto
67     remoteIpHeader: x-forwarded-for
68     connectionTimeout: 180000
69     basedir:
70     # secs
71     backgroundProcessorDelay: 30
72 #图片服务地址
73 imageUrl:
74   testurl: "http://127.0.0.1:8080/demo/"
75   url: "root"
View Code

启动配置java文件

  1 package com.chenpt.config;
  2 
  3 import org.springframework.beans.BeansException;
  4 import org.springframework.beans.factory.annotation.Autowired;
  5 import org.springframework.beans.factory.annotation.Value;
  6 import org.springframework.boot.autoconfigure.AutoConfigureAfter;
  7 import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
  8 import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties;
  9 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 10 import org.springframework.context.ApplicationContext;
 11 import org.springframework.context.ApplicationContextAware;
 12 import org.springframework.context.annotation.Bean;
 13 import org.springframework.context.annotation.Configuration;
 14 import org.springframework.core.Ordered;
 15 import org.springframework.web.servlet.ViewResolver;
 16 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 17 import org.thymeleaf.dialect.IDialect;
 18 import org.thymeleaf.extras.tiles2.dialect.TilesDialect;
 19 import org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer;
 20 import org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView;
 21 import org.thymeleaf.spring4.SpringTemplateEngine;
 22 import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
 23 import org.thymeleaf.spring4.view.ThymeleafViewResolver;
 24 
 25 import java.util.HashMap;
 26 import java.util.HashSet;
 27 import java.util.Map;
 28 import java.util.Set;
 29 
 30 
 31 @Configuration
 32 @EnableWebMvc
 33 @AutoConfigureAfter(ThymeleafAutoConfiguration.class)
 34 @EnableConfigurationProperties(ThymeleafProperties.class)
 35 public class ThymeleafTilesConfiguration implements ApplicationContextAware {
 36 
 37     private ApplicationContext applicationContext = null;
 38 
 39     @Autowired
 40     private ThymeleafProperties props;
 41 
 42     @Value("#{'${spring.thymeleaf.tilesDefLocations}'.split(',')}")
 43     private String[] tilesDefLocations;
 44 
 45     @Value("${imageUrl.url}")
 46     private String imageUrl;
 47 
 48     public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
 49         this.applicationContext = applicationContext;
 50     }
 51 
 52     @Bean
 53     public ViewResolver tilesViewResolver() {
 54         ThymeleafViewResolver vr = new ThymeleafViewResolver();
 55         vr.setTemplateEngine(templateEngine());
 56         vr.setViewClass(ThymeleafTilesView.class);
 57         vr.setCharacterEncoding(props.getEncoding().name());
 58         vr.setOrder(Ordered.LOWEST_PRECEDENCE);
 59         vr.setCache(false);
 60 
 61         Map<String, String> variables = new HashMap<>();
 62         variables.put("imageUrl", imageUrl);
 63 
 64         vr.setStaticVariables(variables);
 65 
 66         return vr;
 67     }
 68 
 69     @Bean
 70     public ViewResolver thymeleafViewResolver() {
 71         ThymeleafViewResolver vr = new ThymeleafViewResolver();
 72         vr.setTemplateEngine(templateEngine());
 73         vr.setCharacterEncoding(props.getEncoding().name());
 74         vr.setOrder(Ordered.HIGHEST_PRECEDENCE);
 75         vr.setExcludedViewNames(props.getExcludedViewNames());
 76         return vr;
 77     }
 78 
 79 
 80     @Bean
 81     public SpringTemplateEngine templateEngine() {
 82         final SpringTemplateEngine engine = new SpringTemplateEngine();
 83         engine.setTemplateResolver(templateResolver());
 84         engine.setAdditionalDialects(dialects());
 85         return engine;
 86     }
 87 
 88     @Bean
 89     public SpringResourceTemplateResolver templateResolver() {
 90         SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
 91         resolver.setPrefix(props.getPrefix());
 92         resolver.setSuffix(props.getSuffix());
 93         resolver.setTemplateMode(props.getMode());
 94         resolver.setCharacterEncoding(props.getEncoding().name());
 95         resolver.setCacheable(props.isCache());
 96         resolver.setApplicationContext(applicationContext);
 97 
 98         return resolver;
 99     }
100 
101     @Bean
102     public ThymeleafTilesConfigurer tilesConfigurer() {
103         ThymeleafTilesConfigurer ttc = new ThymeleafTilesConfigurer();
104         ttc.setDefinitions(tilesDefLocations);
105         return ttc;
106     }
107 
108     private Set<IDialect> dialects() {
109         final Set<IDialect> set = new HashSet<IDialect>();
110         set.add(new TilesDialect());
111         return set;
112     }
113 
114 }
View Code

到此thymeleaf配置就算结束了,下面进行页面模块配置tiles

首先创建HTML模板结构如图

接下来最重要的tiles-defs.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
        "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
        "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">

<tiles-definitions>


    <definition name="merchant/*" template="views/merchant/common/layout">
        <put-attribute name="head" value="views/merchant/common/head"/>
        <put-attribute name="leftmenu" value="views/merchant/common/leftmenu"/>
        <put-attribute name="content" value="views/{0}"/>
        <put-attribute name="footer" value="views/merchant/common/footer"/>
    </definition>

</tiles-definitions>

 代码配置大致这些,楼主项目没贴出来,只是展现了部分,(具体细节楼主也是略知一二,因此此博客只是些代码记录,待以后深入研究)

使用springboot的thymeleaf模板时默认会对HTML进行严格的检查,导致当你的标签没有闭合时就会通不过(解决方法:添加nekohtml依赖)

配置简介

spring.thymeleaf.cache=false
spring.thymeleaf.mode = LEGACYHTML5

第一行配置是清除缓存,实现热部署。也就是修改了html后不用重启,刷新页面就能看到效果。修改完html后一定要ctrl+f9重新build一下。再回到浏览器刷新,就能看到效果了。

第二行配置是回避HTML进行严格的检查的配置,当然你需要提前引入nekohtml依赖

 

posted @ 2018-05-23 14:55  不二尘  阅读(2276)  评论(0编辑  收藏  举报