5

How can i read the session-timeout from the web.xml file?

Tried

getServletContext().getAttribute("session-timeout").toString(); 

but gives me NullPointerException.

Also tried

getServletConfig().getInitParameter("session-timeout");

But gives me null because obviously this is not an init-param

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125

2 Answers2

9

Here's an oneliner.

int sessionTimeoutFromWebXml = Integer.parseInt(XPathFactory.newInstance().newXPath().compile("web-app/session-config/session-timeout").evaluate(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(getServletContext().getResourceAsStream("/WEB-INF/web.xml"))));

;)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Since this code is a little involved, is there a way rather to set the value in the web.xml from a `public` `static` variable? Or to set the value from the `contextInitialized` method of the `ContextListener`? This way, I only write this value in one place. – theyuv Oct 11 '18 at 06:47
1

It should be

   session.getMaxInactiveInterval();

It will return time in seconds.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • 1
    yes, I am aware of that, but is there a way to read that property from the web.xml as is? – MaVRoSCy Jul 08 '13 at 14:12
  • Even I was wondering how can a person with such good reputation doesn't know about it ;). Well I guess we have to read whole xml file, find the session-timeout element and then check the value. I am not quite sure about it. Maybe experts over here can help both of us – Prasad Kharkar Jul 08 '13 at 14:16
  • and actually the `getMaxInactiveInterval()` returns the time in seconds – MaVRoSCy Jul 08 '13 at 14:21
  • 1
    Its a bit weird that the information is stored in minutes and all you can get back is seconds. – MaVRoSCy Jul 08 '13 at 14:29