springboot整合thymeleaf最终版

本次案例因为freemaker和thymeleaf同时引入导致thymeleaf标签无法生效,一个小时浪费了。freemaker和thymeleaf一定不能同时开启


第一步:在pom中导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.qf</groupId>
	<artifactId>springbootthymeleaf</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springbootthymeleaf</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.3</version>
		</dependency>
		<!-- mybatis依赖 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.0</version>
		</dependency>

		<!-- druid连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>

		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.48</version>
		</dependency>


		<!-- freemaker启动器。注意freemarker和thymeleaf两种模板不能同时使用-->
	<!--	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>-->


		<!--aop的启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>


		<!-- shiro ,shiro和quartz不使用时不能放开,不然会报错-->
		<!--<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring-boot-web-starter</artifactId>
			<version>1.4.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-quartz</artifactId>
		</dependency>-->

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j</artifactId>
			<version>1.3.8.RELEASE</version>
		</dependency>
		<!-- thymeleaf模板依赖. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


步骤二:配置application.yaml文件,声明controller层跳转页面的前后缀


#服务器端口号
server:
  port: 8080

#数据库信息
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/shiroweb
    driver-class-name: com.mysql.jdbc.Driver
    #前后缀
  freemarker:
    prefix: /
    suffix: .ftl
    cache: false    #缓存
    content-type: text/html
  resources:
   #修改静态资源加载默认位置
    static-locations: classpath:/static
  servlet:
    multipart:
    #设置上传文件的大小
      max-request-size: 1000MB
      max-file-size: 500MB
#mybatis\u57FA\u672C
mybatis:
  #设置加载mapper文件路径
  mapper-locations: mapper/*.xml
#  type-aliases-package: com.itqf.springbootssmfreemaker03.entity
#  configuration:
#    map-underscore-to-camel-case: true
#    auto-mapping-behavior: full
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

#shiro拦截器
shiro:
  loginUrl: /login    #登录地址
  unauthorizedUrl: /403      #未授权跳往403.ftl这个模板文件
  enabled: true  #web项目的支持
#\u914D\u7F6Efreemaker





上面将thymeleaf要用的配置都配完了,下面就是正常的使用


步骤三:创建给thymeleaf页面传数据的controller层

该案例将该类命名为:ThymeleafController

package com.qf.springbootthymeleaf.controller;

import com.qf.springbootthymeleaf.entity.ShowData;
import com.sun.javafx.font.freetype.HBGlyphLayout;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.ArrayList;
import java.util.List;



@Controller
public class ThymeleafController {

    @RequestMapping("/jump")
    public String jumpThy(Model model){

        //测试集合
        List<String> hobbys = new ArrayList<>();
        hobbys.add("学习");
        hobbys.add("吃火锅");
        hobbys.add("板面");
        hobbys.add("腰子");

        //测试对象
        Date birthday = new Date();
        ShowData showData = new ShowData("二狗子",11,birthday,hobbys);

        List<ShowData> datas = new ArrayList<>();
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);
        datas.add(showData);


        model.addAttribute("datas", datas);

        model.addAttribute("data", showData);
        model.addAttribute("str", "哈哈哈");

        model.addAttribute("str1", "呵呵呵");

        model.addAttribute("index", 10);

        model.addAttribute("html", "<a href='#'>哈哈哈</a>");


        return "index";//将index改成show即可去查看show.html页面的效果
    }

}


步骤四: 创建用到的实体类

package com.qf.springbootthymeleaf.entity;



import java.util.Date;
import java.util.List;

/**
 * 作者:赵伟风
 * 项目名: springboot-cors-mail-04
 * 时间:2019/11/22  15:50
 * 描述:
 */


public class ShowData {
    public ShowData() {
    }

    public ShowData(String name, int age, Date birthday, List<String> hobbys) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.hobbys = hobbys;
    }

    private String name;
    private int age;
    private Date birthday;
    private List<String> hobbys;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    @Override
    public String toString() {
        return "ShowData{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", hobbys=" + hobbys +
                '}';
    }
}

步骤五:配置启动类

package com.qf.springbootthymeleaf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication//因为没有dao层,因此这里没有mapperScan注解
public class SpringbootthymeleafApplication {

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

}


步骤六:在页面中国使用thymeleaf。页面中使用thymeleaf语法一定要先在页面中引入xmlns:th="http://www.thymeleaf.org"命名空间


thymeleaf用到的页面

第一个页面: index.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org"><!--thymeleaf必须要引用xmlns:th="http://www.thymeleaf.org这个命名空间才能在页面中使用thymeleaf语法-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!-- <link rel="stylesheet" type="text/css" href="/index.css">-->
    <link rel="stylesheet" th:href="@{/red.css}" type="text/css"><!--<!--引入css样式。一般用不着。一般都用上面普通的那种引入方式即可-->-->
    
    <style>
         .xx{
             color: #ff0;
         }
    </style>
</head>
<body>


