【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

这篇具有很好参考价值的文章主要介绍了【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

🌕博客x主页:己不由心王道长🌕!
🌎文章说明:spring🌎
✅系列专栏:spring
🌴本篇内容:对SpringBoot进行一个入门学习及对Thymeleaf模板引擎进行整合(对所需知识点进行选择阅读呀~)🌴
☕️每日一语:在人生的道路上,即使一切都失去了,只要一息尚存,你就没有丝毫理由绝望。因为失去的一切,又可能在新的层次上复得。☕️
🕤作者详情:作者是一名双非大三在校生,喜欢Java,欢迎大家探讨学习,喜欢的话请给博主一个三连鼓励。🕤
🚩 交流社区:己不由心王道长(优质编程社区)

SpringBoot简介

SpringBoot是什么

①Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

为什么要学习SpringBoot

一、SpringBoot能简化配置、从 2002 年开始,Spring 一直在飞速的发展,如今已经成为了在Java EE(Java Enterprise Edition)开发中真正意义上的标准,但是随着技术的发展,Java EE使用 Spring 逐渐变得笨重起来,大量的 XML 文件存在于项目之中。

SpringBoot的优势

1、减少开发,测试时间和努力。
2、使用JavaConfig有助于避免使用XML。
3、避免大量的Maven导入和各种版本冲突。
4、提供意见发展方法。
5、通过提供默认值快速开始开发。
6、没有单独的Web服务器需要。这意味着你不再需要启动Tomcat,Glassfish或其他任何东西。

学习SpringBoot前要具备的基础

声明:这不是在劝退,而是在告诉同志们,学习是一个循序渐进的过程,不可操之过急。一步一个脚印的走,才能到达终点站。

学习这个知识点你应该具备的一些基础知识:
基础篇:javase基础,包括但不限于:面向对象,封装,继承,多态,类与接口,集合,IO等等。
基础篇:Spring、SpringMVC:知道Spring是用来管理bean,能够基于Restful实现页面请求交互功能
基础篇:熟练掌握Mybatis

创建第一个SpringBoot项目

在Spring官方下创建SpringBoot项目

一、打开Spring官方—>projects—>SpringBoot—>Spring initializr;
或者点击创建SpringBoot看到以下图片:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
按照上述图片完成后执行第7步会下载一个压缩包:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

二、找到压缩包位置解压
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
三、导入创建好的SpringBoot项目
打开IEDA:file—>open:找到刚才文件解压位置,加载进来即可
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
或者直接把解压好的文件拖进IDEA也可以:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
如图【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

使用IDEA创建SpringBoot项目

说明:我们一般是不会在Spring的官网上创建SpringBoot项目的,而是使用IDEA创建项目,因为IEDA为我们准备好了创建工具,这样的创建更加省时省力。

一、打开IEDA新建一个项目,就叫做SpringBoot:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

二、在项目里新建一个modules,取名为SpringBoot-demo1
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

在上面点击Next之后,跳到下面图片
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
选中之后点击finish—>apply—>ok即可

三、编写测试程序
在Application尝试输出一段话,检查一下代码系统是否正确:

package com.example.springbootdemo1;

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

@SpringBootApplication
public class SpringBootDemo1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo1Application.class, args);
        System.out.println("鸡到底美不美?");
    }

}

【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
很明显,我们创建的第一个SpringBoot成功了。

SpringBoot配置文件详解

属性配置

一、 我们可以看到,SpringBoot项目下的Resources目录下有一个application.properties的配置文件,SpringBoot通过配置文件application.properties就可以修改默认的配置,什么意思呢?举个例子,因为SpringBoot采用的是内嵌tomcat的方式,所以默认端口是8080,我现在通过application.properties配置文件把8080修改为8081:

server.port=8081

执行测试:可以看到端口号已经由8080变为8081
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
上述例子说明了application.properties配置文件可以更改SpringBoot提供的默认配置,设置成我们实际需要的配置。

配置文件分类

SpringBoot使用一个全局的配置文件,配置文件名是固定的(都必须是application.开头),支持三种格式(properties、yaml、yml),由于properties类型的我们已经用过很多,这里就不再过多赘述,这里介绍一下yaml或者yml。

一、创建application.yaml、application.yml文件
yml:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
yaml:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
可以看到两者的用法和格式完全一样,那么是不是说两个作用一样呢?答案是两者一样,所以在使用过程中,我们一般选择yml格式

