how to obtain the relative path of a resource in a j2ee project?


EJB design: how to obtain the relative path of a resource in a j2ee project?

  1. I have a Dynamic Web Project having a flat file (or say text file). I have created a servlet in which I need to use this file. My code is as following: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ( resource != null && !resource.equals ( "" ) ) { //use getResourceAsStream ( ) to properly get the file. InputStream is = getServletContext ().getResourceAsStream ("rateJSON") ; \if ( is != null ) { // the resource exists response.setContentType("application/json"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); StringWriter sw = new StringWriter ( ) ; for(int c =; c != -1; c = )) { sw.write ( c ) ; } PrintWriter out = response.getWriter(); out.print (sw.toString ()) ; out.flush(); } } The problem is that the InputStream is has null value. I'm not sure how to get the correct path? I'm using JBOSS as the app server.
  2. If you have a look at the API you can read: getResourceAsStream: Returns the resource located at the named path as an InputStream object. The data in the InputStream can be of any type or length. The path must be specified according to the rules given in getResource. This method returns null if no resource exists at the specified path. getResource: Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root. might be asking yourself what's the context root? it is the root of your web app folder (or archive) so if you put "file.ext" in WEB-INF then you have to use "/WEB-INF/file.ext" Hope this helps