Search code examples
javasonarqubeserializablehttpsession

How to Fix Non-serializable objects should not be stored in "HttpSession" objects (squid:S2441)


I'm getting the Sonarqube defect

Non-serializable objects should not be stored in "HttpSession" objects (squid:S2441)

for the saving in Httpsession, code:

public static HttpSession setSessionAttribute(final HttpSession session, 
final String attributeName,
        final Object attributeValue) {
    session.setAttribute(attributeName, attributeValue);
    return session;
  }

Solution

  • All your objects that you are adding as attribute to HttpSession has to be Serializable (so that the session with be Serializable),

    SonarQube search for every setAttribute on HttpSession that object is primitive or implements Serializable, Code:

    if (!type.isPrimitive() && !type.isSubtypeOf("java.io.Serializable")) { 
          addIssue(argument, "Make \"" + type + "\" serializable or don't store it in the session."); 
        } 
    

    There's also an issue reported and should be fixed in version 4.2 with handling arrays.

    If you can fix your code, change attributeValue to Serializable

    public static HttpSession setSessionAttribute(final HttpSession session, 
    final String attributeName,
            final Serializable attributeValue) {
        session.setAttribute(attributeName, attributeValue);
        return session;
      }