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) {
 }
 }
Daniel
4,6122 gold badges18 silver badges40 bronze badges
asked Jun 3, 2018 at 8:09
\$\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.
answered Jun 4, 2018 at 7:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.