1.创建SpringBoot项目
项目骨架结构:
2.配置Maven依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
3.修改application.properties为application.yml并配置如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot
username: root
password: *****
driver-class-name: com.mysql.jdbc.Driver
thymeleaf:
suffix: .html
prefix: classpath:templates/
encoding: utf-8
cache: false
4.创建各文件
4.1User实体类
public class User {
private Long id;
private String name;
private Integer age;
private String email;
...省略get和set方法
}
4.2 UserController类
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUsersList")
public String getUsersList(Model model)
{
List<User> userList = userService.getUsersList();
model.addAttribute("userList", userList);
return "user";
}
}
4.3UserService类
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUsersList()
{
List<User>userList = userMapper.findAll();
if(userList!= null){
return userList;
}
return null;
}
}
4.4UserMapper类
@Mapper
public interface UserMapper {
@Results({
@Result(property = "name", column = "f_name"),
@Result(property = "age", column = "f_age"),
@Result(property = "email", column = "f_email")
})
@Select("SELECT f_name, f_age, f_email FROM t_user")
List<User> findAll();
@Insert("INSERT INTO t_user(f_name, f_age) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
@Update("UPDATE t_user SET f_age=#{age} WHERE f_name=#{name}")
void update(User user);
@Delete("DELETE FROM t_user WHERE id =#{id}")
void delete(Long id);
@Insert("INSERT INTO t_user(f_name, f_age) VALUES(#{name}, #{age})")
int insertByUser(User user);
@Insert("INSERT INTO t_user(f_name, f_age) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);
}
4.5 user.html模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title> thymeleaf 模板的练习</title>
</head>
<body>
<table>
<tr th:each="user : ${userList}">
<td>姓名: </td> <td th:text="${user.name}"></td>
<td> email:</td> <td th:text="${user.email}"></td>
<td>年龄: </td> <td th:text="${user.age}"></td>
</tr>
</table>
</body>
</html>