@Entity@Table(name = \'users\')public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = \'id\') private UUID userId; @Column(
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private UUID userId;
@Column(nullable = false)
@NotBlank(message = "Name is Required")
private String name;
@Column(nullable = false)
@NotBlank(message = "Password hash is required")
@Size(min = 8, message = " Password must be more than 8 characters and alphanumeric ")
@Alphanumeric(message = "password must be alpahanumeric")
private String hash;
@Column(nullable = false, unique = true)
@NotBlank(message = "Username is required")
@Size(min = 5, max = 20, message = "Username must be between 5 and 20 characters")
private String username;
// a temporary variable to use in controller to check if roleId is valid in the
// Role entity
@Column(name = "user_role", insertable = false, updatable = false)
private Integer roleId;
@ManyToOne
@JoinColumn(name = "user_role", nullable = false, referencedColumnName = "id")
private Role role;
public User() {
这就是我在模型包中设置用户类的方法。
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody @Valid User user, BindingResult bindingResult) {
// Check for validation errors
if (bindingResult.hasErrors()) {
String errorMessage = bindingResult.getAllErrors().get(0).getDefaultMessage();
logger.info("Validation error: {}", errorMessage);
return new ResponseEntity<>("Validation error: " + errorMessage, HttpStatus.BAD_REQUEST);
}
// Check if username already exists
Optional<User> userOptional = userRepository.findByUsername(user.getUsername());
if (userOptional.isPresent()) {
return new ResponseEntity<>("Username already exists", HttpStatus.BAD_REQUEST);
}
// Ensure roleId is provided in the JSON request
Integer roleId = user.getRoleId();
if (roleId == null) {
return new ResponseEntity<>("Role ID is required", HttpStatus.BAD_REQUEST);
}
// Fetch the Role from repository based on roleId
Optional<Role> optionalRole = roleRepository.findById(roleId);
if (!optionalRole.isPresent()) {
return new ResponseEntity<>("Role not found", HttpStatus.BAD_REQUEST);
}
// Set the fetched Role to the User object
Role role = optionalRole.get();
user.setUserRole(role);
// Save the user to the database
userRepository.save(user);
return ResponseEntity.ok("User registered successfully");
}
还有我的注册 Postmapping。看来我的控制器没有运行任何验证并跳过第一个 if 块语句,我能够使用空字段进行注册。我最近开始使用 Java,这是我的第一个 springboot 项目。仍在学习中。
我检查了是否有正确的依赖项
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>management_tool</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>management_tool</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency> -->
<!-- BCrypt for password hashing -->
<!-- <dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency> -->
<!-- JWT for token handling -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version> <!-- Adjust version as per your Spring Boot version -->
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.3.0</version> <!-- Ensure this matches your Spring Boot version -->
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version> <!-- Specify version -->
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version> <!-- Specify version -->
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<!-- Spring Boot manages the version for you -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
还尝试创建一个 UserDto 类,但似乎面临更多问题。
public class UserDto {
@NotBlank(message = "Name is Required")
private String name;
@NotBlank(message = "Password hash is required")
@Size(min = 8, message = " Password must be more than 8 characters and alphanumeric ")
@Alphanumeric(message = "password must be alpahanumeric")
private String hash;
@NotBlank(message = "Username is required")
@Size(min = 5, max = 20, message = "Username must be between 5 and 20 characters")
private String username;
// a temporary variable to use in controller to check if roleId is valid in the
// Role entity
private Integer roleId;
private Role role;
public User toUser() {
return new User()
.setName(name)
.setUsername(username)
.setHash(hash)
.setRoleId(roleId)
.setUserRole(role);
}
}
在我的 public User toUser() 中,setUsername(String) 未解析。我检查了是否正确导入了所有内容,并且在创建此文件时,我从我的 Users 类中删除了验证。不知道该如何解决