как получить относительный путь к ресурсу в проекте j2ee

У меня есть динамический веб-проект с плоским файлом (или, скажем, текстовым файлом). Я создал сервлет, в котором мне нужно использовать этот файл.

Мой код выглядит следующим образом:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

   // String resource = request.getParameter ("json") ;
             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 = is.read (  ) ; c != -1; c = is.read (  )  )   {
                         sw.write ( c ) ;
                     }
                    PrintWriter out = response.getWriter();
                    out.print (sw.toString ()) ;
                    out.flush();
                 }
          }

}

Проблема в том, что InputStream is имеет нулевое значение.

Я не уверен, как получить правильный относительный путь. Я использую JBOSS в качестве сервера приложений.

Я добавил файл ресурсов в каталог WebContent динамического веб-проекта. В качестве другого подхода я попробовал это:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        ServletConfig config = getServletConfig();
        String contextName = config.getInitParameter("ApplicationName");
        System.out.println("context name"+ contextName);
        String contextPath = config.getServletContext().getRealPath(contextName);
        System.out.println("context Path"+contextPath);
        //contextPath = contextPath.substring(0, contextPath.indexOf(contextName));
        contextPath += "\\rateJSON.txt";
        System.out.println(contextPath);

    String resource = request.getParameter ("json") ;
    System.out.println("Hi there1"+resource);
             if  ( resource != null && !resource.equals ( "" )  )   {
                 System.out.println("Hi there");
                //use getResourceAsStream (  )  to properly get the file.
                //InputStream is = getServletContext ().getResourceAsStream (resource) ;
                InputStream is = getServletConfig().getServletContext().getResourceAsStream(contextPath);


                if  ( is != null )   {  // the resource exists
                    System.out.println("Hi there2");
                     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 = is.read (  ) ; c != -1; c = is.read (  )  )   {
                         sw.write ( c ) ;
                         System.out.println(c);
                     }
                    PrintWriter out = response.getWriter();
                    out.print (sw.toString ()) ;
                    System.out.println(sw.toString());
                    out.flush();
                 }
          }
  }

Теперь значение contextPath: C:\JBOSS\jboss-5.0.1.GA\server\default\tmp\4p72206b-uo5r7k-g0vn9pof-1-g0vsh0o9-b7\Nationwide.war\WEB-INF\rateJSON

Но в этом месте нет файла rateJSON? Кажется, JBOSS не помещает этот файл в App.war или не развертывает его??? Может ли кто-нибудь помочь мне?


person Neeraj    schedule 17.10.2009    source источник


Ответы (2)


Во-первых, проверьте Nationwide.war, чтобы убедиться, что файл rateJSON.txt включен. Если да, то попробуйте:

String rootPath = getServletConfig().getServletContext().getRealPath("/");
File file = new File(realPath + "WEB-INF/rateJSON.txt");
InputStream is = new FileInputStream(file);
person Kaleb Brasee    schedule 17.10.2009
comment
в Nationwide.war файла rateJSON нет. Зачем?? - person Neeraj; 17.10.2009
comment
По какой-то причине все, что упаковывает WAR, не включает этот файл. Используете ли вы сценарий Ant для создания WAR или выполняете автоматическое развертывание на сервере в своей среде IDE? - person Kaleb Brasee; 17.10.2009
comment
автоматическое развертывание на сервере - person Neeraj; 17.10.2009

Я думаю, что этот (getServletContext().getRealPath()) находится в документы...

Этот метод возвращает значение null, если контейнер сервлета по какой-либо причине не может преобразовать виртуальный путь в реальный путь (например, когда содержимое становится доступным из архива .war).

person ian_scho    schedule 24.03.2011