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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27111806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:15:25  来源:igfitidea点击:

Validation form in Spring using @Valid not work

javaspringvalidationcontroller

提问by The Nightmare

I want to validation my form, but this not work. My entity 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 和表单转到 addAdmin 页面:

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

控制器:

    @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. Why @Valid not work?

当我尝试发送空公式时,我应该收到错误消息result.hasErrors()而不是返回错误,我的应用程序转到其他地方并尝试保存用户。为什么@Valid 不起作用?

采纳答案by Bohuslav Burghardt

Are you sure that the validations don't work? Unless you have for example StringTrimmerEditorregistered, your fields will actually be String instances with length equal to 0, not nullvalues 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 @NotBlankannotation. Also I just tried it myself and the @Emailannotation also passes for empty Strings, which would mean that your empty form IS actually valid right now.

如果要验证 String 不为空(不是 null 也不是空字符串),请使用例如@NotBlank注释。此外,我自己@Email也尝试过,注释也通过空字符串,这意味着您的空表单现在实际上是有效的。

回答by ntholi

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. If your application is using validation features, you'll need to manually add back a dependency on spring-boot-starter-validationin your build file.

将我的项目升级到 Spring Boot 2.3.0 后,我为同样的问题苦苦挣扎了几个小时,直到我意识到从#19550 开始,Web 和 WebFlux 启动器在默认情况下不再依赖于验证启动器。如果您的应用程序正在使用验证功能,您将需要spring-boot-starter-validation在构建文件中手动添加回依赖项。

回答by Munna kumar patra

<mvc:annotation-driven/>

check whether above tag is declared within dispatcher-servlet.xml or not. This tag will be active all annotation.

检查上面的标签是否在 dispatcher-servlet.xml 中声明。此标记将激活所有注释。

回答by Derek J.

Today (2018-04-22), the hibernate-validatorhave been update to version 6.0.9.Final. On my test, I found the nested object valid using @Validcan 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:

今天(2018-04-22),hibernate-validator已经更新到了6.0.9.Final版本。在我的测试中,我发现使用@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) {
   //...
}