二、yml、yaml的注意点

1、以空格的缩进来控制层级关系,左对齐的一列数据,属于同一个层级
2、yaml、yml 格式:k: v,之间的空格必须有
3、k 和 v 对大小写敏感
4、k: v,字符串默认不用加上单引号或者双引号
5、在这两个配置文件中#表示注释

三、yml中各种数据类型的使用

对象、map类:
普通写法:

 
Practitioner:
  name: kunkun
  age: 3
 

行内写法:

Practitioner: {name: kunkun,age: 3}

数组:
普通写法:

#缩略格式
Practitioner:
  - name: kunkun
    age:3
    likes:
      - sing
      - dance
      - rap
      - basketball
  - name: xiaoheizi
    age: 4
    likes: 
      - kunkun
      - zhenxiatou
      - suzhi666

行内写法:

Practitioner: [{name: kunkun,age: 3,hobby: [sing,dance,rap,basketball]},
{name: xiaoheizi,age: 4,hobby: [kunkun,zhenxiatou,suzhi666]}]

四、配置文件读取

1、读取单个数据

package com.example.springbootdemo1.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author 不止于梦想
 * @date 2022/10/21 21:12
 */
@RestController
public class indexController {
    @Value("${name}")
    public String username;

    @ResponseBody
    @RequestMapping("/index")
    public String welcomeView(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",username);
        System.out.println(username);
        return "hello";
    }
}

//配置文件

name: kunkun


结果:【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎
技巧:如果数据存在多层级,依次书写层级名称即可

注意:这里踩一个坑,我们在写配置文件的时候,一般都是key value键值对的,而key的值除非是你想要的,不然不要写成user,写成user系统会自动赋值为你系统的管理员:

#这里尝试验证
user:
  name: kunkun


package com.example.springbootdemo1.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author 不止于梦想
 * @date 2022/10/21 21:12
 */
@Controller
public class indexController {
    @Value("${user.name}")
    public String username;

    @ResponseBody
    @RequestMapping("/index")
    public String welcomeView(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",username);
        System.out.println(username.toString());
        return "hello";
    }
}


结果如下:【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

2、读取全部数据
提问:读取全部数据是使用@value标签给所有属性都注入值?
从上面我们可以看到,如果配置文件里的值是少量的,那么可以用@value标签给需要的属性赋值,但是在我们的日常开发中,配置文件的内容很多,一个一个注入得把我们累死!

解决方案:SpringBoot提供了一个对象,能够把所有的数据都封装到这一个对象中,这个对象叫做Environment,使用自动装配注解可以将所有的yaml数据封装到这个对象中

3、读取对象数据
因为Java是一个面向对象的语言,很多情况下,我们会将一组数据封装成一个对象。SpringBoot也提供了可以将一组yml对象数据封装一个Java对象的操作:

第一步:编写配置文件

student:
  username: kunkun
  age: 3
  hobby: dance
    

第二步:编写一个对象类,并且将该对象类作为bean注入到Spring容器中,然后使用注解@ConfigurationProperties指定该对象加载哪一组yaml中配置的信息。

package com.example.springbootdemo1.pojo;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component//交给Spring容器保管
@ConfigurationProperties(prefix = "student")//对应的application.yml配置文件的位置
public class Student{
    private String username;
    private int age;
    private String hobby;

