gpt4 book ai didi

spring - 没有强制执行表单输入约束?

转载 作者:行者123 更新时间:2023-11-28 23:52:46 24 4
gpt4 key购买 nike

我是 Tomcat 和 Spring Web 的新手。我正在尝试通过以下方式使用 Spring 的表单验证功能 this tutorial .一切似乎都运行顺利,除了一件事......我的表单没有进行任何验证,无论我提供什么数据,当我发送表单时我总是可以到达成功页面。

我是否正确使用了约束?我想强制用户填写他们的名字,并且名字至少包含两个字符。

package net.devmanuals.form;

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;

public class RegistrationForm {
@NotEmpty(message = "You surely have a name, don't you?")
@Size(min = 2, message = "I'm pretty sure that your name consists of more than one letter.")
private String firstName;

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return this.firstName;
}
}

表单代码:

    <form:form method="post" commandName="regform">
<p><form:input path="firstName" /> <form:errors path="firstName" /></p>
<p><input type="submit" /></p>
</form:form>

Controller :

@Controller
@RequestMapping("/register")
public class RegistrationController {
@RequestMapping(method = RequestMethod.GET)
public String showRegForm(Map model) {
RegistrationForm regForm = new RegistrationForm();
model.put("regform", regForm);
return "regform";
}

@RequestMapping(method = RequestMethod.POST)
public String validateForm(@Valid RegistrationForm regForm, BindingResult result, Map model) {
if (result.hasErrors()) {
return "regform";
}

model.put("regform", regForm);
return "regsuccess";
}
}

我是否错误地应用了约束?

最佳答案

除了添加<mvc:annotation-driven/>对于您的配置,您需要确保 JSR-303 jar 在您的类路径中。来自docs :

[AnnotationDrivenBeanDefinitionParser] ... configures the validator if specified, otherwise defaults to a fresh Validator instance created by the default LocalValidatorFactoryBean if the JSR-303 API is present on the classpath.

关于spring - 没有强制执行表单输入约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5888779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com