目录
SpringBoot创建
创建方式可以通过官网创建,也可以通过IntelliJ IDEA创建spring boot项目
通过spring initializr网站创建
2. 选择构建工具的版本,选择依赖的模块(Dependecies)
3. 点击Generate Project下载项目压缩包
4. 解压后,使用IDEA导入即可
通过IDEA开发工具新建
1. File->New->Project , 选择Spring Initializr
此处的package源码中已经修改为com.example.spring.windmill
2. 根据需要勾选依赖的dependencies
3. next->finish
本文选用IDEA开发工具创建工程
简单测试Spring Boot
1. 新建HelloController.java文件
2. 输入以下代码:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello...spring boot***";
}
}
3. 启动工程,浏览器打开 http://localhost:8080/hello ,显示
如果报一下错误,
则在启动类里面添加
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
了解配置文件
spring boot的配置文件一般在resources目录下,可以为 application.properties 或 application.yml
yaml 是以数据为中心的语言,本例中适用yml文件进行配置
两者不同的写法:
注意:
yml文件中的属性名称冒号(:)后面有空格,没有空格如图,属性名称没有颜色变化
样例测试
在yml文件中配置name,age属性,在HelloController 添加代码并测试
打开 http://localhost:8080/hello
继续修改yml文件和HelloController文件
重新启动spring boot,打开http://localhost:8080/hello
配置封装类
以上配置当属性过多时比较臃肿,将配置信息封装成类可避免在Controller中适用很多的@Value注解
如将上述信息封装成个人信息类 PersonInfo.java
修改yml
修改HelloController类
重新启动spring boot,打开http://localhost:8080/hello
与数据库连接
添加依赖
pom文件中条件servlet、tomcat、mybatis的依赖
添加list.jsp
在src/main目录下依次创建 webapp、WEB-INF、views 文件夹,再创建一个 list.jsp 文件
新建表
通过navicat新建一个student表,新建语句
CREATE TABLE `student` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`student_id` int(4) NOT NULL,
`name` varchar(64) DEFAULT NULL,
`age` int(4) DEFAULT NULL,
`sex` varchar(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
数据库连接配置
添加相关文件
新建mapper和pojo目录,并添加Person.java和PersonMapper
public class Person {
private Integer id;
private Integer student_id;
private String name;
private Integer age;
private String sex;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getStudent_id() {
return student_id;
}
public void setStudent_id(Integer student_id) {
this.student_id = student_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
新建Controller包添加PersonController.java
在启动类中添加mapper扫描路径
编辑list.jsp
重启工程,打开http://localhost:8080/listInfo
注意事项
中间有几个坑需要注意
serverTimezone=UTC问题:
配置文件yml在数据库连接后添加
没有添加报错
包扫描问题
启动类中没有配置包扫描路径,会出错,另外spring boot启动类中自动加了,可以将其注释掉
出现
代码地址
git: github连接
csdn:csdn博客 本来想免费,系统默认5个币,感谢支持