以下是一个简单的Spring Boot和HTML结合的登录注册功能模块的示例代码:
1. 创建一个Spring Boot项目并添加依赖
在pom.xml
中添加以下依赖:
<dependencies>
<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>
</dependencies>
2. 创建控制器
@Controller
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/register")
public String register() {
return "register";
}
@PostMapping("/register")
public String registerUser(@ModelAttribute User user) {
// 这里可以添加注册逻辑,例如保存用户信息到数据库
return "redirect:/login";
}
}
3. 创建实体类
public class User {
private String username;
private String password;
// 省略getter和setter方法
}
4. 创建HTML模板
src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Login"/>
</div>
</form>
</body>
</html>
src/main/resources/templates/register.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Register</title>
</head>
<body>
<form action="/register" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Register"/>
</div>
</form>
</body>
</html>
5. 运行Spring Boot应用
在应用的入口类中运行Spring Boot应用:
@SpringBootApplication
public class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
以上代码提供了一个简单的登录和注册功能,并且使用了Thymeleaf作为模板引擎来渲染