概述
freemarker自定义标签(java后台宏)实现 - 进阶篇
一、前言
freemarker自定义标签( java后台宏 )实现。
该篇文章对 BaseDirective / UserDirective进行封装 - (用于实际开发)。
在此记录下,分享给大家。
二、freemarker自定义标签(java后台宏)
1、pom文件 依赖引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<!-- SpringBoot 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- SpringBoot 整合 Freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- SpringBoot web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis 支持 SpringBoot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 注解式 插入/构建/优雅代码 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
2、 application.yml 新增配置
spring:
http:
encoding:
force: true
# 模板引擎编码为UTF-8
charset: UTF-8
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
# 模板文件结尾.ftl
suffix: .ftl
# 模板文件目录
template-loader-path: classpath:/templates
datasource:
url: jdbc:mysql://localhost:3306/yys_springboot_mybatis
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mvc: #静态文件
static-path-pattern : /static/**
3、FreemarkerConfig.java
/**
* Freemarker自定义指令(宏)
* Config
* @author yys
*/
@Configuration
public class FreeMarkerConfig {
@Autowired
private freemarker.template.Configuration configuration;
@Autowired
private UserDirective userDirective;
@PostConstruct
public void setSharedVariable() {
// userDirective即为页面上调用的标签名
configuration.setSharedVariable("userDirective", userDirective);
}
}
4、BaseDirective.java
/**
* 所有自定义标签的父类,负责调用具体的子类方法
* Directive
* @author yys
*/
public abstract class BaseDirective implements TemplateDirectiveModel {
private String clazzPath = null;
public BaseDirective(String targetClassPath) {
clazzPath = targetClassPath;
}
private String getMethod(Map params) {
return this.getParam(params, "method");
}
protected int getPageSize(Map params) {
int pageSize = 10;
String pageSizeStr = this.getParam(params, "pageSize");
if (!StringUtils.isEmpty(pageSizeStr)) {
pageSize = Integer.parseInt(pageSizeStr);
}
return pageSize;
}
private void verifyParameters(Map params) throws TemplateModelException {
String permission = this.getMethod(params);
if (permission == null || permission.length() == 0) {
throw new TemplateModelException("The 'name' tag attribute must be set.");
}
}
String getParam(Map params, String paramName) {
Object value = params.get(paramName);
return value instanceof SimpleScalar ? ((SimpleScalar) value).getAsString() : null;
}
private DefaultObjectWrapper getBuilder() {
return new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25).build();
}
private TemplateModel getModel(Object o) throws TemplateModelException {
return this.getBuilder().wrap(o);
}
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels,
TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
this.verifyParameters(map);
String funName = getMethod(map);
Method method = null;
try {
Class clazz = Class.forName(clazzPath);
method = clazz.getDeclaredMethod(funName, Map.class);
if (method != null) {
Object res = method.invoke(this, map);
environment.setVariable(funName, getModel(res));
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
templateDirectiveBody.render(environment.getOut());
}
}
5、UserDirective.java
/**
* 用户管理
* Directive
* @author yys
*/
@Component
public class UserDirective extends BaseDirective {
@Autowired
private UserService userService;
public UserDirective() {
super(UserDirective.class.getName());
}
/**
* 自定义标签的方法
* @param params
* @return
*/
public Object user(Map params) {
return userService.getUserByName(params.get("name").toString());
}
public Object userList(Map params) {
return userService.getUserList();
}
}
6、UserEntity.java
/**
* 用户管理
* Entity
* @author yys
*/
@Data
public class UserEntity implements Serializable {
private Long id;
private String name;
private Integer age;
private Byte status;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date createTime;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date updateTime;
}
7、UserController.java
/**
* 自定义指令(宏)
* Controller
* @author yys
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/list")
public String userList(HttpServletRequest request, String name) {
request.setAttribute("name", StringUtils.isEmpty(name) ? "yys" : name);
return "user/list";
}
}
8、UserService.java
/**
* 用户管理
* Service
* @author yys
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public boolean addUser(String userName, Integer age) {
return userMapper.insert(userName, age) > 0 ? true : false;
}
public UserEntity getUserByName(String userName) {
return userMapper.findByName(userName);
}
public List<UserEntity> getUserList() {
return userMapper.findAll();
}
}
9、UserMapper.java
/**
* 用户管理
* Mapper
* @author yys
*/
public interface UserMapper {
@Select("SELECT id, user_name AS name, age, status, create_time AS createTime, update_time AS updateTime FROM yys_user WHERE user_name = #{name}")
UserEntity findByName(@Param("name") String name);
@Insert("INSERT INTO yys_user VALUES (NULL, #{name}, #{age}, 1, NOW(), NOW())")
int insert(@Param("name") String name, @Param("age") Integer age);
@Select("SELECT id, user_name AS name, age, status, create_time AS createTime, update_time AS updateTime FROM yys_user")
List<UserEntity> findAll();
}
10、启动类
@SpringBootApplication
@MapperScan("com.yys.mapper")
public class YysApp {
public static void main(String[] args) {
SpringApplication.run(YysApp.class, args);
}
}
11、list.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>一生猿,一世猿。</title>
</head>
<style>
.table-div table{ border:1px solid black; }
.table-div table td{ border:1px solid black; }
</style>
<body>
<div class="table-div">
<@userDirective name='${name}'; user, userList>
<#-- 通过名称获取用户宏 -->
<table class="table" style="margin-bottom: 10px;">
<thead>通过名称获取用户:</thead>
<tbody>
<tr>
<td>花名</td>
<td>年龄</td>
<td>创建时间</td>
</tr>
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.createTime?datetime}</td>
<#-- ?date:yyyy-MM-dd ?time:HH:mm:ss ?datetime:yyyy-MM-dd HH:mm:ss -->
</tr>
</tbody>
</table>
<#-- 获取用户列表宏 -->
<table class="table">
<thead>获取用户列表:</thead>
<tbody>
<tr>
<td>花名</td>
<td>年龄</td>
<td>创建时间</td>
</tr>
<#if userList?? && userList?size gt 0>
<#list userList as user>
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.createTime?datetime}</td>
</tr>
</#list>
</#if>
</tbody>
</table>
</@userDirective>
</div>
</body>
</html>
12、初始化sql文件
CREATE TABLE `yys_user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',
`user_name` varchar(32) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '用户年龄',
`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `yys_user` (`id`, `user_name`, `age`, `status`, `create_time`, `update_time`) VALUES ('1', 'yys', '18', '1', NOW(), NOW());
INSERT INTO `yys_user` (`id`, `user_name`, `age`, `status`, `create_time`, `update_time`) VALUES ('2', '洞人', '23', '1', NOW(), NOW());
13、测试
http://localhost:8080/user/list
a、页面结果 - 如下图所示 :
Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长。
最后
以上就是淡定面包为你收集整理的5分钟学会Freemarker自定义标签(java后台宏)实现-进阶篇的全部内容,希望文章能够帮你解决5分钟学会Freemarker自定义标签(java后台宏)实现-进阶篇所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复