SpringBoot学习笔记

SpringBoot简介

SpringBoot是一个Spring家族中的一个全新的框架,用来简化Spring应用程序的创建和开发过程,也可以说SpringBoot能简化我们之前采用SpringMVC+Spring+MyBatis框架进行开发的过程

1.1.什么是SpringBoot
springboot 是 spring 快速开发脚手架,通过约定大于配置的方式,快速构建和启动 spring 项目.
springboot根据我们项目中所引入的依赖,比如引入了springmvc构件,就会判断出是要进行springmvc的web开发,就会把springmvc的相关基本配置自动配置好了,不需要我们在xml中配置。 比如配置前端控制器DispatcherServlet、配置视图解析器、配置静态资源访问、处理器映射器、处理器适配器等一系列组件,

1.2.SpringBoot解决了哪些痛点
spring 的缺点:
1.复杂的配置
项目各种配置是开发时的损耗, 写配置挤占了写应用程序逻辑的时间。
2.混乱的依赖管理
项目的依赖管理非常的繁琐。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这是一个棘手的问题。并且,一旦选错了依赖的版本,随之而来的就是各种的不兼容的bug
spring boot 可以解决上面 2 个问题

1.3.SpringBoot有哪些特性
快速开发 spring 应用的框架
内嵌 tomcat 和 jetty 容器,不需要单独安装容器,使用main方法就可以 直接启动发布一个 web应用
简化 maven 配置,通过继承 parent构件 ,一站式引入需要的各种依赖(启动器),简化依赖管理
通过 约定大约配置的方式可以实现基于注解的零配置思想
和各种流行框架, spring web mvc , mybatis , spring cloud 无缝整合
官网
总结
spring boot 是 spring 快速开发脚手架,通过约定大于配置,优化了混乱的依赖管理,和复杂的配置,让我们用java -jar方式,运行启动 java web 项目

1.4SpringBoot四大核心
1)自动配置
2)起步依赖
3)Actuator
4) 命令行界面

使用Eclipse创建一个SpringBoot工程

1.先下载springboot的插件
2.创建工程
.在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

pow 简单了解

<?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.6.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<!-- 自己项目的坐标 -->
	<groupId>com.ycx</groupId>
	<artifactId>001</artifactId>
	<version>1.0.0</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
	<!-- jdk的版本 -->
		<java.version>1.8</java.version>
		<maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
	</properties>
	<!-- SpringBoot框架web项目起步依赖 -->
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
       <!-- SpringBoot 框架测试起步依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
		<!-- springboot项目打包编译依赖 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

在生成的工程的 src/main/java目录下有一个springboot的启动类
在这里插入图片描述

在src/main/resources 目录下
static 目录用于存放静态资源
templates 目录用于存放 模板 springboot官方推荐使用Thymeleaf 处理前端
application.properties springboot核心配置文件

注意!! 以后写代码需要在springboot入口类所在包的同级或下级目录下来进行编写

第一个springboot项目
在springboot的入口类下面的包里有一个控制器
在这里插入图片描述
在这里插入图片描述
这时在springboot入口类中启动springboot
在页面输入地址可以得到
在这里插入图片描述
注意!!!

1.要想修改tomcat端口号在
这个目录下server.port=80
2.输入地址的时候不要使用https 不然会报错

3.在application.properties 可以配置上下文根

使用springboot框架的核心配置文件 application.yml 或者application.properties
配置文件只能有一个 可以使用application.yml 也可以使用 application.properties
新建 yml 的方式 new – file —取名为application.yml
yml的格式
在这里插入图片描述
若两种配置文件都存在的话以 properties的为准

多环境下核心配置文件的使用

在工作中,一个项目的诞生需要经历开发、测试、准生产、生产等多个步骤,在不同的步骤中我们使用的配置文件也可能存在不同,因此,我们需要对不同的环境配置相应的配置文件,并在主核心配置文件中选择我们当前要使用的配置文件。
方式一使用properties
可以给每个环境建一个properties 命名规范 application-xxx.properties
在这里插入图片描述
你就可在新建的properties中定义你所需要的内容 然后在主核心配置文件中使用spring.profiles.active=指定使用哪个配置文件
=号后面填写的是你的配置文件-后的名 例如在这里
使用来启动
方式二使用 yml

