2009-10-17 3 views
0

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

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

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

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 \ сервер \ умолчанию \ TMP \ 4p72206b-uo5r7k-g0vn9pof-1 -g0vsh0o9-b7 \ Nationwide.war \ WEB-INF \ rateJSON

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

ответ

2

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

String rootPath = getServletConfig().getServletContext().getRealPath("/"); 
File file = new File(realPath + "WEB-INF/rateJSON.txt"); 
InputStream is = new FileInputStream(file); 
+0

в Nationwide.war файла "rateJSON" нет. Зачем?? – Neeraj

+0

По какой-то причине, что бы упаковывать, WAR не включает этот файл. Используете ли вы скрипт Ant для создания WAR или автоматически развертываете сервер на своей среде IDE? –

+0

автоматическое развертывание на сервере – Neeraj

1

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

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