Announcement Announcement Module
Collapse
No announcement yet.
holding on to ServletContext and using getRealPath() Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • holding on to ServletContext and using getRealPath()

    My web application holds a reference to ServletContext and frequently uses servletContext.getRealPath(uri). I haven't noticed any bad side effects, but I wonder if this would work in all circumstances and on all application servers/servlet engines. (I've only tried it on Tomcat.)

    Are there circumstances when the ServletContext would be refreshed and I'd be holding a stale context? Are there platforms where getRealPath(uri) wouldn't give the expected result, and if so, is there something else I could use instead to locate files?

    I'm aware, by the way, that AbstractController has a getServletContext(), but I don't want to rely on subclassing AbstractController. I also haven't seen how to get the ServletContext from WebApplicationContextUtils. What I've done so far is to subclass ContextLoaderListener and then simply set the ServletContext into a static variable, as shown here:

    ServletContextHolder.servletContext = servletContextEvent.getServletContext();

  • #2
    I don't think there is anything wrong with holding the ServletContext although I disagree with your need to do so. "You're doing it wrong ..." sort of a thing.

    You should really implement the ServletContextListener just in case the container reloads the context for whatever reason. A stale copy might hold older data which may cause your app to behave unpredictably.

    Comment


    • #3
      holding on to ServletContext and using getRealPath()

      ServletContextListener! Much better.

      Now, what about servletContext.getRealPath()? Is that safe on all platforms? If not, are there any workarounds?

      Comment


      • #4
        I don't know about all platforms but it works on pretty much all versions of tomcat. I do remember running into problems using jboss though. You might have to go through a few bugzilla's and jira's to dig up it's true safety.

        Comment

        Working...
        X