5分钟学会Freemarker自定义标签(页面宏)实现

                                            freemarker自定义标签(页面宏)实现

一、前言

       freemarker自定义标签(页面宏)实现。

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

 二、freemarker自定义标签(页面宏)

                                               

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

}

4、UserController.java

/**
 * 自定义指令(宏)
 *      Controller
 * @author yys
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public String userList(HttpServletRequest request) {
        // 获取用户列表
        request.setAttribute("userList", userService.getUserList());
        return "user/list";
    }

}

5、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();
    }

}

6、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();

}

7、启动类

@SpringBootApplication
@MapperScan("com.yys.mapper")
public class YysApp {

    public static void main(String[] args) {
        SpringApplication.run(YysApp.class, args);
    }

}

8、list.ftl


<#-- 宏模板引入 -->
<#include "../macro_global_library.ftl" />


<@header title="一生猿,一世猿。" ; param>
    <link rel="stylesheet" type='text/css' href="/static/css/common.css"/>
    <div class="table">--------- ${param} ---------</div>
</@header>


<@htmlBody>
    <div class="table-div">
        <table class="table">
            <thead>简介:</thead>
            <tbody>
                <tr>
                    <td>花名</td>
                    <td>年龄</td>
                    <td>创建时间</td>
                </tr>
                <#list userList as user>
                    <tr>
                        <td>${user.name}</td>
                        <td>${user.age}</td>
                        <td>${user.createTime?datetime}</td>
                    </tr>
                </#list>
            </tbody>
        </table>
    </div>
</@htmlBody>


<@footer ; param>
    <div class="div">--------- ${param} ---------</div>
</@footer>

9、macro_global_library.ftl ***(公共宏模板)***


<#-- 公共顶部 -->
<#macro header title keywords="default value" description="default value">
<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;" />
        <meta name="format-detection" content="telephone=no" />
        <title>${title}</title>
        <meta name="keywords" content="${keywords}" />
        <meta name="description" content="${description}" />

        <#nested "页面顶部">
    </head>
    <body>
</#macro>

<#-- 公共body -->
<#macro htmlBody>
<body>
  <#nested>
</body>
</#macro>

<#-- 公共底部 -->
<#macro footer>
    <#nested "页面底部"><#-- 嵌套内容(自定义marco的模板片段),而且支持传递参数 -->
</html>
</#macro>

10、common.css

.table-div table{ border:1px solid black; }
.table-div table td{ border:1px solid black; }
.div{ margin-top: 20px; }

11、初始化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());

12、测试

http://localhost:8080/user/list

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

                    

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

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

猜你喜欢

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