    @Override
    public String toString() {
        return "Student{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", hobby='" + hobby + '\'' +
                '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

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

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public Student() {
    }

    public Student(String username, int age, String hobby) {
        this.username = username;
        this.age = age;
        this.hobby = hobby;
    }
}

第三步,编写测试类

package com.example.springbootdemo1;

import com.example.springbootdemo1.pojo.Student;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBootDemo1ApplicationTests {
    @Autowired
    private Student student;
    @Test
    void contextLoads() {
        System.out.println(student);
    }

}

测试结果如下:
【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

总结:@value和@ConfigurationProperties都是获取配置文件信息的;@value常用在获取单个或者少量的配置文件,而后者常需要对应配置文件属性的封装类,即把文件属性映射写成一个封装的类,并把类交给spring管理(常配合Component使用)。然后使用@ConfigurationProperties添加前缀以对应起来配置文件的属性。

SpringBoot整合Thymeleaf模板引擎

Thymeleaf简介

一、Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似

二、Thymeleaf的主要目标是将优雅的自然模板带到您的开发工作流程中—HTML能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。

三、Thymeleaf的主要目标是提供一个优雅和高度可维护的创建模板的方式。 为了实现这一点,它建立在自然模板的概念之上,以不影响模板作为设计原型的方式将其逻辑注入到模板文件中。 这改善了设计沟通,弥合了前端设计和开发人员之间的理解偏差。

示例:Thymeleaf 通过在 html 标签中,增加额外属性来达到“模板+数据”的展示方式,示例代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf命名空间-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于在展示文本-->
<h1 th:text="欢迎来到Thymeleaf">欢迎访问静态页面</h1>
</body>
</html>

当直接使用浏览器打开时,浏览器展示结果如下。

欢迎来到Thymeleaf

当通过 Web 应用程序访问时,浏览器展示结果如下。

欢迎访问静态页面

整合

SpringBoot整合Thymeleaf需要三个步骤:

一、引入对应Thymeleaf的starter其实在以后的整合中,要整合什么技术,就引入该技术的starter即可:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.7.3</version>
</dependency>

二、创建模板文件,并放在指定目录下

2.1 由于 SpringBoot 为 thymeleaf 提供了一整套的自动化配置方案,我们几乎不用做任何更改就可以直接使用,如下是SpringBoot中thymeleaf的默认配置

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
	public static final String DEFAULT_PREFIX = "classpath:/templates/";
	public static final String DEFAULT_SUFFIX = ".html";
	/**
	 * Whether to check that the template exists before rendering it.
	 */
	private boolean checkTemplate = true;
	/**
	 * Whether to check that the templates location exists.
	 */
	private boolean checkTemplateLocation = true;
	/**
	 * Prefix that gets prepended to view names when building a URL.
	 */
	private String prefix = DEFAULT_PREFIX;
	/**
	 * Suffix that gets appended to view names when building a URL.
	 */
	private String suffix = DEFAULT_SUFFIX;
	/**
	 * Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
	 */
	private String mode = "HTML";
	...
}

通过 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 找到 SpringBoot 中 thymeleaf 的默认配置:

 
@ConfigurationProperties //这个注解熟不熟悉,这不就是上面的读取配置文件注入的注解吗?
DEFAULT_ENCODING :默认字符编码,为utf-8
DEFAULT_PREFIX  默认前缀表达式,值为"classpath:/templates/",即类路径下的templates,对应了SpringBoot项目下的Resource下的templates。
DEFAULT_SUFFIX 后缀表达式,默认为.html

从上面代码可以看出,thymeleaf 模板文件默认放在 resources/templates 目录下,默认的后缀是 .html。
当然,我们有时候不想用默认配置,因为需求是多样的,这个时候SpringBoot也是提供了个性化的方法供我们使用。
在SpringBoot配置文件中:

spring:
  #thymeleaf模板引擎
  thymeleaf:
    #是否开启缓存
    cache: false
    #编码格式
    encoding: UTF-8


这里我把缓存关闭,就能使页面进行实时的更新。

三、整合thymeleaf 模板引擎
上面已经把starter导入了,然后配置了thymeleaf,接下来编写测试

编写一个Controller:

package com.example.springbootdemo1.controller;


import com.example.springbootdemo1.pojo.User;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 不止于梦想
 * @date 2022/10/21 21:12
 */
@RestController
public class indexController {

    @RequestMapping("/index")
    public ModelAndView indexView(){
        ModelAndView mv = new ModelAndView();
        List<User> userList = new ArrayList<>();
        for(int i=0;i<5;i++){
            User user = new User("zhangsan"+i,5+i);
            userList.add(user);
        }
        mv.addObject("user",userList);
        mv.setViewName("index");
        return mv;
    }
}

编写要跳转的index.html界面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf命名空间-->
<head>
    <meta charset="UTF-8">
    <title>Title</title>74
</head>
<body>
<table border="1">
    <tr>
        <td>用户姓名</td>
        <td>用户年龄</td>
    </tr>
    <tr th:each="item : ${userList}">
        <td th:text="${item.userName}"></td>
        <td th:text="${item.userAge}"></td>
    </tr>
</table>
</body>
</html>

在配置文件中,编写视图解析器:

