Spring Boot实现简单的登录注册功能
以下是一个简单的Spring Boot应用程序示例,它包含了用户的登录和注册功能。这个例子使用了Spring Security来处理安全相关的功能,并使用了Thymeleaf作为模板引擎来渲染HTML页面。
- 首先,在
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-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
</dependencies>
- 创建一个简单的
User
实体类:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and setters...
}
- 创建一个
UserRepository
接口:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
boolean existsByUsername(String username);
}
- 创建
UserController
处理登录和注册逻辑:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/register")
public String registerUser(@RequestParam String username, @RequestParam String password) {
if (userRepository.existsByUsername(username)) {
return "register?error";
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
userRepository.save(user);
return "redirect:/login";
}
@PostMapping("/login")
public String loginUser(@RequestParam String username, @RequestParam String password, Model model) {
// 这里简单起见,不进行密码散列比对
User user = userRepository.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
model.addAttribute("error", "用户名或密码错误");
return "login";
评论已关闭