有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java关于设置对象属性的机制

我是SpringMVC新手,对设置对象属性的机制和在请求之间传递对象的机制感到困惑。这就是一个例子。 我有一个名为Person的类来存储带有两个字段name和age的信息。我在下面有一个名为PersonController的控制器类

@Controller
public class PersonController {
    @RequestMapping("/home")
    public ModelAndView enterInfo() {
        return new ModelAndView("home", "command",new Person());
    }
    @RequestMapping("/next")
    public String getInfo(Person per, Model md) {
        md.addAttribute("name", per.getName());
        md.addAttribute("age", per.getAge());
        return "next";
    }

}

第一个方法enterInfo()返回引用名为“home”的视图的ModelAndView对象,并创建一个新的空Person对象。这是我的home.jsp文件:

<%@ page session="false" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <form action = "next">
        Name: <input type = "text" name = "name"/><br><br>
        Age: <input type = "text" name = "age"/><br><br>
        <input type = "submit" value = "submit"/>
    </form>
</body>
</html>

因此,当我单击“submit”按钮时,Spring将映射到@RequestMapping("/next"),它是带注释的方法getInfo()。此方法返回视图“next”,其中显示有关person对象的信息

这个项目运行得很好,但我不知道Spring如何能够毫无错误地运行它。在控制器类的两种方法中,我没有任何设置方法。在方法getInfo()中,Spring如何获得我刚刚创建的Person对象?我认为如果没有像@ModelAttribure@SessionAttribute这样的注释,方法getInfo()无法获取对象Person,因此它将为空。但在这个例子中,它仍然可以获得信息。有人能给我解释一下这个机制吗


共 (1) 个答案

  1. # 1 楼答案

    在getInfo()方法中,Spring如何获得我刚刚创建的Person对象

    它不会。它会创建一个新实例

    https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-methods

    Any other argument

    If a method argument is not matched to any of the earlier values in this table [e.g. @ModelAttribute] and it is a simple type (as determined by BeanUtils#isSimpleProperty, it is a resolved as a @RequestParam. Otherwise, it is resolved as a @ModelAttribute.

    因此,它实际上是一个@ModelAttribute,正如文档中所提到的:

    https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-modelattrib-method-args

    You can use the @ModelAttribute annotation on a method argument to access an attribute from the model or have it be instantiated if not present.

    因此,如果您想确保在加载和编辑时引用同一个人,则需要在模型中,例如在会话中。更典型的情况是,您可以从数据库中加载,这样您就可以编写一个带有@ModelAttribute注释的方法,并且您的控制器如下所示:

    @Controller
    public class PersonController {
    
        @RequestMapping("/loadPersonForEdit")
        public String loadPersonForEdit() {
            return "edit";
        }
    
        @RequestMapping("/updatePerson")
        public String updatePerson(Person per) {
            //database update person
            return "personDetails";
        }
    
        //called by the framework on loadPersonForEdit() to set the model attribute
        //on saving the edit, the returned instance will be used passed to updatePerson()
        @ModelAttribute("person")
        public Person getPerson(@RequestParam(value = "personId", required = false) 
                                       Long personId){
           return personId == null ? new Person() : datebase.getPerson(personId);    
        }
    }