<!--thymeleaf标签都是th:text="el表达式"开头的-->

<!--测试单个值-->
      <p th:text="${str}"></p>
      <hr>


<!--thymeleaf后台传来的key进行拼接-->
      <p th:text="${'哈哈哈呵呵呵'+str}"></p>

<!--后台传来的两个key进行拼接-->
      <p th:text="${str+str1}"></p>

<!--数字之间做加法,这里等于2-->
      <p th:text="${1+1}"></p>

<!--thymeleaf中的三目运算符的使用-->
      <p th:text="${index>10?'index大于10':'index小于10'}"></p>


      <hr>
<!--获取后台传过来的对象属性的写法-->
      <p th:text="${data.name}"></p>
      <p th:text="${data.age>=18?'成年人':'未成年人'}"></p>
      <p th:text="${data.birthday}"></p>
<!--获取后台传过来的对象属性为数组的写法-->
      <p th:text="${data.hobbys}"></p>
<!--获取后台传过来的对象属性为数组下标为1的值的写法-->
      <p th:text="${data.hobbys[1]}"></p>

      <hr>

      <br>
          <!--四大共享域对象!
          servletcontxt session request response (pagcontext)-->



           <!--利用共享域获取static文件的绝对路径-->
         <p th:text="${#servletContext.getRealPath('/static')}"></p>

         输出几个爱好!
         <p th:text="${data.hobbys.size()}"></p><!--获取后台传过来的数组的长度-->
         <p th:text="${#lists.size(data.hobbys)}"></p><!--同样也是获取data对象中的数组的长度-->
         <p th:text="${data.getName()}"></p><!--获取data的爱好属性-->
         <p th:text="${#dates.format(data.birthday,'yyyy年MM月dd日')}"></p><!--格式化传过来的日期-->

      <hr>
        <p th:value="${str}"></p>

      <input type="text" th:value="${str}">

<!--下拉框的写法-->
       <select name="vm">
            <option th:value="${str}" th:text="${str1}"></option><!--th:value代表value属性。th:text代表文本内容-->
       </select>

      <hr>
        text/utext
       <div th:text="${html}"><!--th:text无法解析html标签内容,只会直接显示出来-->

       </div>

      <div th:utext="${html}"><!--th:utext可以解析html标签内容-->

      </div>

      <hr>

      a标签超链接

      <a  href="/jump?name=ergouzi" >普通的</a>

      <a th:href="@{/jump(name=${data.name},age=${data.age})}" >可以获取共享域中的数据</a><!--jump代表请求地址,要穿过去的参数用()括号括起来,属性名等于${动态值}}-->

      <hr>
        优化获取方式  th:object  *{}
      <div th:object="${data}">
            <p th:text="*{name}"></p><!--相当于data.name。就是获取data对象的name属性-->
            <p th:text="*{age}"></p>
            <div>
                <p th:text="*{name}"></p>
            </div>
      </div>

<!--      <p th:text="*{name}"></p>-->

      <hr>
     th:filed
     <div th:object="${data}">

         <input id="name" name="name" value="二狗子" />
         <input  th:field="*{age}" />
     </div>
        

<!--class赋值。值是最上面的class,名叫xx那个-->
    <p th:class="${'xx'}" th:text="${'我的老家哈哈哈哈'}"></p>


<!--if条件判断-->
     <p th:if="${data.age>20}">年龄大于20</p><!--th:if="el表达式"用于判断-->
      <p th:unless="${data.age>20}">年龄小于20</p><!--取反-->


     <div th:switch="${data.age}"><!--就和java的switch...case语法一样。data.age的值满足下面某个case就显示那个标签-->
          <p th:case="11">年龄为11</p>
         <p th:case="12">年龄为12</p>
         <p th:case="*">年龄未知</p>
     </div>





</body>
</html>

第二个页面: show.htmml

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <center>

         <!--下拉框遍历。hobby代表每次遍历出来的对象,vs代表状态对象,data.hobbys代表被遍历的数组-->
         <select name="ergouzi">
                <option th:each="hobby,vs:${data.hobbys}" th:value="${hobby}" th:text="${hobby}"></option>
         </select>



         <table border="1px solid red"  cellpadding="0px" cellspacing="0px">
                <tr>
                    <th>编码</th>
                    <th>名字</th>
                    <th>年龄</th>
                    <th>生日</th>
                    <th>爱好</th>
                </tr>
<!--                th:each = 每次遍历的数据,状态对象 : 集合数据  -->
                <tr th:each="data,datavs:${datas}"><!--data每次遍历出来的数据,datavs遍历的第几次,datas代表被遍历的集合-->
                    <th th:text="${datavs.count}"></th>
                    <th th:text="${data.name}"></th>
                    <th th:text="${data.age+'岁'}"></th>
                    <th th:text="${#dates.format(data.birthday,'yyyy年MM月dd日')}"></th>
                    <th th:text="${#strings.listJoin(data.hobbys,',')}"></th>
                </tr>
         </table>


     </center>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值