Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.NotSerializableException when @ViewScoped is used

If I use @ViewScoped in JSF, then the following exception occurs:

java.io.NotSerializableException: com.solv.basics.Basics
    java.io.ObjectOutputStream.writeObject0(Unknown Source)
    java.io.ObjectOutputStream.writeObject(Unknown Source)
    java.util.HashMap.writeObject(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
    java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)

I can solve it by letting the bean implement Serializable. However, I do not understand the reasoning. Why does this exception only occur for the view scope and not the other scopes?

like image 295
vijaya kumar Avatar asked Sep 25 '13 04:09

vijaya kumar


2 Answers

You didn't provide the settings from web.xml, but if the javax.faces.STATE_SAVING_METHOD is set to client, the view is always serialized, so the NotSerializableException will always occur.

You should always make your JSF beans serializable, because application server may want to serialize the session, so all session-scoped and view-scoped beans, even if state saving is set to server.

But if the server isn't serializing your session, you won't get that error on session scoped beans. But if view is serialized on client, it means that all view scoped beans are serialized to string that is sent as hidden field with all requests, and the JSF engine is detecting that your beans are not serializable.

NotSerializableException occurs only when the server tries to actually serialize your beans!

like image 89
Danubian Sailor Avatar answered Nov 15 '22 03:11

Danubian Sailor


You have to implement Serialization in you bean

public MyJSFBean implements Serializable{
//Bean coding
}

In @ViewScoped bean it is required because the screen data is valid for view not for just one request. In case of @SessionScoped bean data is stored in the session which takes care of serialization of data

like image 21
SXV Avatar answered Nov 15 '22 04:11

SXV