5分钟学会Freemarker自定义标签(java后台宏)实现

                                         freemarker自定义标签(java后台宏)实现

一、前言

       freemarker自定义标签( java后台宏 )实现。

       在此记录下,分享给大家。

 二、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

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 {

    public static BeansWrapper getBeansWrapper(){
        return new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
    }

}

5、UserDirective.java ***(后台宏定义)***

/**
 * 用户管理
 *      Directive
 * @author yys
 */
@Component
public class UserDirective extends BaseDirective {

    @Autowired
    private UserService userService;

    @Override
    public void execute(Environment env, Map map, TemplateModel[] templateModels,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        // 通过名称获取用户宏
        env.setVariable("user", getBeansWrapper().wrap(userService.getUserByName(map.get("name").toString())));
        // 获取用户列表宏
        env.setVariable("userList", getBeansWrapper().wrap(userService.getUserList()));
        body.render(env.getOut());
    }

}

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 {

    @Autowired
    private UserService userService;

    @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?name=洞人

  a、页面结果 - 如下图所示 :

                    

                       Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长

发布了74 篇原创文章 · 获赞 253 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_42175986/article/details/103478060