Beans serialization in JSP

2019-05-25 03:18发布

问题:

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

回答1:

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.



回答2:

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.