-1

I need access to the ServletContext to use the getRealPath() method on some files that are in my WEB-INF directory. However, the class I need to do this work in is a non-CDI class that is used for some backend processing based on a request made earlier from JAX-RS. How can I get the ServletContext outside of the lifecycle of the JAX-RS request?

I'm using Wildfly 10, if that changes the way I would go about this

seanr8
  • 411
  • 1
  • 5
  • 15
  • What do you mean for backend processing? Ejb? – empyros Sep 25 '17 at 14:23
  • I honestly don't know. This is pretty new to me. The request goes into a queue to be processed by a separate thread later and the REST call just returns 200 to say it'll be in the queue. But I need the ServletContext on the other thread, after the REST call has returned, to perform the operation scheduled from the request on a file inside the WAR's WEB-INF. But since it's on a separate thread and the JAX-RS call has already returned, the ServletContext, even though it was put in the queue as well, is now null. – seanr8 Sep 25 '17 at 17:20
  • `getRealPath()` is unportable and you must not use it. See this [answer](https://stackoverflow.com/a/12160863/1426227). – cassiomolin Sep 26 '17 at 09:34

1 Answers1

0

The trick is to load a servlet at the startup of the Java EE application, see @WebServlet annotation. The Servlet.init() method is invoked upon startup of the container, which we will leverage to work with ServletContext, in this case calling getRealPath() and storing returned value into static variable. You may access the value from the rest of your app by calling RealPathServlet.getRealPath().

@WebServlet(value="/real-path", loadOnStartup=1)
public class RealPathServlet extends HttpServlet {

    private static String realPath;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        realPath = config.getServletContext().getRealPath("yolo");
        Logger.getLogger(ContextPathServlet.class.getName()).info("Real path is " + realPath);
    }

    public static getRealPath() {
        return realPath;
    }

    ...
}
Mišo Stankay
  • 339
  • 1
  • 8