How can I disable serialization in Wicket 1.5?

前端 未结 5 452
一生所求
一生所求 2021-01-03 00:50

I want to turn off serialization in my Wicket app and store all page/session information in RAM. My application has a very small number of users (generally 1); I do not need

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 00:51

    I can't comment about anything specific to Wicket, but speaking generally the entire point of an Http Session is to store Serializable state between requests (and in clustered environments, to allow that state to be replicated to multiple nodes in the cluster to provide redundancy in the event of a node failure). Putting something that is not Serializable into it is generally considered an error, as shown by your stack trace. I'd be somewhat surprised if there is any sort of configuration option that would change this (though perhaps there is; as I said I can't really comment on the Wicket side of things).

    A simple alternative, if you do not require true persistence and if the data is not exceptionally large/complex, is to just use hidden form fields on your page to keep track of the relevant state.

    But if what you want is an in-memory cache, why not implement your own? It's simple enough to do:

    public class SessionCache {
        private static final Map> CACHE = Collections.synchronizedMap(new HashMap>());
    
        public static Object getAttribute(String sessionId, String attribName) {
            Map attribs = CACHE.get(sessionId);
            if (attribs != null) {
                synchronized(attribs) {
                    return attribs.get(attribName);
                }
            }
    
            return null;
        }
    
        public static void setAttribute(String sessionId, String attribName, Object attribValue) {
            Map attribs = CACHE.get(sessionId);
            if (attribs == null) {
                attribs = new HashMap();
                CACHE.put(sessionId, attribs);
            }
    
            synchronized(attribs) {
                attribs.put(attribName, attribValue);
            }
        }
    
        public static void destroySession(String sessionId) {
            CACHE.remove(sessionId);
        }
    
        public static void createSession(String sessionId, boolean force) {
            if (force || ! CACHE.containsKey(sessionId)) {
                CACHE.put(sessionId, new HashMap());
            }
        }
    }
    

    Note that you'll want to hook that into Wicket's session lifecycle so that old sessions are removed when they expire. Otherwise you'll have a gradual memory leak on your hands. From the docs it looks like you can accomplish this using registerUnboundListener() on the HttpSessionStore class.

提交回复
热议问题