我是 Spring-MVC 的新手,我对设置对象属性的机制和在请求之间传递对象的机制感到困惑。这是一个例子。
我有一个名为 Person
的类来存储包含两个字段名称和年龄的信息。下面我有一个名为 PersonController
的 Controller 类。
@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”的 View 的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>
因此,当我单击“提交”按钮时,Spring 将映射到 @RequestMapping("/next")
,它是带注释的方法 getInfo()
。此方法返回 View “下一个”,该 View 显示有关人员对象的信息。
项目运行得很好,但是不知道Spring如何运行才不会报错。在 Controller 类的两种方法中我没有任何设置方法。另外,在 getInfo()
方法中,Spring 如何准确获取我刚刚创建的 Person 对象?我认为如果没有像 @ModelAttribure
或 @SessionAttribute
这样的注释,方法 getInfo()
无法获取对象 Person
并且因此它将为空。但在这个例子中它仍然可以获得信息。那么有人可以向我解释一下这个机制吗?
最佳答案
同样在 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
并且正如文档中与此相关的注释:
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.
因此,如果您想确保在加载和编辑时引用同一个人,则需要以某种方式在模型中,例如在 session 中。更常见的是,您可以从数据库加载,这样您就可以编写一个用 @ModelAttribute
注释的方法,您的 Controller 将如下所示:
@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);
}
}
关于java - 关于设置对象属性的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696221/