gpt4 book ai didi

java - @ModelAttribute注解中声明的Bean的范围是什么

转载 作者:行者123 更新时间:2023-12-02 06:16:33 26 4
gpt4 key购买 nike

我有一个包含 40 列的表和一个与该表对应的 Bean。但在页面上我只显示 10 个字段。当页面呈现时,通过调试,我可以看到 bean 被表中的所有字段填充,并且我使用 model.addAttribute("emp", emp) 将其添加到模型中。但是在更改页面上的某些字段后,当我再次提交页面时,我看到只有那些出现在页面上的字段被填充。尽管该 bean 位于“ session ”范围内,但其余的都不是。

我有一个 Controller ,当我提交页面时会调用该 Controller 。就像下面这样

@RequestMapping({"/update.html"})
public String updateData(@ModelAttribute("emp") Employee emp){
// All fields of Employee bean are not getting populated
}

我在 JSP 中编写了如下内容。

<jsp:useBean class="com.Employee" id="emp"
scope="request" />

注意:- 我也使用scope="session"进行了测试。

所以我的问题是,即使将 bean 放入 SESSION 范围后,为什么我没有将其放入我的 Controller 中。 @ModelAttribute 是如何改变我的 bean 范围的?

最佳答案

方法参数上的

@ModelAttribute 本质上将模型(您通过字段提交的内容)与类型(在本例中为 Employee)绑定(bind),并公开此绑定(bind)类型作为可以在 jsp 中使用的模型。此时它根本不是 Spring bean,只是一个作用域为请求的对象。

现在,关于如何预填充您的 bean,一种更简洁的方法可能是在 Controller 中定义另一个用 @ModelAttribute 注释的方法,该方法负责从数据库加载您的模型方式:

@ModelAttribute("emp")
public Employee loadModelAttributes(@RequestParam("empid") int empid){
// return employee fully populated..
}

这将确保在您的 Controller 方法中,只有您从 UI 提交的字段现在会更新到您从数据库填充的基本 Employee 中,这样您就没有将事物保存在隐藏变量中。

@RequestMapping({"/update.html"})
public String updateData(@ModelAttribute("emp") Employee emp){
// All fields of Employee bean are not getting populated
}

关于java - @ModelAttribute注解中声明的Bean的范围是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21398999/

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