Java springboot 验证对我不起作用

问题描述 投票:0回答:1
@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");
    }

还有我的用于注册的邮政映射。看来我的控制器没有运行任何验证并跳过第一个 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);
    }
}

在我的公共 User toUser() 中,我的 setUsername(String) 未解决。我已经检查过是否正确导入了所有内容,当我创建此文件时,我从我的 Users 类中删除了验证。不知道如何解决

java spring-boot validation
1个回答
0
投票

问题在于你的依赖性。

<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>

不需要这些依赖项,因为它们都已经是

spring-boot-starter-validator
的一部分。事实上,您使用的
javax.validation:validation-api
依赖项与 Spring Boot 3 不兼容。Spring Boot 3 与 JakartaEE 版本兼容,而不是 JavaEE 版本(您已包含)。

删除这些依赖项后,您可能会收到编译错误,指出

package javax.validation not found
,请将导入修复为来自
jakarta.validation

通过这些更改,它应该可以工作。

一些额外的提示:

  • 删除
    slf4j
    logback
    依赖项,默认情况下已包含这些依赖项。
  • 删除默认包含的
    spring-boot-starter-logging
    依赖项。
  • 从已为您管理的
    <version>
    lombok
    中删除
    pring-boot-configuration-processor
    标签。事实上,如果你升级 java,你的 Lombok 版本将不再工作。
  • 看起来您正在混合
    io.jsonwebtoken
    依赖项的版本(0.9.1 和 0.11.5),确保这些版本匹配(或删除不需要的版本)。混合来自不同版本依赖项的模块是很麻烦的事。
© www.soinside.com 2019 - 2024. All rights reserved.