[JAVA] Object registered in session must be Serializable

Serializable objects are registered in session!

Since the implementation is over, a code error was pointed out when I analyzed it with SonarLint

HogeData data = new HogeData();
//Abbreviation(Fill data with value)
session.setAttribute("KEY", data); 

There is a wavy line in the data part of setAttribute. The contents of the indication are as follows.

Make “HogeData” serializable or don’t store it in the session.

I didn't notice it because the app is working fine, but it's a bug: beetle: so I'll remove it!

Cause

Quoted from "Object to be registered in session must be Serializable"

A session is a convenient "container" that can save objects across screen transitions, but since it basically allocates a part of the memory area and uses it, (1) when the allocated area becomes full, or (2) When the servlet container is stopped, the saved object on the session is temporarily written to Disk and saved. The disk writing process for such objects is called serialization. Not all objects can be serialized in Java, only classes that implement java.io.Serializable.

If you save an object that doesn't implement Serializable in a session, it should be fine at first, but it causes trouble when serialization is required. (Usually you will get an exception called NotSerializableException.) This problem is difficult to find in transient tests in the development environment, and it is often first discovered in the form of trouble during continuous operation in the production environment, so great care should be taken.

It seems that serialization is essential when storing an Object in HttpSession. TestData was pointed out because it didn't implement Serializable.

Solution

As SonarLint pointed out, I implemented Serializable in the TestData class.


import java.io.Serializable;

public class HogeData implements Serializable  {
    private String AAA;
    private String BBB;
    //Abbreviation
}

Reference page

The Object registered in the session must be Serializable About Tomcat session persistence

Recommended Posts

Object registered in session must be Serializable
Value object in 3 minutes
[rails] Problems that cannot be registered / logged in with devise