可以给每个环境建一个yml 命名规范 application-xxx.yml

通过
在这里插入图片描述
来启动

application.properties自定义配置

1) 一个个获取
有时候我们需要在配置文件中定义一些不存在的属性供我们使用 这时我们就需要使用自定义配置
我们可以使用 @Value(“{属性}”)注解来获取我们在配置文件中声明的属性
在这里插入图片描述
在这里插入图片描述
2)映射到一个对象(必须要有前缀)
我们配置文件中的属性 想要映射到我们的一个类中的属性
1.将类交给spring容器管理 使用 @Component
2.使用@ConfigurationProperties使其成为核心配置类 其有个前缀(prefix=“”)属性不能为空 属性值为我们配置文件中属性的前缀
3.想要使用的话直接通过注解注入类 @Autowried
在这里插入图片描述

@Component
@ConfigurationProperties(prefix="a")
public class School {
	private String ycx;
	private String psd;
	public String getYcx() {
		return ycx;
	}
	public void setYcx(String ycx) {
		this.ycx = ycx;
	}
	public String getPsd() {
		return psd;
	}
	public void setPsd(String psd) {
		this.psd = psd;
	}

}

在这里插入图片描述

springboot集成jsp

1.在已存在的src/main新建webapp在这里插入图片描述
2在application.properties中配置视图解析器

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

右键项目 选propeties 进行项目配置
在这里插入图片描述
点击apply后应用

会生成webcontent 这个文件夹 可以删除他 因为我们使用的是maven 的自己配置的web 或者webapp目录

右键项目 properties 配置

这时候会有一个这个目录
在这里插入图片描述
选中他 remove 掉 webcontent , 添加自己的web目录
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
把web-inf移动进去
添加jsp文件

在这里插入图片描述
添加对jsp的支持jar

<!-- 对jsp 解析的支持 -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

springboot 集成mybatis

1) 添加mybatis依赖 ,mysql驱动、

不添加版本号的话会自动使用父类的父类管理的版本号 当然也可以自己指定版本号、

<!-- mysql驱动 -->
		<dependency>
		 	<groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- mybatis整合Springboot框架的起步依赖 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.0</version>
		</dependency>

使用mybatis逆向工程
跟之前mybatis中一样使用
在这里插入图片描述
在mapper接口(dao层)添加@Mapper注解
在这里插入图片描述
在applicatio.properties中配置数据库连接信息、

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xiaomissm?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

若你的xml文件
在这里插入图片描述

不在resources下 你需要在pow.xml中手动把它们变为resources

在这里插入图片描述
若有很多dao 一个个加mapper岂不是很麻烦 所以我们可以在我们的入口类中 中添加@MapperScan()注解
其中有个属性为basePackages 后面填写的是 包名
@Mapper()

SpringBoot项目下使用事物

事物是一个完整的功能,也叫做是一个完整的业务
事物只跟DMLsql语句有关 也就是 增删改
使用@Transactional注解

SpringBoot中集成SpringMVC中常用的注解

@RestController 相当于控制层类加上@Controller+@ResponseBody,意味着当前控制层类中所有方法返回的都是JSON对象

@GetMapping(value=“/hello”) 就相当于 @RequestMapping(value=“/hello”,methon =RequestMethod.GET)
通常在查询数据的时候使用

@PostMapping 也类似 该注解通常在新增数据的时候使用

@DeleteMapping 也类似 该注解通常在删除数据时使用

@PutMapping 也类似 该主机通常在修改数据时使用

SpringBoot 实现RESTful

主要使用 @PathVariable获取请求路径中的参数
没有使用之前

	@RequestMapping("/student")
      public  Admin admin(Integer id,String psw){
		Admin a =new Admin();
		a.setaId(id);
        a.setaName("哈哈");
        a.setaPass(psw);              
		return  a ;		
	}

在页面中使用
在这里插入图片描述
来出发响应
使用@PathVariable我们可以

	@RequestMapping("/student/{id}/{psw}")
    public  Admin admin2(@PathVariable("id")Integer id,
    		@PathVariable("psw")String psw){
		Admin a =new Admin();
		a.setaId(id);
      a.setaName("哈哈");
      a.setaPass(psw);              
		return  a ;		
	}

