美文网首页
modelAttribute 三

modelAttribute 三

作者: 程序员札记 | 来源:发表于2023-07-10 22:46 被阅读0次

数据转换convertIfNecessary

一路调用内部最后到这里:


image.png image.png image.png

最后抛异常了:


image.png

这里明显会转换错误,我故意的,如果是数字的话肯定是没问题的。
这下次我改改:


image.png

有了:


image.png

请求参数不存在的情况createAttribute

前面分析的都是请求参数存在了,如果不存在呢,其实就是用构造方法创建一个对象。

    protected Object createAttribute(String attributeName, MethodParameter parameter,
            WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

        MethodParameter nestedParameter = parameter.nestedIfOptional();
        Class<?> clazz = nestedParameter.getNestedParameterType();

        Constructor<?> ctor = BeanUtils.findPrimaryConstructor(clazz);
        if (ctor == null) {
            Constructor<?>[] ctors = clazz.getConstructors();
            if (ctors.length == 1) {
                ctor = ctors[0];
            }
            else {
                try {
                    ctor = clazz.getDeclaredConstructor();
                }
                catch (NoSuchMethodException ex) {
                    throw new IllegalStateException("No primary or default constructor found for " + clazz, ex);
                }
            }
        }

        Object attribute = constructAttribute(ctor, attributeName, parameter, binderFactory, webRequest);
        if (parameter != nestedParameter) {
            attribute = Optional.of(attribute);
        }
        return attribute;
    }

我们尝试让请求参数不存在,这次没有name1了:

image.png

但是有异常了,因为我们需要int类型,这个基本类型,没有默认构造方法,那我们改成Integer看看:
[图片上传失败...(image-41115f-1689086027603)]

改成Integer

image.png

也一样:


image.png

因为他们都要找默认构造函数,是不存在的。所以要么有这个请求参数,要么改成其他类型,比如String比较好。比如我改成Dog吧,至少有默认构造函数,可以实例化出来。

image.png image.png

相关文章

网友评论

      本文标题:modelAttribute 三

      本文链接:https://www.haomeiwen.com/subject/dflyudtx.html