gpt4 book ai didi

java - 如何使用格式化程序将请求绑定(bind)到表单命令对象的 int 属性的空字符串 http 参数默认为 0?

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:51 25 4
gpt4 key购买 nike

在 spring-mvc 应用程序中,我将字符串 http 请求参数绑定(bind)到命令对象中的 int 字段。我在 DataBinder 中设置了 DefaultFormattingConversionService。如果该参数为空字符串,则绑定(bind)不会成功,我会收到目标字段的 typeMismatch 错误代码。在这种情况下,我希望在 int 字段上设置默认值 (0)。我可以通过扩展 CustomNumberEditor 类并重写其 setValue(Object) 并将其注册到 DataBinder 来实现此目的,如下所示:

        binder.registerCustomEditor(int.class, 
new CustomNumberEditor(Integer.class, nfInt, true)
{
public void setValue(Object o)
{
super.setValue((o == null)? 0 : o);
}
}
);

但是,我想使用 Formatters 来获得与上述属性编辑器相同的行为。我喜欢这样一个事实:可以使用字段/方法级别注释来启用格式化程序,并且一般来说,转换服务框架感觉比基于属性编辑器的框架更容易使用和配置(除了上述问题)。

最佳答案

如果您想将此转换应用于所有模型的整数,您可以做的是注册一个新的 Spring Converter ,而不是使用 Spring Formatter 。您定义自己的逻辑,可以是这样的:

import org.springframework.core.convert.converter.Converter;

class StringToInteger implements Converter<String, Integer> {
public Integer convert(String source) {
return source != null? Integer.valueOf(source) : 0;
}
}

您将像这样在配置类中注册:

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
class WebMvcContext extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToInteger());
}
}

您还可以找到更详细的信息herehere

关于java - 如何使用格式化程序将请求绑定(bind)到表单命令对象的 int 属性的空字符串 http 参数默认为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44264533/

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