在页面使用
在这里插入图片描述
第一二个参数被@PathVariable获取
但是如果要是还有一个请求他只是请求路径发生变法 如
@RequestMapping(“/student/{id}/{ppp}”)这样的话我们在网页中发出的请求都是上图这种的 它就没法区分了 所以我们需要使用RESTful风格来区分
若是查询 我们可以使用
@GetMapping(“/student/{id}/{ppp}”)来进行

SpringBoot使用拦截器

1.定义一个拦截器实现HandlerInterceptor接口

package com.bjpowernode.springboot.interceptor;

import com.bjpowernode.springboot.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截的规则
        //从session中获取用户的信息
        User user = (User) request.getSession().getAttribute("user");

        //判断用户是否为空
        if (null == user){
            response.sendRedirect(request.getContextPath() + "/user/page/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}


2.定义一个配置类实现WebMvcConfigurer接口 相当于是之前的注册配置文件
@Configuration //只要类上加@Configuration,就说明此类为一个配置类,就相当于一个xml配置文件

在这里插入图片描述

package com.bjpowernode.springboot.config;

import com.bjpowernode.springboot.interceptor.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration  //只要类上加@Configuration,就说明此类为一个配置类,就相当于一个xml配置文件
public class SystemConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //定义要拦截的路径
        String[] addPathPatterns = {
                "/user/**"
        };

        //排除不需要拦截的路径
        String[] excludePathPatterns = {
                "/user/page/login",
                "/user/login"
        };

        registry.addInterceptor(new UserInterceptor())
                .addPathPatterns(addPathPatterns)
                .excludePathPatterns(excludePathPatterns);
    }
}


SpringBoot使用Filter过滤器

方式一注解实现
新建一个类 实现Filter 接口 重写doFilter方法 在类上面加上@WebFilter注解 在入口类上扫描到这个和过滤器
在入口类中使用 @ServletComponentScan注解

@WebFilter(urlPatterns="/firstfilter")
public class FirstFilter implements Filter{
 
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("进入过滤器");
		
	}
}

在这里插入图片描述

SpringBoot设置字符编码

1.新建一个字符编码过滤器

package com.ycx.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration //将此类定义为配置类
public class SystemConfig {

	@Bean
public FilterRegistrationBean chFilterRegistrationBean(){
        //创建字符编码过滤器
		
CharacterEncodingFilter characterEncodingFilter	 =new CharacterEncodingFilter();	
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("utf-8");

		FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();		
		//设置字符编码过滤器
		filterRegistrationBean.setFilter(characterEncodingFilter);
//设置字符编码过滤器 路径		
		filterRegistrationBean.addUrlPatterns("/*");
		
		return filterRegistrationBean;
}
	
	
}

2.在application.properties 中关闭SpringBoot的http字符编码支持
在这里插入图片描述
方式二:
在application.properties 中 直接设置

server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8

SpringBoot 集成 Thymeleaf 模板

1.创建项目

在这里插入图片描述
2.pom.xml 文件下会自动添加如下依赖


		<!-- SpringBoot框架集成Thymeleaf的起步依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<!-- SpringBoot框架Web项目起步依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

注意!!
1 ·所有的想要被解析的html页面都必须在rescources的templates文件夹下 这个文件夹是跟随项目的生成而生成的
2 · html页面想要使用templates标签必须加上命名空间 xmlns:th="http://www.thymeleaf.org xmlns->命名空间

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2 th:text="${data}">哈哈哈我显示了</h2>
</body>
</html>

控制层

@Controller
public class UserControl
	
	
	 @RequestMapping(value="/hello")
	 public String index(Model model) {
	 model.addAttribute("data","SpringBoot 集成 Thymeleaf 模版!");
	
	 return "hello";
	 }

}

在这里插入图片描述
测试

在这里插入图片描述

但是这样有个问题就是 你改页面数据刷新它并不能显示出来最新的数据
所以我们需要在核心配置文件application.properties 中设置

可选项

#thymeleaf 模版前缀,默认值,可选项
spring.thymeleaf.prefix=classpath:/templates/
#thymeleaf 模版后缀,默认值,可选项
spring.thymeleaf.suffix=.html

