Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc @modeldattribute注释是如何工作的?为什么可以';难道我没有得到价值吗?_Spring Mvc - Fatal编程技术网

Spring mvc @modeldattribute注释是如何工作的?为什么可以';难道我没有得到价值吗?

Spring mvc @modeldattribute注释是如何工作的?为什么可以';难道我没有得到价值吗?,spring-mvc,Spring Mvc,这是我的密码: public ModelAndView login(@ModelAttribute("testVO") TestVO testVO){ //test the VO work theory //testVO = new TestVO(); testVO.setTestStr("this is my test!"); return "index/index"; } 当我使用new为testVO创建一个对象时。 我无法在jsp页面中获取该值。 如果我使

这是我的密码:

public ModelAndView login(@ModelAttribute("testVO") TestVO testVO){
    //test the VO work theory
    //testVO = new TestVO();
    testVO.setTestStr("this is my test!");
    return "index/index";
}
当我使用new为testVO创建一个对象时。 我无法在jsp页面中获取该值。 如果我使用set方法,它会工作

因此,我认为: 对象testVo是由IOC容器创建的,因此JSP从容器中获取引用,而不是我自己创建的容器

我说得对吗?
高级版谢谢。

你猜对了。以下文本来自spring文档:

An @ModelAttribute on a method argument indicates the argument should be 
retrieved from the model. If not present in the model, the argument should be
instantiated first and then added to the model.
如果您想自己创建它,您需要将它添加到模型中(如下所示),以便在jsp中使用

public String login(Model model){

    TestVO testVO = new TestVO();
    testVO.setTestStr("this is my test!");

    model.addAttribute("testVO", testVO);
    return "index/index";
}

伙计,这里是@modeldattribute注释的最佳解释:

至少读两章。这将给你一个理论知识

你可以在我的博客上找到一个实用的问题:


我希望这会对你有所帮助

把你班上的其他同学发上来。但默认情况下,模型属性每次都是一个新实例,并且将根据请求数据中的任何内容设置值。感谢您的解释!谢谢你,Alex,你认识到我应该再次阅读API文档。当我再次阅读时,我发现了一些新的东西,真的谢谢!下面是我的jsp页面中的代码<代码>测试VO:。我使用了你上面发布的代码,效果很好。我认为应该首先在方法中设置一个参数,以便commandName可以匹配testVO。我错了,只是和模型上的匹配。非常感谢你!