springboot简单项目
时间: 2023-07-01 12:16:39 浏览: 49
下面是一个简单的Spring Boot项目示例,包括了一个简单的Web页面和数据库操作:
1. 创建一个Spring Boot项目,可以使用Spring Initializr或者手动搭建。
2. 添加Spring Boot和数据库(这里以MySQL为例)的相关依赖,例如:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
3. 配置数据库连接信息,在`application.properties`文件中添加以下内容:
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
```
4. 创建一个实体类(例如`User`)和对应的仓库类(例如`UserRepository`),使用JPA实现数据库操作。
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
// getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 创建一个控制器类(例如`UserController`),定义Web页面和数据库操作。
```
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/")
public String index(Model model) {
List<User> userList = userRepository.findAll();
model.addAttribute("users", userList);
return "index";
}
@GetMapping("/addUser")
public String addUserPage() {
return "addUser";
}
@PostMapping("/addUser")
public String addUser(User user) {
userRepository.save(user);
return "redirect:/";
}
}
```
6. 创建两个Thymeleaf模板页面(例如`index.html`和`addUser.html`),分别用于展示用户列表和添加用户。
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</tbody>
</table>
<a href="/addUser">Add User</a>
</body>
</html>
```
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form method="post" action="/addUser">
<label>Name:</label>
<input type="text" name="name"><br>
<label>Age:</label>
<input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
<a href="/">Back to User List</a>
</body>
</html>
```
7. 运行项目,访问`http://localhost:8080/`即可查看所有用户信息,并可以添加新用户。