设置关闭thymeleaf的缓存

#设置 thymeleaf 页面缓存失效
spring.thymeleaf.cache=false

这时候更改页面就能显示更新后的页面了

URL 表达式原文链接
语法@{…}
主要用于链接、地址的展示,可用于

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>URL 路径表达式 -> @{}</title>
</head>
<body>
<h1>URL 路径表达式:@{...}</h1>
<h2>绝对路径(没有参数)</h2>
<a th:href="@{http://localhost:8080/thymeleaf/info}">查看:绝对路径</a>
<h2>绝对路径(路径中有参数)</h2>
<a th:href="@{'http://localhost:8080/thymeleaf/user/info?id=' + 
${user.id}}">查看用户信息:绝对路径(带参数)</a>
<h2 style="color: red">实际开发推荐使用:相对路径(没有参数)</h2>
<a th:href="@{/thymeleaf/info}">查看:相对路径</a>
<h2 style="color: red">实际开发推荐使用:相对路径(路径中有参数)</h2>
<a th:href="@{'/thymeleaf/user/info?id=' + ${user.id}}">查看用户信息:相
对路径(带参数)</a>
<a th:href="@{/thymeleaf/info(id=${user.id})}">推荐使用:优雅的带参数路径
写法</a>
</body>
</html>

为了演示加上下文的效果,在 application.properties 中配置项目上下文

#设置上下文根
server.servlet.context-path=/url-expression

在 ThymeleafController 中添加如下方法:

