-
什么是SpringBoot?
SpringBoot 是一个快速开发的框架, 封装了Maven常用依赖、能够快速的整合第三方框架;简化XML配置,全部采用注解形式。最明显的特点是,让文件配置变的相当简单、让应用部署变的简单SpringBoot内置服务器,并装备启动类代码,可以快速开启一个Web容器进行开发。
-
快速上手SpringBoot第一个程序
1.导入maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE </version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
注意:spring-boot-starter-parent是一个特殊的starter,以及是Spring Boot 的父级依赖,它用来提供相关的Maven默认依赖,使用它之后,常用的包依赖可以省去 version 标签!
2.编写HelloWorld类之启动方式一,运行点击右键运行即可
@RestController
/**
* 在上加上RestController
* 表示修饰该Controller所有的方法返回JSON格式,直接可以编写
*/
@EnableAutoConfiguration
/**
* 帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot,
* 并创建对应配置类的Bean,并把该Bean实体交给IoC容器进行管理。
*/
public class HelloService {
@RequestMapping("/Hello")
public String Hello() {
return "HelloSpringBoot!";
}
public static void main(String[] args) {
/**
* 是springboot驱动spring应用上下文的引导类
* 他的run()方法启动Spring应用
* 实质上是为Spring应用创建并初始化Spring上下文。
*/
SpringApplication.run(HelloService.class,args);
}
}
如果启动成功你就会看到控制台有这样的信息可以看到端口8008等:
SpringBoot启动方式二:
定义一个HelloTwo.java
@RestController
public class HelloTwo {
@RequestMapping("/open")
public String open() {
return "大阳光你好";
}
}
然后在刚刚你定义的HelloService类里面加上@ComponentScan注解
@ComponentScan("top.yunhuisu.service") //扫描包注解
SpringBoot启动方式三(常用):
定义一个SpringBootApp类,运行和上面一样
@SpringBootApplication
/*SpringBootApplication
是@ComponentScan和@EnableAutoConfiguration的组合
注意SpringBootApplication的ComponentScan扫描是同级包或者子包*/
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class,args);
}
}
-
Web开发之静态资源访问
在我们Web开发中会用到大量的Js,CSS,图片等静态资源
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
Eg:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/Kid.jpg。如能显示图片,配置成功。
静态资源的默认访问优先级:META-INF/resources > resources > static > public
-
SpringBoot的配置
SpringBoot使用的是一个全局的配置文件,就是下面会提到的application.properties配置文件,这个文件的路径放在esources目录下面或者放在类路径下面,并且这个文件名是固定的。
关于这个配置文件有两种格式:application.properties,application.yml
1.编写application.yml文件
Student:
name: "大阳光"
age: 20
2.编写GetYml类
@Controller
public class GetYml {
@Value("${Student.name}")
private String Name;
@Value("${Student.age}")
private int Age;
@RequestMapping("/getYml")
public String getYml() {
return "姓名:"+Name+"\t"+"年龄:"+Age;
}
}
3.启动程序后,尝试访问http://localhost:8080/getYml
-
SpringBoot配置切换
1.测试环境:在resource目录下面建一个application.yml和application-dev.yml多套环境application不变,在后面加-跟环境名字即可
2.怎么实现环境变换,在主yml文件中加上下面的代码
spring:
profiles:
active: dev //active后面就是你的环境名
-
SpringBoot的JSR303验证:
1.在pom.xml中导入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.在你要验证的类上面加上@Validated即可,然后再在字段上面加上具体的验证方法,如下面验证邮箱
@Data
@Component
@ConfigurationProperties(prefix = "student")
@Validated //数据验证
public class Student {
private String name;
private int age;
@Email
private String Email;
private List list;
}
3.JSR303的规则
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前,验证成立的话被注释的元素一定是一个过去的日期
@Future 验证 Date 和 Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期
@Pattern 验证 String 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。
数值检查
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为”“,Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 被指定的元素必须在合适的范围内
@Range(min=10000,max=50000,message=”range.bean.wage”)
@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
-
渲染Web页面
-
使用FreeMarker
1.在pom.xml中导入依赖Jar
<!-- Spring Boot Freemarker 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.在resources目录下面建立一个templates目录,然后建立一个View页面,后缀为ftl,后面会讲到FreeMarker配置后缀可以自己定义
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<p style="color: red;font-size: 12px;font-family: 'Calibri Light'">姓名:${Name}</p>
<p style="color: red;font-size: 12px;font-family: 'Calibri Light'">地址:${Address}</p>
</body>
</html>
3.建一个Controller类
@Controller
public class Freemarker {
@RequestMapping("/index")
public String index(Map<String, Object> student) {
student.put("Name","大阳光");
student.put("Address","成都");
return "index";
}
}
4.启动程序后,尝试访问http://localhost:8080/index
-
FreeMarker配置
1.建一个application.yml(一定要这个名字哈,不然访问会找不到)
spring:
http:
encoding:
force: true
### 模版引擎编码为UTF-8
charset: UTF-8
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
## 模版文件结尾.html
suffix: .html
## 模版文件目录
template-loader-path: classpath:/templates
2.在templatas下面建一个index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<#if (Age >= 18) >
你已成年
<#else>
都不去你未成年
<#-- <#else >-->
<#-- 其他-->
</#if>
<#list userList as user>
${user}
</#list>
</body>
</html>
3.建一个测试类FreeMaker.java
@Controller
public class Freemarker {
@RequestMapping("/index")
public String index(Map<String, Object> student) {
student.put("Name","大阳光");
student.put("Address","成都");
student.put("Age",18);
ArrayList user = new ArrayList<>();
user.add("大阳光海盗");
user.add("大阳光男孩");
student.put("userList",user);
return "index";
}
}
4.试着访问一下localhost:8080/index
注意点:虽然FreeMaker模板可以使用if和list,但是要注意一下就那么写个>是不能解析的
两种方法 :
1 用符号代替: > gt , >= gte ,< lt , <= lte
2 加括号 <#if(x>y)>
-
使用Thymeleaf
1.导入依赖Jar
<!--引入thymeleaf的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.建一个application.yml文件
###ThymeLeaf配置
spring:
thymeleaf:
#prefix:指定模板所在的目录
prefix: classpath:/templates/
#check-tempate-location: 检查模板路径是否存在
check-template-location: true
#cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
cache: true
suffix: .html
encoding: UTF-8
mode: HTML5
3.建一个Thymeleaf类
@Controller
public class Thymeleaf {
@RequestMapping("/index2")
public String index(Map<String, Object> student) {
student.put("Name","大阳光");
student.put("Age",20);
ArrayList<Object> user = new ArrayList<>();
user.add("1");
user.add("2");
student.put("user",user);
return "index";
}
}
4.建一个index.html文件在templates下面,注意这里要加一个约束
<!DOCTYPE html>
<!--需要在HTML文件中加入以下语句: -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show User</title>
</head>
<body>
<table>
<span>姓名:[[${Name}]]</span>
年龄:<span th:text="${Age}"></span>
<span th:if="${Age >= 18}">成年</span>
<span th:each="user:${user}">
<li th:text="${user}"></li>
</span>
</table>
</body>
</html>
5. 试着访问一下localhost:8080/index2
6.常用标签
咱们上面知道Thymeleaf通过特殊的标签来寻找属于Thymeleaf的部分,并渲染该部分内容,而除了上面展示过的th:text
之外还有很多常用标签,并且Thymeleaf也主要通过标签来识别替换对应位置内容,Thymeleaf标签有很多很多,功能也很丰富,这里列举一些比较常用的标签如下:
标签 | 作用 | 示例 |
---|---|---|
th:id | 替换id | <input th:id="${user.id}"/> |
th:text | 文本替换 | <p text:="${user.name}">bigsai</p> |
th:utext | 支持html的文本替换 | <p utext:="${htmlcontent}">content</p> |
th:object | 替换对象 | <div th:object="${user}"></div> |
th:value | 替换值 | <input th:value="${user.name}" > |
th:each | 迭代 | <tr th:each="student:${user}" > |
th:href | 替换超链接 | <a th:href="@{index.html}">超链接</a> |
th:src | 替换资源 | <script type="text/javascript" th:src="@{index.js}"></script> |
-
SpringBoot数据库访问
-
整合Jdbc篇
1.导入数据库连接包和Jdbc包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
2.在application.yml文件中写数据库配置信息
datasource:
url: jdbc:mysql:///vdemo
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
3.在数据库创建一张users表
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
4.在service包下面建一个JDBCTest类
@RestController
public class JDBCtest {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/insertUser")
public String insertUser(String Name,int Age) {
int i = jdbcTemplate.update("INSERT INTO users(name, age) VALUE (?,?)", Name, Age);
return i > 0 ? "插入成功":"插入失败";
}
}
5.试着访问localhost:8080/insertUser?Name=大阳光&Age=20
-
整合Mybaties篇
1.第一步在导入依赖Jar
<!-- springboot 整合mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2.在mapper文件夹下面建一个映射
public interface UserMapper {
@Select("SELECT id as id,name as username,age as age FROM users WHERE id = #{id}")
User FindById(@Param("id") int id);
@Insert("INSERT INTO users(id, name, age) VALUE (null,#{username},#{age})")
int insertUser(Map map);
}
3.在service包下面建一个MybatisTest类
@RestController
public class MybatiesTest {
@Autowired
UserMapper userMapper;
@RequestMapping("/insertMybaties")
public String insertMybaties() {
HashMap<String, Object> user = new HashMap<>();
user.put("username","大阳光男孩");
user.put("age",22);
int i = userMapper.insertUser(user);
return i > 0 ? "插入成功":"插入失败";
}
@RequestMapping("/FindId")
public String FindId() {
User user = userMapper.FindById(2);
return user.toString();
}
}
4.最后即可测试是否成功
-
页面异常处理
@ControllerAdvice
public class HelloTwo {
@RequestMapping("/404")
@ExceptionHandler(RuntimeException.class)
public String open() {
return "404";
}
}