Why some times tutorials make beans implement Serializable object and others do not? I know that object should be serialized when I want to send it through a network, so does that prove that each bean used in sessions should implements Serializable objects and beans defined in JSP pages should not since they are not transferred using HTTP requeset
2 Answers
I know that object should be serialized when I want to send it through a network, so does that prove that each bean used in sessions should implements Serializable
You seem to believe that objects in a session are sent to the client in the http transfer? That's certainly not the case. What is tranferred is only the session id (typically in a cookie). The servlet container (eg Tomcat) just keeps in memory the session objects (beans or not), indexed by the session id.
Besides, serialization does not only apply to network transfer, it also applies to save/load to persistent storage (eg disk).
Now, many servlet containers usually allow (depending on the settings) to persist the Session objects to disk so they can survive a app-server restart. For that scenario, to have your session objects serializable is a must.
Anyway, implementing the Serializable interface is a nice thing to have for every java bean, and usually it's easy.

- 73,180
- 20
- 142
- 190
-
Maaaaaaaaaaaaaaaaany thanx for this useful information. I didn't know that session Id is the only thing that transfer using HTTP protocol. – palAlaa Feb 06 '11 at 04:29
By definition, a well-formed Java Bean implements Serializable
(which is just a tag interface anyway) or Externalizable
(since 1.4) So if your bean class doesn't, it's not well-formed.
However, there's so much that does implement Serializable you can often get away with it if the bean has a well-known parent class.

- 110,348
- 25
- 193
- 263
-
I think SUN developers have another reasonable reason to make bean implements Seriablizable! – palAlaa Feb 06 '11 at 04:23
-
@Alla, I was a Sun Java Architect for 10 years. BY DEFINITION a Bean must implement serializable, because beans are supposed to be able to be maintained persistently. Long ago I wrote a Java editor in which you could drag and drop bears from jar files during run time, using that trick and introspection. – Charlie Martin Feb 06 '11 at 04:28
-
I'm quite sure that the Java Beans spec does not require that beans be serialisable (although it manages not to actually define what a bean is). IIRC, the Servlet spec requires objects stored in the session to be serialisable. – Tom Hawtin - tackline Feb 06 '11 at 15:17
-
Then you're (a) wrong and (b) not following the links; try again. Or refer to Chapter 5 of the spec. http://cds-esd.sun.com/ESD4/JSCDL/javabeans/1.01/beans.101.pdf?AuthParam=1297012320_6b7e68830f8ba96a1e15aa954616a66b&TicketId=B/w3lRqESFtOQRxHPFNSkwLq&GroupName=CDS&FilePath=/ESD4/JSCDL/javabeans/1.01/beans.101.pdf&File=beans.101.pdf – Charlie Martin Feb 06 '11 at 17:13