gpt4 book ai didi

java - Spring注释表单验证有问题吗?

转载 作者:行者123 更新时间:2023-12-01 04:54:30 25 4
gpt4 key购买 nike

很抱歉问了这么简单的问题。我搜索了很多,但找不到确切的解决方案。

在我的 spring bean 类中,我有像 (private int id) 这样的 int 字段。我使用了 @NotEmpty 注释。

我需要在输入字段中只允许使用数字,而不是任何字母或字符串。我需要使用什么注释。

我尝试了 @NumberFormat(style = Style.NUMBER)@Digits(fraction = 0, integer = 5) 注释,但没有任何效果。

请向我建议表单验证的解决方案或任何示例...

最佳答案

我建议您阅读relevant part of the reference小心。您创建实现 Validator 接口(interface)的 validator :

public class FooValidator implements Validator {

/**
* This Validator validates *just* Foo instances
*/
public boolean supports(Class clazz) {
return Foo.class.equals(clazz);
}

public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Foo foo = (Foo) obj;
if (!isNumeric(foo.getFieldThatShouldBeNumeric())
{
e.rejectValue("fieldThatShouldBeNumeric", "notnumeric");
}
}
}

然后将其注入(inject)“本地”到 Controller 本身:

@Controller
public class MyController {

@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}

@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }

或“全局”:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven validator="globalValidator"/>

</beans>

关于java - Spring注释表单验证有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14395415/

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