@RequestMapping(value = "/thymeleaf/url")
public String url(Model model) {
 User user = new User();
 user.setId(2);
 user.setName("赵六");
 user.setPhone("13800000000");
 user.setAddress("上海市");
 model.addAttribute("user",user);
 return "url";
}
@RequestMapping(value = "/thymeleaf/info")
public String info(Integer id) {
 System.out.println("用户编号:" + id);
 return "info";


在这里插入图片描述
在这里插入图片描述
th:each这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与JSTL 中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map
遍历 List 集合
A、 在 ThymeleafController 中添加 eachList 方法,准备集合数据

@RequestMapping("/each/list")
public String eachList(Model model){
 List<User> userList = new ArrayList<User>();
 for (int i = 0;i < 10;i++){
 User user = new User();
 user.setId(100 + i);
 user.setNick("张" + i);
 user.setPhone("1361234567" + i);
 user.setAddress("北京市大兴区" + i);
 userList.add(user);
 }
 model.addAttribute("userList",userList);

 return "each";
}

创建 eachList.html 对 List 集合进行遍历

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>循环遍历 List 集合</title>
</head>
<body>
<h1>th:each 循环遍历 List 集合</h1>
<div style="color: red">
 1.user:当前对象的变量名<br/>
 2.userStat:当前对象的状态变量名<br/>
 3.${userList}:循环遍历的集合<br/>
 4.变量名自定义
</div>
<div th:each="user,userStat:${userList}">
 <span th:text="${userStat.index}"></span>
 <span th:text="${user.id}"></span>
 <span th:text="${user.name}"></span>
 <span th:text="${user.phone}"></span>
 <span th:text="${user.address}"></span>
</div>
</body>
</html>

代码说明
th:each="user, iterStat : ${userlist}"中的 u s e r L i s t 是 后 台 传 过 来 的 集 合 u s e r 定 义 变 量 , 去 接 收 遍 历 {userList} 是后台传过来的集合 user 定义变量,去接收遍历userList是后台传过来的集合user定义变量,去接收遍历{userList}集合中的一个数据
◼ iterStat
${userList} 循环体的信息
◼ 其中 user 及 iterStat 自己可以随便取名
◼ interStat 是循环体的信息,通过该变量可以获取如下信息
index: 当前迭代对象的 index(从 0 开始计算)
count: 当前迭代对象的个数(从 1 开始计算)这两个用的较多
size: 被迭代对象的大小
current: 当前迭代变量
even/odd: 布尔值,当前循环是否是偶数/奇数(从 0 开始计算)
first: 布尔值,当前循环是否是第一个
last: 布尔值,当前循环是否是最后一个
注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat
在这里插入图片描述
遍历 Map 集合

@RequestMapping(value = "/each/map")
public String eachMap(Model model) {
 Map<Integer,Object> userMaps = new HashMap<Integer, Object>();
 for (int i = 0; i < 10; i++) {
 User user = new User();
 user.setId(i);
 user.setName("李四"+i);
 user.setPhone("1390000000"+i);
 user.setAddress("天津市"+i);
 userMaps.put(i,user);
 }
 model.addAttribute("userMaps",userMaps);
 return "eachMap";
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>循环遍历 Map 集合</title>
</head>
<body>
<h1>th:each 循环遍历 Map 集合</h1>
<div th:each="userMap,userMapStat:${userMaps}">
 <span th:text="${userMapStat.count}"></span>
 <span th:text="${userMap.key}"></span>
 <span th:text="${userMap.value}"></span>

 <span th:text="${userMap.value.id}"></span>
 <span th:text="${userMap.value.name}"></span>
 <span th:text="${userMap.value.phone}"></span>
 <span th:text="${userMap.value.address}"></span>
</div>
</body>
</html>

th:if
th:unless

@RequestMapping(value = "/condition")
public String condition(HttpServletRequest request,Model model) {
 User user1 = null;
 model.addAttribute("user1",user1);
 User user2 = new User();
 user2.setId(1001);

 user2.setName("小岳岳");
 user2.setPhone("13900000000");
 user2.setAddress("北京市");
 model.addAttribute("user2",user2);
 model.addAttribute("sex",1);
 User user3 = new User();
 user3.setId(1002);
 user3.setName("孙悦");
 user3.setPhone("13200000000");
 user3.setAddress("北京市");
 model.addAttribute("user3",user3);
 request.getSession().setAttribute("user3",user3);
 return "condition";
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>条件判断</title>
</head>
<body>
<h1>th:if 用法:如果满足条件显示,否则相反</h1>
<div th:if="${sex eq 1}">
 男:<input type="radio" name="sex" th:value="1"/>
</div>
<div th:if="${sex eq 0}">
 女:<input type="radio" name="sex" th:value="0"/>
</div>
<h1>th:unless 用法:与 th:if 用法相反,即对条件判断条件取反</h1>
<div th:unless="${sex == 1}">
 男:<input type="radio" name="sex" th:value="1"/>
</div>
<div th:unless="${sex eq 0}">
 女:<input type="radio" name="sex" th:value="0"/>
</div>
<div th:if="${user1 eq null}">
 <h3 style="color: red">用户未登录</h3>
</div>
<div th:unless="${user2 == null}">
 用户姓名:<span th:text="${user2.name}"></span>
</div>
<h1>从 session 中获取值</h1>
<div th:if="${user3 != null}">
 <span th:text="${user3.name}"></span>
</div>
</body>
</html>

th:switch/th:case

<h1>th:switch/th:case 用法</h1>
<div th:switch="${sex}">
 <span th:case="1">性别:男</span><br/>
 <span th:case="2">性别:女</span><br/>
 <span th:case="*">性别:保密</span>
</div>

一旦某个 case 判断值为 true,剩余的 case 默认不执行,“*”表示默
认的 case,前面的 case 都不匹配时候,执行默认的 case

th:inline 使用内敛表达式不需要依托html的标签即可显示后端页面的值

th:inline 有三个取值类型 (text, javascript 和 none),值为 none 什么都不做,没有效果
(1) 内敛文本(th:inline=”text”)
内敛文本表达式不依赖于 html 标签,直接使用**内敛表达式[[表达式]]**即可获取动态数据,但
必须要求在父级标签上加 th:inline = “text”属性

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>内敛文本</title>
</head>
<body>
<h1>标准变量表达式(展示数据)</h1>
用户编号:<span th:text="${user.id}"></span><br/>

用户姓名:<span th:text="${user.name}"></span><br/>
用户手机号:<span th:text="${user.phone}"></span><br/>
用户地址:<span th:text="${user.address}"></span><br/>
<h1>内敛文本 th:inline="text"</h1>
<div th:inline="text">
 用户编号:<div>[[${user.id}]]</div><br/>
 用户姓名:[[${user.name}]]<br/>
 用户手机号:[[${user.phone}]]<br/>
 用户地址:[[${user.address}]]<br/>
</div>
</body>
</html>

注意:一般我们将 th:inline="text"放到标签中

内敛脚本(th:inline=”javascript”)
th:inline=”javascript”在 js 代码中获取后台的动态数据

<script type="text/javascript" th:inline="javascript">
 function showInlineJavaScript() {
 alert("欢迎 " + [[${user.name}]] + " 到我院指导工作!联系方式: " + 
[[${user.phone}]]);
 }
</script>
<button th:onclick="showInlineJavaScript()">展示内容</button>

Thymeleaf 字面量
字面量:对应数据类型的合法取值,可以在 html 页面直接使用,不需要后台传递

文本字面量
用单引号’…'包围的字符串为文本字面量

<h1>文本字面量:用单引号'...'包围的字符串</h1>
<a th:href="@{'/user/info?id=' + ${user.id}}">查看用户:文本字面的路径使用</a><br/>
<span th:text="您好"></span>

数字字面量

<h1>数字字面量</h1>
今年是<span th:text="2019">1949</span><br/>
20 年后,将是<span th:text="2019 + 20">1969</span><br/>

boolean 字面量

<h1>boolean 字面量</h1>
<div th:if="${success}">执行成功</div>
<div th:unless="${flag}">执行不成功</div>

Thymeleaf 字符串拼接

<h1>文本字面量使用"+"拼接字符串</h1>
<span th:text="''+${totalRows}+''+${totalPage}+'页,当前第'+${currentPage}+''"></span>
<h1>另一种更优雅的方式:使用"|要拼接的内容|"减少字符串拼接的加号</h1>
<span th:text="|共${totalRows}条${totalPage}页,当前第${currentPage}页|"></span>

Thymeleaf 运算符
三元运算:表达式?”正确结果”:”错误结果”
算术运算:+ , - , * , / , %
关系比较::> , < , >= , <= ( gt , lt , ge , le )
相等判断:== , != ( eq , ne )

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>运算符</title>
</head>
<body>
<h1>三元运算符</h1>
<span th:text="${sex eq 1 ? '':''}"></span><br/>
<span th:text="${sex == 1 ? '':''}"></span><br/>
20*8=<span th:text="20 * 8"></span><br/>
20/8=<span th:text="20 / 8"></span><br/>
20+8=<span th:text="20 + 8"></span><br/>
20-8=<span th:text="20 - 8"></span><br/>
<div th:if="5 > 2">5>2 是真的</div>
<div th:if="5 gt 2">5 gt 2 是真的</div>
</body>
</html>

Thymaleaf 表达式基本对象
模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由
#号开始引用,我们比较常用的内置对象

#request
#request 相 当 于 httpServletRequest 对 象 , 这 是 3.x 版 本 , 若 是 2.x 版 本 使 用
#httpServletRequest,在页面获取应用的上下文根,一般在 js 中请求路径中加上可以避免 404

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>Thymeleaf 表达式基本对象</title>
</head>
<body>
<script type="text/javascript" th:inline="javascript">
 var basePath = [[${#httpServletRequest.getScheme() + "://" + 
#httpServletRequest.getServerName() + ":" + 
#httpServletRequest.getServerPort() + 
#httpServletRequest.getContextPath()}]];
 //http://localhost:8080/springboot/user/login

 //获取协议名称
 var scheme = [[${#request.getScheme()}]];
 //获取服务 IP 地址
 var serverName = [[${#request.getServerName()}]];
 //获取服务端口号
 var serverPort = [[${#request.getServerPort()}]];
 //获取上下文根
 var contextPath = [[${#request.getContextPath()}]];
 var allPath = scheme+"://"+serverName+":"+serverPort+contextPath;
 alert(allPath);
</script>
</body>
</html>

#session

相当于 HttpSession 对象,这是 3.x 版本,若是 2.x 版本使用#httpSession
在后台方法中向 session 中放数据

<h1>从 SESSION 中获取用户名称</h1>
<span th:text="${#session.getAttribute('username')}"></span><br/>
<span th:text="${#httpSession.getAttribute('username')}"></span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值