Search code examples
javaservletshttpsession

Deprecation warning while implement HttpSession


While I'm trying to implement HttpSession, I should override getSessionContext method. But it casues deprecated warnings because the method and its return type HttpSessionContext is deprecated.

@deprecated javadoc tag fixes a warning on the definition of getSessionContext but cannot fix a warning on the import of HttpSessionContext. And putting @SuppressWarnings before the import causes a compile error.

How can I fix both of the warnings?

Code:

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

public class MyServletSession implements HttpSession {
    // ...

    /**
     * @deprecated
     */
    @Override
    public HttpSessionContext getSessionContext() {
        throw new UnsupportedOperationException();
    }

    // ...
}

Warning:

$ javac -Xlint:deprecation -cp /path/to/javax.servlet-api-3.0.1.jar MyServletSession.java
MyServletSession.java:5: warning: [deprecation] HttpSessionContext in javax.servlet.http has been deprecated
import javax.servlet.http.HttpSessionContext;
                                     ^
1 warning

Solution

  • If you really need to implement your own HttpSession, and suppress the deprecation warnings, I believe the correct compiler argument is -Xlint:-deprecation. Notice the - before deprecation

    Edit: This remove all deprecation warnings, so it might not be suitable if you're trying to suppress only the warnings in that one class. Instead, I found this to work for me:

    // Note, no import of javax.servlet.http.HttpSessionContext
    import javax.servlet.http.HttpSession;
    
    @SuppressWarnings("deprecation")
    public class MySession implements HttpSession {
    
        /**
         * This javadoc comment, along with the fully qualified name of HttpSessionContex in the method signature seems to do the trick.
         * @deprecated
         */
        public javax.servlet.http.HttpSessionContext getSessionContext() {
        }
    
        //... All your other methods
    }