spring:
  #thymeleaf模板引擎
  thymeleaf:
    #是否开启缓存
    cache: false
    #编码格式
    encoding: UTF-8
  mvc:
    view:
      prefix: /pages/
      suffix: .html

总结

SpringBoot是一门十分重要的技术,而学习这门技术有一定的门槛,需要我们掌握Spring技术栈的相关东西,而Spring Boot对于后面分布式的服务又是至关重要的,SpringCloud是在Spring Boot基础之上才能加以学习的,所以每一个Java技术人员,都应该学好SpringBoot。文章来源地址https://www.toymoban.com/news/detail-422156.html

到了这里,关于【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 整合Thymeleaf教程及使用 springboot配合thymeleaf,调用接口不跳转页面只显示文本

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。 目录 一、整合

    2024年02月08日
    浏览(66)
  • springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理

    本系统为springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理。页面为极简模式,没有任何渲染。 源码:https://gitee.com/qfp17393120407/spring-boot_thymeleaf 架构截图 此处以用户表为例,其他表数据可在源码获取。 用户表 共用属性 共用属性自动填充配置

    2024年02月07日
    浏览(39)
  • SpringBoot -04 Thymeleaf入门与基础语法

    在spring的官方中并不支持jsp的渲染模板,对jsp并不友好,推荐使用Thymeleaf、FreeMarker等模板引擎 .html(不能取域对象的值) 能写Java代码的HTML,但是thymsleaf可以取值存值 特点: 动静结合:Thymeleaf页面可以独立运行,不依赖与服务器(jsp不可以) 开箱即用:支持标准的模板语言,

    2024年02月02日
    浏览(70)
  • Spring6 + thymeleaf基础整合

    tomcat10 spring(mvc)6 thymeleaf

    2024年02月16日
    浏览(29)
  • SpringBoot整合RabbitMQ(基础)

    一.环境准备 1、在pom文件中引入对应的依赖: 2、在application.yml配置文件中配置RabbitMQ: 二、整合 点对点,简单模式 ①配置文件中声明队列 ②创建生产者 消息发送成功后,在web管理页面查看: 可以看到对应队列中产生了消息 ③创建消费者 启动项目,可以看到消息成功消费:

    2024年02月11日
    浏览(27)
  • Elasticsearch基础,SpringBoot整合Elasticsearch

    Elasticsearch,简称为es,es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通

    2024年01月19日
    浏览(34)
  • Elasticsearch基础入门及整合SpringBoot

    目录 一.下载镜像文件 二.创建实例 2.1 创建elasticsearch实例 2.2 创建Kibana实例 三.es初步索引 1、_cat 2、索引一个文档(保存) 3、查询文档  4.更新文档 5.删除文档索引   6.bulk 批量 API 四.进阶检索 1、SearchAPI  2、Query DSL 1)、基本语法格式 Elasticsearch 提供了一个可以执行查询的

    2024年02月04日
    浏览(29)
  • Kafka 基础整理、 Springboot 简单整合

    定义: Kafka 是一个分布式的基于发布/订阅默认的消息队列 是一个开源的分布式事件流平台,被常用用于数据管道、流分析、数据集成、关键任务应用 消费模式: 点对点模式 (少用) 消费者主动拉取数据,消息收到后清除消息 发布/订阅模式 生产者推送消息到队列,都消费者

    2024年02月03日
    浏览(64)
  • ES基础、高级特性及整合SpringBoot

            之前给服务器安好了ES和Kibana一直没来得及动手试试,这篇就系统性地介绍一下ES的基本使用和特性,以及如何将其与SpringBoot整合。         本文基于 ElasticSearch 7.5.0 + Kibana 7.5.0,版本一定要一致! 目录 1 什么是ElasticSearch? 2 ElasticSearch基本概念 2.1 ElasticSearch/Ki

    2024年02月05日
    浏览(32)
  • 206、SpringBoot 整合 RabbitMQ 的自动配置类 和 对应的属性处理类 的知识点

    ▲ Spring Boot 提供了一个 spring-boot-starter-amqp 的Starter来支持RabbitMQ,只要添加该Starter,它就会添加 spring-rabbit 依赖库(它有传递依赖了amqp-client.jar) ▲ 只要类加载路径下包含了 spring-rabbit 依赖库, Spring Boot 会自动配置 CachingConnectionFactory (CachingConnectionFactory:带缓存的连接工

    2024年02月07日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包