2
\$\begingroup\$

Below is my code to maintain a session timeout globally in Java spring configuration and to load the session timeout value from a properties file. Do you have any suggestions to improve my code?

public class MySessionListener implements HttpSessionListener {
    @Override
        public void sessionCreated(HttpSessionEvent event) {
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                InputStream stream = classLoader.getResourceAsStream("bimspring.properties");
                Properties properties = new Properties();
                properties.load(stream);
                String sessionTimeout = properties.getProperty("cookieName", "No Value Found");
                event.getSession().setMaxInactiveInterval(Integer.parseInt(sessionTimeout));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void sessionDestroyed(HttpSessionEvent event) {

        }

    }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Quite a number of points for this short piece of code:

  • As the properties file will probably not change at runtime, loading it every single time a session gets created is a total waste. See whether you can cache the session timeout in a static variable.
  • If the value is not set, the default "no value found" will lead to a number format exception. Better use a sensible parseable default.
  • Similar context: by setting the value to a non-parseable string, you can kill the server with a misconfiguration.
  • "sessionTimeout" should not be named "cookieName"
  • Separation of concerns: a method should do one thing. This is a mixup of reading the program configuration and using the determined value to set the timeout.
  • Error handling: printStackTrace does not accomplish anything. Do something real (e.g. log an error for the server admin, shutdown, whatever.) If you decide to continue the process in case of an I/O exception, set a sensible default on the session.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.