我正在加载一个用户对象,我调用一个服务,然后将该用户存储为控制器中GET模型中的命令对象。此用户对象具有许多未在jsp页面中映射的属性。提交表单后,我在POST时获取控制器的命令对象。但奇怪的是,我只在命令对象中看到映射到jsp页面的属性。当我加载对象时那些所有其他属性都丢失了。我需要对象中的所有属性才能将其成功保存在hte数据库中。
有人可以帮我解决这个问题吗?谢谢!
更新
我正在添加一些代码以便更好地理解它。在POST处理程序中,除了使用jsp绑定的属性之外,我还希望命令对象具有在GET处理程序中加载的所有属性。相反,我失去了所有的东西,除了那些与jsp绑定的东西。我在这里做错了吗?
@RequestMapping(method = RequestMethod.GET)
public String showForm(ModelMap model, HttpSession session, HttpServletRequest request) throws Exception {
UserBean user = Util.getUser(session);
UserBean command = (UserBean)userProfileService.loadByUserName(user.getUserName());
model.addAttribute("command", command);
return formView;
}
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("command") UserBean command, BindingResult result, HttpSession session) throws Exception {
UserBean user = (UserBean) command;
userProfileService.saveUser(user);
return "successView";
}
更新
我正在添加一些代码以便更好地理解它。在POST处理程序中,除了使用jsp绑定的属性之外,我还希望命令对象具有在GET处理程序中加载的所有属性。相反,我失去了所有的东西,除了那些与jsp绑定的东西。我在这里做错了吗?
@RequestMapping(method = RequestMethod.GET) public String showForm(ModelMap model, HttpSession session, HttpServletRequest request) throws Exception { UserBean user = Util.getUser(session); UserBean command = (UserBean)userProfileService.loadByUserName(user.getUserName()); model.addAttribute("command", command); return formView; }
@RequestMapping(method = RequestMethod.POST) public String onSubmit(@ModelAttribute("command") UserBean command, BindingResult result, HttpSession session) throws Exception { UserBean user = (UserBean) command; userProfileService.saveUser(user); return "successView"; }
更新
如果我将命令对象存储在会话中,jsp如何绑定该属性。我以为我需要将它存储在模型中? 你能解释一下吗。
更新
在会话中存储命令对象可以解决问题。我能够使用
存储它@SessionAttributes ("command")
非常感谢!
答案 0 :(得分:1)
这是预期的行为。 Spring不会占用您现有的对象(如何获取它?) - 它会创建一个新对象并用数据填充它。
您可以使用@ModelAttribute
带注释的方法来指定一个方法,该方法将通过其ID(已提交)从存储(db?)加载现有对象。
@ModelAttribute带注释的方法在选择的@RequestMapping带注释的处理程序方法之前执行。它们有效地使用通常从数据库加载的特定属性预填充隐式模型。然后,可以通过所选处理程序方法中的@ModelAttribute注释处理程序方法参数访问此类属性,可能会对其应用绑定和验证。
答案 1 :(得分:0)
Spring-MVC Model
值成为JSP中的Request范围属性。这是一种单向转换,当用户从您的页面发布表单时,Spring-MVC不会恢复Model
值。
当我需要在GET和POST之间存储信息时(即在GET上设置某些东西并在POST上读回),我设置了一个Session属性。
在您的情况下,我认为您需要执行以下操作之一:
Util.getUser(session);
方法调用onSubmit
。command
对象存储在showForm
的会话中,并使用onSubmit
方法> 答案 2 :(得分:0)
@ModelAttribute用于直接设置来自jsp的Student对象中的值,另外在servlet中你需要使用request.getattribute()来获取属性,而不是调用student setter方法。 所以你可以在jsp页面中使用这两个关键字。
<form action="grade" method="get" name="contact1" modelAttribute="contact1">
</form>
或