简体   繁体   English

Spring 中使用@Valid 的验证表单不起作用

[英]Validation form in Spring using @Valid not work

I want to validation my form, but this not work.我想验证我的表单,但这不起作用。 My entity class我的实体 class

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

@Entity
@Table(name = "users")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    @NotNull
    @Size(max = 20)
    @Column(name = "username")
    private String username;
    @NotNull
    @Size(max = 20)
    @Column(name = "password")
    private String password;
    @NotNull
    @Size(max = 20)
    @Column(name = "firstName")
    private String firstName;
    @NotNull
    @Size(max = 20)
    @Column(name = "lastName")
    private String lastName;
    @Size(min = 11, max = 11)
    @Column(name = "personalId")
    private String personalId;
    @Size(max = 40)
    @Column(name = "city")
    private String city;
    @Size(max = 40)
    @Column(name = "address")
    private String address;
    @NotNull
    @Email
    @Size(max = 30)
    @Column(name = "email")
    private String email;
    @Size(min = 9, max = 9)
    @Column(name = "phone")
    private String phone;
    @OneToMany(mappedBy = "user")
    private Set<UserRole> userRoleSet;
}

adminList.jsp and form go to addAdmin page: adminList.jsp 和表单 go 添加管理页面:

<form action="addAdminForm" method="post">
    <input type="submit" value="Dodaj administratora" />
</form>

addAdmin.jsp page formule: addAdmin.jsp页面公式:

    <form:form action="addAdmin" modelAttribute="user" method="post">
    <form:label path="username">Login: </form:label>
    <form:input path="username" />
    <form:errors path="username" cssClass="error" />
    <br />
    <form:label path="password">Hasło: </form:label>
    <form:password path="password" />
    <form:errors path="password" cssClass="error" />
    <br />
    <form:label path="firstName">Imię: </form:label>
    <form:input path="firstName" />
    <form:errors path="firstName" cssClass="error" />
    <br />
    <form:label path="lastName">Nazwisko: </form:label>
    <form:input path="lastName" />
    <form:errors path="lastName" cssClass="error" />
    <br />
    <form:label path="email">Email: </form:label>
    <form:input path="email" />
    <form:errors path="email" cssClass="error" />
    <br />
    <input type="submit" value="Dodaj" />
</form:form>

Controller: Controller:

    @RequestMapping(value = "/admin/addAdminForm", method = RequestMethod.POST)
public ModelAndView goAddAdminForm() {
    ModelAndView mav = new ModelAndView("admin/addadmin");
    mav.addObject("user", new User());
    return mav;
}

@RequestMapping(value = "/admin/addAdmin", method = RequestMethod.POST)
public String addAdmin(@Valid @ModelAttribute("user") User user,
        BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "admin/addadmin";
    } else {
        userService.createUser(user);
        user = userService.findByUsername(user.getUsername());
        UserRole userRole = new UserRole("ROLE_ADMIN");
        userRole.setUser(user);
        userRoleService.createUserRole(userRole);
        return "redirect:/admin/adminlist";
    }
}

When i try send empty formule i should get error messages result.hasErrors() not return error and my application go to else and try save user.当我尝试发送空公式时,我应该收到错误消息result.hasErrors() not return error 和我的应用程序 go 到 else 并尝试保存用户。 Why @Valid not work?为什么@Valid 不起作用?

After upgrading my project to Spring Boot 2.3.0, I struggled for hours with the same issue until I realized that as of #19550 , Web and WebFlux starters do not depend on the validation starter by default anymore.将我的项目升级到 Spring Boot 2.3.0 后,我为同样的问题苦苦挣扎了几个小时,直到我意识到从#19550 开始,Web 和 WebFlux 启动器在默认情况下不再依赖于验证启动器。 If your application is using validation features, you'll need to manually add back a dependency on spring-boot-starter-validation in your build file.如果您的应用程序正在使用验证功能,则需要在构建文件中手动添加回对spring-boot-starter-validation的依赖项。

Are you sure that the validations don't work?您确定验证不起作用吗? Unless you have for example StringTrimmerEditor registered, your fields will actually be String instances with length equal to 0, not null values when you submit the form and therefore the annotation would consider such values to be valid.除非您已注册StringTrimmerEditor ,否则您的字段实际上将是长度等于 0 的 String 实例,而不是提交表单时的null值,因此注释会认为这些值是有效的。

If you want to validate that String is not blank (not null and not an empty String), use for instance the @NotBlank annotation.如果要验证 String 不为空(不是 null 也不是空字符串),请使用例如@NotBlank注释。 Also I just tried it myself and the @Email annotation also passes for empty Strings, which would mean that your empty form IS actually valid right now.此外,我自己也尝试过, @Email注释也通过空字符串,这意味着您的空表单现在实际上是有效的。

I struggled with the same issue in my Spring Boot 2.4.1 project.我在 Spring Boot 2.4.1 项目中遇到了同样的问题。 You'll need to add this dependency in your pom.xml file您需要在 pom.xml 文件中添加此依赖项

...
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
...

I had the same error (the application did not validate).我有同样的错误(应用程序没有验证)。

I added我加了

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

and worked!并工作!

<mvc:annotation-driven/>

check whether above tag is declared within dispatcher-servlet.xml or not.检查上面的标签是否在 dispatcher-servlet.xml 中声明。 This tag will be active all annotation.此标记将激活所有注释。

Today (2018-04-22), the hibernate-validator have been update to version 6.0.9.Final .今天(2018-04-22), hibernate-validator已经更新到了6.0.9.Final版本。 On my test, I found the nested object valid using @Valid can be work <= version 5.2.5.Final , I don't understand why the latest can't working (maybe someone can explain in future), here is my code:在我的测试中,我发现使用@Valid有效的嵌套对象可以工作 <= version 5.2.5.Final ,我不明白为什么最新的不能工作(也许将来有人可以解释),这是我的代码:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PackQueryReq {

    // ......

    @NotNull(message = "params can't be NULL")
    @Valid
    private PackQueryParams params;
}
public class PackQueryParams {

    @Min(value=1)
    @NotNull(message = "enterpriseId can't be NULL")
    private Integer enterpriseId;
}

And on spring MVC controller:在 spring MVC 控制器上:

public Resp query(@RequestBody @Valid PackQueryReq packQuery) {
   //...
}

I had the same issue with 2.5.0 (SNAPSHOT) spring boot project.我在 2.5.0 (SNAPSHOT) spring boot 项目中遇到了同样的问题。 I added the below dependency in the pom.xml file and it worked.我在 pom.xml 文件中添加了以下依赖项并且它起作用了。

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

I had the same problem in Kotlin with old beans automatically converted from Java.我在Kotlin中遇到了同样的问题,旧 bean 自动从 Java 转换。 They were missing the field target specifier , without which the javax.validation annotations had no effect.他们缺少field目标说明符,没有它javax.validation注释无效。

A Kotlin snippet from the question code (with field to solve the problem):问题代码中的 Kotlin 片段(带有解决问题的field ):

@field:NotNull
@field:Size(max = 20)
@Column(name = "username")
var username:  String

I had to change the version of hibernate-validator.我不得不更改 hibernate-validator 的版本。 With 8.0.0 does not work, but with 6.1.5 does. 8.0.0 不起作用,但 6.1.5 起作用。

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.5.Final</version>
    </dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM