springboot+html实现简单注册登录
下面是一个简单的Spring Boot和HTML结合实现注册和登录的例子。
首先,你需要创建一个Spring Boot项目并添加相关依赖,比如spring-boot-starter-web
和thymeleaf
。
<!-- 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>
然后,创建控制器来处理注册和登录的请求。
// RegistrationController.java
@Controller
public class RegistrationController {
@GetMapping("/register")
public String registerForm(Model model) {
model.addAttribute("user", new User());
return "register";
}
@PostMapping("/register")
public String registerSubmit(@ModelAttribute User user) {
// 这里应该是将用户信息保存到数据库的逻辑
return "redirect:/login";
}
}
// LoginController.java
@Controller
public class LoginController {
@GetMapping("/login")
public String loginForm(Model model) {
model.addAttribute("user", new User());
return "login";
}
@PostMapping("/login")
public String loginSubmit(@ModelAttribute User user) {
// 这里应该是验证用户信息的逻辑
return "home";
}
}
接下来,创建注册和登录的HTML模板。
<!-- 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" th:field="*{username}" />
</div>
<div>
<label>Password:</label>
<input type="password" th:field="*{password}" />
</div>
<div>
<input type="submit" value="Register" />
</div>
</form>
</body>
</html>
<!-- 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" th:field="*{username}" />
</div>
<div>
<label>Password:</label>
<input type="password" th:fi
评论已关闭