以一个博客项目,实战使用
本文目录:
1、Beetl介绍
Beetl是什么:Beetl( 发音同Beetle ) 目前版本是3.2,相对于其他java模板引擎,具有功能齐全,语法直观,性能超高,以及编写的模板容易维护等特点。使得开发和维护模板有很好的体验。同时,Beetl具备引擎可定制性,可以打造自己的模板引擎。
模板是一种设计模式,只要这种设计模式存在,就有Beetl的用武之地。Beetl可以用于
动态页面生成,网站,后台管理系统等
静态内容生成,比如互联网世界的大部分静态网页的生成
短信,微信,邮件内容等生成
二进制文档生成,比如PDF,Word (需要通过模板生成中间文本格式,如markdown,xml,然后通过工具转成二进制)
Vue,React等JS框架符合现在前后端分离,但不代表所有项目,所有需求都是这样。除非你只定位自己是搞前后端分离的。一个项目,既可以用上Beetl,也可以用上Vue,比如Beetl+Vue,或者使用Beetl完成项目中的其他需求。
2、集成SpringBoot2.x
项目结构
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.5.RELEASE
com.oy
boot-beetl
0.0.1-SNAPSHOT
boot-beetl
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
com.ibeetl
beetl-framework-starter
1.1.68.RELEASE
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
IndexController
@Controllerpublic classIndexController {
@GetMapping("/")publicString index(HttpServletRequest request){
request.setAttribute("title","一起学Beetl");
request.setAttribute("test","springboot 集成 beetl 一起来学呀");return "index1.btl";
}
}
模板文件 index1.btl
${title}3、Beetl模板的基础用法 [变量、循环、条件]
3.1、集成BeetlSql,用来查询数据库
创建数据库 create database beetl_test_blog;
引入依赖
org.springframework.boot
spring-boot-starter-jdbc
com.zaxxer
HikariCP
mysql
mysql-connector-java
5.1.40
application.properties中增加数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/beetl_test_blog?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true
spring.datasource.username=root
spring.datasource.password=
添加数据源配置类 DBConfig
packagecom.oy;importjavax.sql.DataSource;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.env.Environment;importcom.zaxxer.hikari.HikariDataSource;@Configurationpublic classDBConfig {
@Bean(name= "datasource")publicDataSource datasource(Environment env) {
HikariDataSource ds= newHikariDataSource();
ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));returnds;
}
}
测试数据源配置是否成功
@Controllerpublic classIndexController {
@AutowiredprivateDataSource dataSource;
@GetMapping("/")public String index(HttpServletRequest request) throwsSQLException{
System.out.println(dataSource.getConnection());
request.setAttribute("title","一起学Beetl");
request.setAttribute("test","springboot 集成 beetl 一起来学呀");
request.setAttribute("dataSource", dataSource);return "index1.btl";
}
}
index1.btl
${title}dataSource:${dataSource}
启动项目,访问 http://localhost:8080/ 。
3.2、BeetlSQL