springboot使用web登陆页面连接数据库代码
时间: 2023-04-05 08:02:41 浏览: 174
spring连接数据库代码
3星 · 编辑精心推荐
您好,以下是使用 Spring Boot 连接数据库的示例代码:
1. 首先,在 pom.xml 文件中添加以下依赖:
```
<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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
```
2. 在 application.properties 文件中添加以下配置:
```
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
```
3. 创建一个实体类 User:
```
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// 省略 getter 和 setter 方法
}
```
4. 创建一个 UserRepository 接口:
```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
5. 创建一个 LoginController 控制器:
```
@Controller
public class LoginController {
@Autowired
private UserRepository userRepository;
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, HttpSession session) {
User user = userRepository.findByUsername(username);
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("user", user);
return "redirect:/home";
} else {
return "login";
}
}
@GetMapping("/home")
public String home(HttpSession session) {
User user = (User) session.getAttribute("user");
if (user != null) {
return "home";
} else {
return "redirect:/login";
}
}
}
```
6. 创建一个 login.html 页面:
```
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="/login">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
```
7. 创建一个 home.html 页面:
```
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome, ${user.username}!</h1>
<a href="/logout">Logout</a>
</body>
</html>
```
以上就是使用 Spring Boot 连接数据库的示例代码,希望能对您有所帮助。
阅读全文