spring boot 01
一、spring boot介绍
1、优势
创建独立的 Spring 应用程序
嵌入的 Tomcat,无需部署 WAR 文件
简化 Maven 配置
自动配置 Spring
提供生产就绪型功能,如指标,健康检查和外部配置
2、特性
为基于 Spring 的开发提供更快的入门体验
开箱即用,没有代码生成,也无需 XML 配置。同时也可以修改默认值来满足特定的需求
提供了一些大型项目中常见的非功能特性,如嵌入式服务器、安全、指标,健康检测、外部配置等
Spring Boot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式
二、搭建springboot项目
通过spring initializr创建spring boot项目选择
选择spring boot的版本号和所需要的依赖
项目就可以直接运行起来,如果创建项目的时候忘记勾选了,后续在手动的加上这些依赖
默认包扫描的地址,Application(main函数)所在的那个包
三、如何访问到前端页面
1. 引入所需的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 编写Controller就可以了
@Controller
public class DemoController {
@RequestMapping("index")
public String index(String name, Model model) {
model.addAttribute("name", name);
return "index";
}
}
3. 编写页面
放到resource/templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>项目首页</title>
</head>
<body>
<h1>第一个页面</h1>
<div th:text="${name}"></div>
</body>
</html>
四、怎么读取后端的值
通过Model可以设置这个值
可以通过模板引擎读取值
<div th:text="${name}"></div>
五、介绍配置文件
读取resource/application.properties \ application.yml
端口号配置,项目前缀配置
yml
server:
port: 8080
servlet:
context-path: /api
properties
server.port=8085
server.servlet.context-path=/springboot
不同环境的配置
application-环境1
application-环境1
指定激活的环境
spring.profiles.active=dev
六、项目打包
mvn clean package
运行
java -jar jar包
七、集成jdbcTemplate
1. 引入依赖
<!-- 添加mysql jdbc依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加springboot jdbcTemplate依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2. 添加配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
dbcp2:
max-idle: 20
min-idle: 10
3. 注入jdbcTemplate执行sql语句
@Controller
@AllArgsConstructor
public class DemoController {
private final JdbcTemplate jdbcTemplate;
@RequestMapping("index")
public String index(String name, Model model) {
model.addAttribute("name", name);
return "index";
}
@RequestMapping("user")
public String test() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from t_user");
System.out.println(list);
return "user";
}
}
4. 循环渲染
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="ch">
<head>
<meta charset="UTF-8">
<title>用户界面</title>
</head>
<body>
用户界面
<table>
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<tr th:each="item:${list}">
<td
th:text="${item.id}"></td>
<td
th:text="${item.username}"></td>
<td
th:text="${item.password}"></td>
</tr>
</tbody>
</table>
</body>
</html>
八、自动打开浏览器
package com.tledu.springboot01.core;
import lombok.AllArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class OpenBrowser implements CommandLineRunner {
private final Environment environment;
@Override
public void run(String... args) throws Exception {
System.out.println("应用已经准备就绪 ... 启动浏览器并自动加载指定的页面 ... ");
try {
String port = environment.getProperty("server.port");
String contextPath = environment.getProperty("server.servlet.context-path");
//指定自己项目的路径
Runtime.getRuntime().exec("cmd /c start http://localhost:"+port+contextPath);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
九、知识点
1. thymeleaf常用配置
spring:
thymeleaf:
cache: false #清除缓存,实现热部署
mode: LEGACYHTML5 #回避HTML进行严格的检查的配置,当然你需要提前引入nekohtml依赖。
# 配置了前缀
prefix: classpath:/templates/
# 配置了后缀
suffix: .html
web:
resources:
# 配置静态文件路径默认是classpath:/static/
static-locations: classpath:/static/
mvc:
# 静态文件匹配模式
static-path-pattern: /**
2. 设置th的命名空间
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
设置完成之后,就会代码的提示了
3. 取值操作
3.1 取普通值
th:text="${}"
<div th:text="${name}"></div>
3.2 取富文本
th:utext="${}"
<div th:utext="${content}"></div>
3.3 取对象的值
3.3.1 通过对象加属性的方法
<div th:text="${user.username}"></div>
3.3.2 通过th:object
<ul th:object="${user}">
<li th:text="*{username}">用户名</li>
<li th:text="*{password}"></li>
<li th:text="*{id}"></li>
</ul>
3.4 在标签内获取对应值
默认情况th:text 会覆盖掉标签内的值,这时候如果我们希望他们能共存的话
<div th:inline="text">
用户名:[[${name}]]
</div>
3.5 在js脚本中取值
<script th:inline="javascript">
var name = [[${name}]];
console.log(name)
</script>
3.6 数据处理
我们经常需要对元数据进行一些处理,这里thymeleaf给我们提供了数据处理的api
<!-- 时间格式化 -->
<p th:text="${#dates.format(mydate,'yyyy-MM-dd')}" />
<p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss.SSS')}" />
<hr />
<!-- 替换 把.换成$ -->
<p th:text="${#strings.replace('www.baidu.cn','.','$')}" />
<!-- 转大写 -->
<p th:text="${#strings.toUpperCase('www.baidu.cn')}" />
<!-- 去除两边空格 -->
<p th:text="${#strings.trim(' www.baidu.cn ')}" />
<hr />
<!-- 判断names中是否包含boot-0 -->
<p th:text="${#sets.contains(names,'boot-0')}" />
<p th:text="${#sets.contains(names,'boot-9')}" />
<!-- 元素个数 -->
<p th:text="${#sets.size(names)}" />
<hr />
<!-- 判断ids中是否包含 0 -->
<p th:text="${#sets.contains(ids,0)}" />
<!-- 取出下标为1的元素 -->
<p th:text="${ids[1]}" />
<p th:text="${names[1]}" />
除了上面提到的api,还有很多别的api,大家用到的时候可以自行查阅
4. 地址操作
4.1 spring boot 内置地址处理
spring boot内置了地址处理,如果需要引用静态资源,我们可以通过@{}处理地址
<!-- 引用 js-->
<script th:src="@{/js/index.js}" ></script>
<!-- 引用 css-->
<link rel="stylesheet" type="text/css" th:href="@{/css/index.css}">
<!-- 引用 图片-->
<img th:src="@{/images/mao.png}" alt="图片"/>
4.2 在css中引入静态资源
可以通过相对地址引用
div {
background-color: lightblue;
background-image: url("../images/mao.png");
}
4.3 链接跳转
<a href="detail">详情</a>
<a href="/api/detail">绝对地址</a>
<a th:href="@{/detail}">thymeleaf写法</a>
<a th:href="@{/detail?name=张三丰}">thymeleaf传参</a>
<a th:href="@{/detail(name=张三丰,id=123)}">thymeleaf新写法</a>
<a th:href="@{/detail(name=${name},id=123)}">thymeleaf引用变量</a>
5. 获取内置对象
当我们需要使用内置对象的时候,可以通过#内置对象获取,如
<!-- 使用request中的方法 -->
<p th:text="${#httpServletRequest.getRemoteAddr()}" />
<!-- 获取request中的数据 -->
<p th:text="${#httpServletRequest.getAttribute('requestMessage')}" />
<!-- 获取session中的数据 -->
<p th:text="${#httpSession.getAttribute('sessionMessage')}" />
<p th:text="${#httpSession.getId()}" />
<!-- 获取项目根目录 -->
<p th:text="${#httpServletRequest.getServletContext().getRealPath('/')}" />
<hr />
<!-- 默认获取request中的数据 -->
<p th:text="'requestMessage = ' + ${requestMessage}" />
<!-- 获取session中的数据,需要使用session调用 -->
<p th:text="'sessionMessage = ' + ${session.sessionMessage}" />
<!-- 获取application中的数据,需要使用application调用 -->
<p th:text="'applicationMessage = ' + ${application.applicationMessage}" />
6、条件判断
6.1 th:if
满足条件的显示
6.2 th:unless
不满足条件的显示
<div th:unless="${user == null}" th:object="${user}">
<div th:text="*{username}"></div>
<div th:text="*{password}"></div>
</div>
<div th:if="${user == null}">
暂无数据
</div>
6.3 当条件不为bool类型时的判断依据
不只是布尔值的 true 和 false, th:if 表达式返回其他值时也会被认为是 true 或 false,规则如下:
boolean 类型并且值是 true, 返回 true
数值类型并且值不是 0, 返回 true
字符类型(Char)并且值不是 0, 返回 true
String 类型并且值不是 “false”, “off”, “no”, 返回 true
不是 boolean, 数值, 字符, String 的其他类型, 返回 true
值是 null, 返回 false
7. 循环渲染
<ul>
<li th:each="item,eachInfo:${list}" th:object="${item}">
<div th:text="*{username}"></div>
<div th:text="*{password}"></div>
<div th:text="${eachInfo}"></div>
</li>
</ul>
th:each="【数组的每一项】,【遍历的信息】:【遍历的数组】"