java.io.NotSerializableException when @ViewScoped is used
Asked Answered
D

2

5

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?

Dominique answered 25/9, 2013 at 4:18 Comment(0)
C
6

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!

Constringe answered 25/9, 2013 at 8:9 Comment(3)
There's actually one more reason and it's this one which makes MyFaces somewhat different from Mojarra. If you find out this, you get a vote.Fleabane
@BalusC: Is it the notion of shallow & deep copy, difference being Mojarra does not serialize the state in the session with JSF storing only pointers to that specific state in a session.Horal
@Shirgill: you have asked about this already :) https://mcmap.net/q/2035222/-server-state-serialization-in-a-session-in-mojarraFleabane
M
1

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

Mazdaism answered 25/9, 2013 at 7:7 Comment(1)
Two same answers have been provided yet.Arenas

© 2022 - 2024 — McMap. All rights reserved.