简体   繁体   English

Spring MVC @SessionAttributes混乱!

[英]Spring MVC @SessionAttributes confusion!

I'm using 2.5 and doing everything via annotations. 我正在使用2.5并通过注释做所有事情。

I have a simple form that allows the user to edit an object. 我有一个简单的表单,允许用户编辑对象。 The controller behind it creates the object and adds it to the model on GET, and processes the changes on POST (submit). 它后面的控制器创建对象并将其添加到GET上的模型,并在POST(提交)上处理更改。 It works fine, but I don't understand why. 它工作正常,但我不明白为什么。 The object is never explicitly added to the session, and the object's "id" isn't passed to the submit method. 该对象永远不会显式添加到会话中,并且对象的“id”不会传递给submit方法。 How does the submit method of the controller know the object's "id" value? 控制器的submit方法如何知道对象的“id”值?

The reason this question came up is that I have another form / controller that is nearly identical to the one above, but doesn't "work" unless I add the object to @SessionAttributes. 出现这个问题的原因是我有另一个表单/控制器几乎与上面的相同,但除非我将对象添加到@SessionAttributes,否则它不会“工作”。 The difference is that the object this particular controller works with has a reference to another object that is lazy loaded (I'm using Hibernate behind the scenes). 区别在于此特定控制器使用的对象具有对延迟加载的另一个对象的引用(我在后台使用Hibernate)。 When I submit the form without putting the parent object in SessionAttributes, I get a DataIntegrityViolationException because I'm never loading the referenced object. 当我提交表单而不将父对象放在SessionAttributes中时,我得到一个DataIntegrityViolationException,因为我从不加载引用的对象。

When I add the parent object to @SessionAttributes the problem magically disappears. 当我将父对象添加到@SessionAttributes时,问题神奇地消失了。 I say magically because even though I put the parent object into the session on GET, I still never explicitly loaded the referenced object, so it should be null (or an empty proxy or whatever happens). 我神奇地说,因为即使我把父对象放在GET上的会话中,我仍然没有显式加载引用的对象,所以它应该是null(或者是一个空的代理或任何发生的事情)。

What in the world is going on? 世界上到底发生了什么? I need some help! 我需要协助!

The object is most likely recreated during submit phase. 该对象很可能在提交阶段重新创建。 The id might be "stored" in a hidden form field. id可以“存储”在隐藏的表单字段中。

You should be careful with session attributes, I always try to avoid it unless I have a very good reason. 你应该小心会话属性,我总是试图避免它,除非我有一个很好的理由。 In combination with Hibernate it can create all sorts of headache. 与Hibernate结合使用可以产生各种各样的头痛。

If you must, use a fully initialized copy. 如果必须,请使用完全初始化的副本。

How does the submit method of the controller know the object's "id" value? 控制器的submit方法如何知道对象的“id”值?

Controller doesn't know the "id". 控制器不知道“id”。 I think Spring creates new object using default constructor and populates form data into it. 我认为Spring使用默认构造函数创建新对象,并将表单数据填充到其中。 Hibernate must be think that this is a new object and stores it into database with a new id. Hibernate必须认为这是一个新对象,并使用新的id将其存储到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM