目录
- 一、静态资源导入
- 二、thymeleaf模板引擎
- 三、数据 库相关操作
- 3.1 JDBC
- 3.2 MyBatis
一、静态资源导入
静态资源理解为HTML、CSS、JS、图片等等,不需要查数据库也不需要程序处理就能够显示的页面。
这些静态资源可以放在以下目录:
- resources
- static(默认使用)
- public
优先级从上往下以此降低
二、thymeleaf模板引擎
如果直接用纯静态页面进行开发会很麻烦,但如果使用模板引擎就会简单很多,模板引擎相当于是一个页面框架,可以把后端的数据进行绑定填入,从而生成html文件。
例如jsp就是一个模板引擎,但是SpringBoot是不支持用jsp的,所以就要换一个模板引擎,SpringBoot推荐使用thymeleaf
使用方法:
- 导入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
- 将html文件放在templates目录下
- 在html文件中加入约束
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 在html文件中,将需要赋值的地方用thymeleaf替换。格式是 th:元素名=“变量表达式”
- 普通: ${变量名}
- 选择:*{变量名}
- 国际化消息:#{变量名}
- URL:@{变量名}
- 片段:~{变量名}
<div th:text="${msg}"></div>
- 在controller中创建对应的请求处理方法,并在Model对象中加入想要显示出来的属性即可
@RequestMapping("/test")
public String test(Model model) {
model.addAttribute("msg", "hello world") ;
return "test" ;
}
三、数据 库相关操作
3.1 JDBC
- 在创建项目的时候,选择jdbc的依赖
- 在application.yaml配置文件中写入数据源的用户名、密码、url、驱动等信息
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql//localhost:3306/test
driver-class-name: com.mysql.cj.jdbc.Driver
- JdbcTemplate是一个处理数据库的模板,它自动加载了数据源和各种配置,并且已经在SpringBoot中注册好了,所以可以直接使用JdbcTemplate对象里的各种方法实现各种SQL操作,只需要写好SQL语句并将其作为参数放到各种方法中即可。
@Autowired
JdbcTemplate jdbcTemplate ;
public List<Map<String, Obejct>> select() {
//1、写SQL语句
String sql = "select * from user" ;
//2、调用jdbcTemplate中的方法
List<Map<String, Obejct>> list = jdbcTemplate.queryForList(sql) ;
return lsit ;
}
3.2 MyBatis
- 导入依赖 mybatis-spring-boot-starter
- 在application.yaml配置文件中写入数据源的用户名、密码、url、驱动等信息
- 创建实体类,对应数据库中的表
- 创建mapper接口,并在接口名之前加上@Mapper注解和@Repository注解,分别表明这个接口是MyBatis的,这个接口是dao层的。该接口中写各种想要实现的方法名
@Mapper
@Repository
public interface UserMapper {
User querUserById(int id) ;
int addUser(User user) ;
int updateUser(User user) ;
int deleteUser(int id) ;
}
- 在resources->mapper目录中创建mapper.xml文件,这个过程就完全是MyBatis的过程
- 在SpringBoot的配置文件中整合MyBatis,使其能扫描到MyBatis的东西。之后使用的方式就和以往使用MyBatis一样了
mybatis.mpper-locations=classpath:mapper/*.xml