简体   繁体   English

使用java / j2ee,序列化如何工作以及如何在会话中保存该对象?

[英]With java/j2ee, how does serialization work and in relation to saving that object in session?

If I have a complex object with hundreds of String fields and objects of objects. 如果我有一个包含数百个String字段和对象对象的复杂对象。 Some are implementing Serializable and some aren't. 有些正在实现Serializable,有些则不是。

How would a j2ee server serialize that data in session. j2ee服务器如何在会话中序列化该数据。 Would I expect all data to be returned. 我是否希望返回所有数据。 Even the objects of objects. 甚至是物体的物体。

Session.setAttribute(data) Session.setAttribute(数据)

Eg Session.getAttribute() == data.getData().getData().getData().getData1() 例如Session.getAttribute()== data.getData()。getData()。getData()。getData1()

Will the object returned from getData1() return correctly? 从getData1()返回的对象是否正确返回?

(I am using both Tomcat 6 and Websphere 6+) (我正在使用Tomcat 6和Websphere 6+)

The servlet spec requires objects that are stored in sessions to be fully serializable, and if you violate the spec it would be perfectly correct behaviour for the container to crash with a NotSerializableException and dismiss the entire session as invalid. servlet规范要求存储在会话中的对象可以完全序列化,如果违反规范,容器崩溃并使用NotSerializableException并将整个会话视为无效将是完全正确的行为。

Fortunately, most web containers are more forgiving and will instead keep the session in memory and merely write a warning into the log file. 幸运的是,大多数Web容器都更宽容,而是将会话保留在内存中,只是在日志文件中写入警告。 Of course, this can cause problems if you have a lot of sessions containing a lot of data. 当然,如果你有很多包含大量数据的会话,这可能会导致问题。

Serialization saves the entire object graph*. 序列化保存整个对象图*。 When your complex object goes in the session the whole thing gets stored. 当您的复杂对象进入会话时,整个事物都会被存储。 If you want to use clustering then all the objects that are part of your complex object must be Serializable, because at that point your object is getting written to a store that can be accessed by other nodes in the cluster. 如果要使用群集,那么属于复杂对象的所有对象必须是可序列化的,因为此时您的对象将被写入可由群集中的其他节点访问的存储。

EDIT: should've added that being static and transient fields don't get serialized, of course. 编辑:当然,应该补充一点,静态和瞬态字段不会被序列化。 I try not to include static mutable fields in stuff that needs to be serialized. 我尽量不在需要序列化的东西中包含静态可变字段。

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

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