zoukankan      html  css  js  c++  java
  • JavaEE开发之SpringBoot整合MyBatis以及Thymeleaf模板引擎

    使用thymeleaf布局

    使用thymeleaf布局非常的方便

    <footer th:fragment="copy"> 
    &copy; 2016
    </footer>

    在页面任何地方引入:

    <body> 
      <div th:include="footer :: copy"></div>
      <div th:replace="footer :: copy"></div>
    </body>

    th:include 和 th:replace区别,include只是加载,replace是替换

    返回的HTML如下:

    <body> 
       <div> &copy; 2016 </div> 
      <footer>&copy; 2016 </footer> 
    </body>

    下面是一个常用的后台页面布局,将整个页面分为头部,尾部、菜单栏、隐藏栏,点击菜单只改变content区域的页面

    <body class="layout-fixed">
      <div th:fragment="navbar"  class="wrapper"  role="navigation">
        <div th:replace="fragments/header :: header">Header</div>
        <div th:replace="fragments/left :: left">left</div>
        <div th:replace="fragments/sidebar :: sidebar">sidebar</div>
        <div layout:fragment="content" id="content" ></div>
        <div th:replace="fragments/footer :: footer">footer</div>
      </div>
    </body>

    任何页面想使用这样的布局值只需要替换中见的 content模块即可

     <html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout">
       <body>
          <section layout:fragment="content">
        ...

    也可以在引用模版的时候传参

    <head th:include="layout :: htmlhead" th:with="title='Hello'"></head>

    layout 是文件地址,如果有文件夹可以这样写 fileName/layout:htmlhead
    htmlhead 是指定义的代码片段 如 th:fragment="copy"

    https://github.com/cloudfavorites/favorites-web

    http://blog.csdn.net/quuqu/article/details/52511933

    Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用。

    Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑。这意味着Thymeleaf还可以作为模板引擎框架。

    Thymeleaf的模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。例如下面的html文件,当作为静态文件时,product name显示为Red Chair,当运行在容器中并提供product这个对象时,product name的值会自动替换为product.description对应的值。

    1.bean值替换
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 2</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 1: bean values</h1>
            <h2>Product information</h2>
            <dl>
                <dt>Product name</dt>
                <dd th:text="${product.description}">Red Chair</dd>
    
                <dt>Product price</dt>
                <dd th:text="${product.price}">350</dd>
    
                <dt>Product available from</dt>
                <dd th:text="${product.availableFrom}">2014-12-01</dd>
            </dl>
        </body>
    </html>
    2.简单数据转换(数字,日期)
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 2</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 2: bean values</h1>
            <h2>Product information</h2>
            <dl>
                <dt>Product name</dt>
                <dd th:text="${product.description}">red Chair</dd>
    
                <dt>Product price</dt>
                <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>
    
                <dt>Product available from</dt>
                <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>
            </dl>
        </body>
    </html>
    3.字符串拼接
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 3</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 3: string concatenation</h1>
            <h2>Product information</h2>
            <dl>
                <dt>Product price</dt>
                <dd th:text="${'$'+product.price}">235</dd>
            </dl>
        </body>
    </html>
    4.国际化
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title th:text="#{tutorial.exercise4}">Thymeleaf tutorial: exercise 4</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1 th:text="#{tutorial.exercise4}">Thymeleaf tutorial - Solution for exercise 4: internationalization</h1>
            <h2 th:text="#{product.info}">Product information</h2>
            <dl>
                <dt th:text="#{product.name}">Product name</dt>
                <dd th:text="${product.description}">Red chair</dd>
    
                <dt th:text="#{product.price}">Product price</dt>
                <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">350</dd>
    
                <dt th:text="#{product.available}">Product available from</dt>
                <dd th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</dd>
            </dl>
        </body>
    </html>
    此时html需要相应的配置文件。例如如下配置文件:

    en:

    tutorial.exercise4=Thymeleaf tutorial - exercise 4: internationalization
    product.info=Product information
    product.name=Product name
    product.price=Product price
    product.available=Product available from
    back=Back

    fr

    tutorial.exercise4=Tutorial De Thymeleaf - exercice 4: l'internationalisation
    product.info=Information du produit
    product.name=Nom du produit
    product.price=Prix du produit
    product.available=Produit disponible depuis
    back=Revenir

    5.转义和非转义文本
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 5</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Solution for exercise 5: escaped and unescaped text</h1>
            <div th:text="${html}">
                Some escaped text
            </div>
            <div th:utext="${html}">
                Some unescaped text
            </div>
        </body>
    </html>
    上述两个div分别生成的html代码为
    <div>This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;</div>
    <div>This is an <em>HTML</em> text. <b>Enjoy yourself!</b></div>
    6.迭代
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 6</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 6: iteration</h1>
            <h2>Product list</h2>
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Price</th>
                        <th>Available from</th>
                    </tr>
                </thead>
                <tbody th:remove="all-but-first">
                    <tr th:each="product:${productList}">
                        <td th:text="${product.description}">Red Chair</td>
                        <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$123</td>
                        <td th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</td>
                    </tr>
                    <tr>
                        <td>White table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                    <tr>
                        <td>Reb table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                    <tr>
                        <td>Blue table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                </tbody>
            </table>
        </body>
    </html>
    7.迭代统计
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 7</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Solution for exercise 7: iteration stats</h1>
            <h2>Product list</h2>
            <table>
                <thead>
                    <tr>
                        <th>Index</th>
                        <th>Description</th>
                        <th>Price</th>
                        <th>Available from</th>
                    </tr>
                </thead>
                <tbody th:remove="all-but-first">
                    <tr th:each="product : ${productList}">
                        <td th:text="${productStat.count}">1</td>
                        <td th:text="${product.description}">Red chair</td>
                        <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$350</td>
                        <td th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</td>
                    </tr>
                    <tr>
                        <td>2</td>
                        <td>White table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                    <tr>
                        <td>3</td>
                        <td>Reb table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                    <tr>
                        <td>4</td>
                        <td>Blue table</td>
                        <td>$200</td>
                        <td>15-Jul-2013</td>
                    </tr>
                </tbody>
            </table>
        </body>
    </html>
    8.条件判断
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 8</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 8: conditions</h1>
            <h2>Product list</h2>
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Price</th>
                        <th>Available from</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="product : ${productList}">
                        <td th:text="${product.description}">Red chair</td>
                        <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$350</td>
                        <td th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</td>
                        <td>
                            <span th:if="${product.price lt 100}" class="offer">Special offer!</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </body>
    </html>
    9.更多条件判断
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 9</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 9: more on conditions</h1>
            <h2>Customer list</h2>
            <table>
                <thead>
                    <tr>
                        <th>First name</th>
                        <th>Last name</th>
                        <th>Gender</th>
                        <th>Payment method</th>
                        <th>Balance</th>
                    </tr>
                </thead>
                <tbody th:remove="all-but-first">
                    <tr th:each="customer : ${customerList}">
                        <td th:text="${customer.firstName}">Peter</td>
                        <td th:text="${customer.lastName}">Jackson</td>
                        <!-- 
                           Use th:switch for selecting content based on ${customer.gender}.
                           As genre can be null if unknown, better use ${customer.gender?.name()}
                           for obtaining its name.
                        -->
                        <td th:switch="${customer.gender?.name()}">
                            <img th:case="'MALE'" src="../../../images/male.png" th:src="@{/images/male.png}" alt="Male" /> <!-- Use "/images/male.png" image -->
                            <img th:case="'FEMALE'" src="../../../images/female.png" th:src="@{/images/female.png}" alt="Female" /> <!-- Use "/images/female.png" image -->
                            <span th:case="*">Unknown</span>
                        </td>
                        <td>
                            <span th:text="${customer.paymentMethod.description}">Direct debit</span>
                            <!-- Show next message only when paymentMethod is not CREDIT_CARD -->
                            <span th:unless="${customer.paymentMethod.name() == 'CREDIT_CARD'}" class="warn">
                                Payment must be done in the next 4 days
                            </span>
                        </td>
                        <!-- Add class="enhanced" when balance is greater than 10000 -->
                        <td th:class="${customer.balance gt 10000} ? 'enhanced'" th:text="${customer.balance}">350</td>
                    </tr>
                    <tr>
                        <td>Mary</td>
                        <td>Johanson</td>
                        <td><img src="../../../images/female.png" /></td>
                        <td><span>Credit card</span></td>
                        <td>5000</td>
                    </tr>
                    <tr>
                        <td>Robert</td>
                        <td>Allen</td>
                        <td><img src="../../../images/male.png" /></td>
                        <td>
                            <span>Credit card</span>
                            <span class="warn">Payment must be done in the next 4 days</span>
                        </td>
                        <td class="enhanced">50000</td>
                    </tr>
                </tbody>
            </table>
        </body>
    </html>
    10.Spring表达式语言
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 10</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Solution for exercise 10: Spring Expression language</h1>
      
            <h2>Arithmetic expressions</h2>
            <p class="label">Four multiplied by minus six multiplied by minus two module seven:</p>
            <p class="answer" th:text="${4 * -6 * -2 % 7}">123</p>
     
            <h2>Object navigation</h2>
            <p class="label">Description field of paymentMethod field of the third element of customerList bean:</p>
            <p class="answer" th:text="${customerList[2].paymentMethod.description}">Credit card</p>
     
            <h2>Object instantiation</h2>
            <p class="label">Current time milliseconds:</p>
            <p class="answer" th:text="${new java.util.Date().getTime()}">22-Jun-2013</p>
            
            <h2>T operator</h2>
            <p class="label">Random number:</p>
            <p class="answer" th:text="${T(java.lang.Math).random()}">123456</p>
        </body>
    </html>
    11.超链接
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 11</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Answer for exercise 11: links</h1>
            <h2>Product actions</h2>
            <ul>
                <li><a href="#" th:href="@{/exercise11/product.html(action='view')}">View product</a></li>
                <li><a href="#" th:href="@{/exercise11/product.html(action='edit')}">Edit product</a></li>
            </ul>
        </body>
    </html>
    12.表单
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 12</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Solution for exercise 12: forms</h1>
            <h2>Customer edition</h2>
            <form action="saveCustomer.html" th:action="@{/exercise12/saveCustomer.html}" th:object="${customer}" method="post">
                <input type="hidden" th:field="*{id}" />
                
                <label for="firstName">First name:</label>
                <input type="text" th:field="*{firstName}" value="John" />
                
                <label for="lastName">Last name:</label>
                <input type="text" th:field="*{lastName}" value="Wayne" />
                
                Genre:
                <div th:each="gender : ${genders}" class="radio">
                    <input type="radio" th:value="${gender}" th:field="*{gender}" />
                    <label th:for="${#ids.prev('gender')}" th:text="${gender.description}">Male</label>
                </div>
                <div th:remove="all" class="radio">
                    <input type="radio" />
                    <label>Female</label>
                </div>
                
                <label for="paymentMethod">Payment method:</label>
                <select th:field="*{paymentMethod}" th:remove="all-but-first">
                    <option th:each="paymentMethod : ${paymentMethods}"
                            th:value="${paymentMethod}" th:text="${paymentMethod.description}">Credit card</option>
                    <option>Another payment method</option>
                    <option>Another payment method</option>
                </select>
                
                <label for="balance">Balance (dollars):</label>
                <input type="text" th:field="*{balance}" size="10" value="2500" />
                
                <input type="submit" />
            </form>
        </body>
    </html>
    13.内联
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Thymeleaf tutorial: exercise 13</title>
            <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
            <meta charset="utf-8" />
        </head>
        <body>
            <h1>Thymeleaf tutorial - Solution for exercise 13: inlining</h1>
            <h2>Birthday email</h2>
            <form action="#" method="post">
                <label for="body">Message body:</label>
    <textarea id="body" name="body" th:inline="text">
    Dear [[${customerName}]],
    
    it is our sincere pleasure to congratulate your in your birthday:
        Happy birthday [[${customerName}]]!!!
    
    See you soon, [[${customerName}]].
    
    Regards,
        The Thymeleaf team
    </textarea>
                <input type="submit" value="Send mail" />
            </form>
        </body>
    </html>
    --------------------------------------------------------------------------------------------------------------

    以上资料都来自http://itutorial.thymeleaf.org/。如果对Thymeleaf有兴趣,可以试试他们做的交互教程,很是好用。上面的html代码都是来自thymeleaf的交互教程

     http://www.cnblogs.com/dreamfree/p/4158557.html

    上篇博客我们聊了《JavaEE开发之SpringBoot工程的创建、运行与配置》,从上篇博客的内容我们不难看出SpringBoot的便捷。本篇博客我们继续在上篇博客的基础上来看一下SpringBoot是如何引入和使用MyBatis和Thymeleaf的。在之前的博客中我们提到过Hibernate,今天博客所引入的Mybatis所扮演的角色与Hibernate类似,都是一套ORM框架,主要负责持久化的,也是将数据库中的数据直接映射为Model的框架。

    而Thymeleaf就是一个模板引擎了,与之前我们聊得PHP中的Smarty模板引擎类似。如果你们的Web工程是前后端分离的,那么就用不着Thymeleaf等模板引擎了。本篇博客要做的事情就是在SpringBoot工程中引入MyBatis,然后通过MyBatis所提供的映射方法以及注解来读取数据库中的信息。然后使用Thymeleaf模板在前端进行数据的展示。

    我们之前在聊Swift开发服务端的内容,也就是Perfect框架时,用到了MySQL相关的东西。本篇博客我们就使用Perfect框架之前所操作的数据库就行了。关于Swift的Perfect框架的相关内容,请移步于《Swift中的服务端框架---Perfect》系列博客。因为之前聊过MySQL相关的东西了,本篇博客就不做过多赘述了。关于MySQL的安装,请参见之前发布的博客《macOS Sierra安装Apache2.4+PHP7.0+MySQL5.7.16》。本篇博客,我们就把重点放到Spring Boot中的MyBatis和Thymeleaf上。

    一、MyBatis的引入与使用

    1.配置pom文件

    首先我们来看一下如何在Spring Boot中引入MyBatis。首先我们在http://mvnrepository.com/中找到Mybatis Spring Boot Starter相关的Mvn仓库连接。如下所示,从下方截图中,我们不难看出,目前MyBatis Spring Boot Starter的最新版本是1.2.0。不过本篇博客中我们使用的是1.1.1版本,因为我引入1.2.0后,我的SpringBoot工程根本启动不了,于是换成1.1.1版本就OK了。

      

    在pom.xml添加上下方的配置项,引入mybatis-spring-boot-starter和mysql-connector-java相关配置。mysql-connector-java顾明思议,就是连接MySQL数据库使用的依赖包。pom.xml中的配置如下。

    复制代码
            <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
            
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.38</version>
            </dependency>
    复制代码

    2、配置MySQL数据库连接

    因为我们使用的是Spring Boot引入的MyBatis, Mybatis Spring Boot Starter会为我们做好多自动化的配置,比如SqlSessionFactory的创建等等。需要我们做的就是在application.properties文件中进行数据库连接的相关配置即可。下方就是我们在配置文件中添加的连接数据库的相关信息。主要配置了数据库连接的路径,数据库的用户名以及密码,数据库的驱动。

    #Config MySQL Connect Info
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/perfect_note
    spring.datasource.username=root
    spring.datasource.password=admin!@#
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver

    3、创建Model类

    接下来我们就来创建数据库中的相应数据所要映射的数据Model类。接下来我们就来操作perfect_note数据库中的content表,如下所示。下方数据库及数据库中的数据是我们之前在聊Perfect框架时所使用的数据,本篇博客我们依然对该数据进行操作。

      

    根据上述cotent表中的字段,我们来创建该表所对应的model类。下方这个Content类就是我们所创建的content表所对应的Model。具体如下所示。

      

    4.创建映射接口

    接下来我们来创建数据库表与Model直接的映射接口。在该接口中提供了数据与Model直接的映射关系,并且提供了相关的SQL操作。下方的ContentMapper接口就是我们创建的content表与ContentModel之间的映射关系。并且在该接口中的方法所对应的注解中,提供了相应的SQL操作。

    在ContentMapper接口的query()方法中,该方法所对应的SQL语句是“select * from content”,也就是查询所有content中的数据。@Results注解提供了数据库表的字段与Model的属性的映射关系。下方指定了表字段"id"与"contentId"对应,字段名"create_time"与“createTime”属性相对应,而未指定的就是字段名与属性名一致。

    queryById()就是带有条件的查询方法了。其参数就是查询的条件。通过@Param注解进行条件与参数的绑定。具体代码如下所示。

      

    5、创建测试用的Controller

    为了简便期间,我们就不创建DAO层了,就直接在Controller中来调用上述接口中的方法即可。下方这个MyBatisTestController就是我们创建的用来测试上述操作的测试控制器。当然我们将该控制器声明为@RestController以便我们对其进行测试。然后使用@Autowired注解注入ContentMapper类型的对象,我们可以通过该对象来操作上述接口中所对应的方法。queryContentById()方法,对应的是contentMapper中的queryById()方法,queryAll()方法对应的是Mapper中的query()方法,具体代码如下所示。

    下方我们直接将获取到的Model或者Model数组进行返回,在Spring Boot中,直接返回的Model会被映射成相应的JSON格式的数据的,这个稍后我们会直观的看到。

      

    6、访问上述路由

    我们先访问/queryContentById这个路由,再访问这个路由时,我们要提供一个参数contentId。也就是用来查询数据的条件。下方截图中的结果就是我们对contentId=6的条件查询的结果。

      

    接下来我们来查询一下所有的数据,也就是访问queryAll路由。具体结果如下所示。

      

    二、Thymeleaf模板的引入与使用

    上面引入MyBatis算是妥了,以后的博客中还会继续对MyBatis的相关东西进行介绍。接下来我们就引入Thymeleaf模板,然后显示我们使用MyBatis读取到的相关数据。下方我们就来看一下在Spring Boot中是如何整合Thymeleaf模板的

    1、配置pom.xml文件

    在pom.xml中添加Thymeleaf在Spring Boot中相关的库,具体如下所示:

    复制代码
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
                <version>1.5.2.RELEASE</version>
            </dependency>
    复制代码

    2、创建模板使用的Controller

    紧接着,我们就来创建模板所对应的Controller,如下所示。下方我们依然使用注入的ContentMapper对象来获取数据。然后将获取的数据添加到model对象中,在添加时,我们会为该数据对象指定一个参数名称,如下方的"contents"。然后返回模板页面即可,下方的“display”就是我们模板页面所在的文件名称。

      

     

    3、创建模板页面

    然后我们就该创建模板页面了,也就是此处的display.html。下方就是display.html页面的所有内容。其中我们为数据的显示添加了一些css样式,并使用CDN引入了目前最新版本的Bootstrap。下方带有“th:”前缀的属性就是Thymeleaf模板的标签。

    首先使用“th:if="${not #lists.isEmpty(contents)}"”来判断contents属性所对应的值是否为空,如果不为空,则执行标签中的内容。然后使用th:if="${not #lists.isEmpty(contents)}"来遍历contents中的内容,类似于while循环。通过th:each="content:${contents}"取出每一项的数据。通过th:text="${content.contentId}"取出某个属性的值。具体内容如下所示。

    复制代码
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta content="text/html;charset=UTF-8"/>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <title>Content</title>
    </head>
    <body>
        <div class="center-block" style="800px" th:if="${not #lists.isEmpty(contents)}">
            <div class="row"  style="height:50px;  color: #ffffff">
              <div class="col-md-1">CotentId</div>
              <div class="col-md-2">Title</div>
              <div class="col-md-5">Cotent</div>
              <div class="col-md-1">UserId</div>
              <div class="col-md-2">CreateTime</div>
            </div>
            <div th:if="${not #lists.isEmpty(contents)}">
                <div class="row" th:each="content:${contents}" style="height:40px; margin-top: 1px; color: #ffffff">
                  <div class="col-md-1"><span th:text="${content.contentId}"></span></div>
                  <div class="col-md-2"><span th:text="${content.title}"></span></div>
                  <div class="col-md-5"><span th:text="${content.content}"></span></div>
                  <div class="col-md-1"><span th:text="${content.userID}"></span></div>
                  <div class="col-md-2"><span th:text="${content.createTime}"></span></div>
                </div>
            </div>
        </div>
        
    </body>
    </html>
    复制代码

    4、访问上述路由

    创建完展示用的模板后,接下来我们要做的事情就是要对其进行访问了。下方截图就是我们最终的访问结果。

      

    本篇博客就先到这儿吧,以后还会使用到MyBatis的其他内容,到时候再细说。

    本篇博客所涉及代码的github地址:https://github.com/lizelu/SpringBootProject

    http://www.cnblogs.com/ludashi/p/6669133.html

  • 相关阅读:
    Javaweb中的监听器
    Maven
    Ajax
    jQuery
    Spring入门
    spring boot实战——微信点餐系统02:接口信息,分页工具,gson, 注解信息,表单验证,字段返回(时间处理,null处理)
    Nginx
    Spring Data JPA
    spring boot实战——微信点餐系统01:开始代码
    spring boot实战——微信点餐系统00:项目设计,环境搭建
  • 原文地址:https://www.cnblogs.com/softidea/p/6855077.html
Copyright © 2011-2022 走看看