2014-05-24 166 views
3

我使用下面的方法來獲取從WAR文件中的資源WildFly獲得資源:WildFly - 從戰爭

this.getClass().getResource(relativePath) 

當應用程序部署爲展開WAR它的工作原理。 它以前也用壓縮WAR工作。昨天,我在Eclipse中做了一個乾淨的項目重建,並且它停止了工作。

當我檢查資源根:

logger.info(this.getClass().getResource("/").toExternalForm()); 

我得到這個:

file:/C:/JBoss/wildfly8.1.0.CR1/modules/system/layers/base/org/jboss/as/ejb3/main/timers/ 

原來如此,難怪這是行不通的。它可能與JBoss模塊加載有關,但我不知道這是一個錯誤還是正常行爲。

我在StackOverflow上發現了各種類似的問題,但沒有適用的解決方案。其中一個建議是使用ServletContext中,像這樣:

@Resource 
private WebServiceContext wsContext; 
... 
ServletContext servletContext = (ServletContext)this.wsContext.getMessageContext() 
     .get(MessageContext.SERVLET_CONTEXT); 
servletContext.getResource(resourcePath); 

但是,當我試圖獲得MessageContext中以這種方式,我得到一個IllegalStateException。所以我基本卡住了。有任何想法嗎?

+0

? – UVM

+0

從JAX-RS Web服務中的@GET方法。 –

+0

更具體地說,從**無狀態** JAX-RS Web服務中的@GET方法。 –

回答

1

我終於放棄了,並把我的資源文件放在一個新的JBoss模塊中,如此鏈接所述。

https://community.jboss.org/wiki/HowToPutAnExternalFileInTheClasspath

它的工作原理,但不足之處是有兩個部署目標這樣的事情比較複雜。有利的是,WAR文件的大小會減少,如果只有部分資源發生變化,我不必重新部署應用程序。

2

我們遇到了類似的問題,我們的錯誤是我們試圖通過原始路徑訪問靜態資源,而不是使用資源提供的輸入流 - 即使部署非爆炸的代碼,以下代碼也適用於我們。戰爭文件。

final URL resource = this.getClass().getResource(FILE); 

try (final InputStream inputStream = resource.openStream(); 
    final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
    final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { 
    // Use bufferedReader to read the content 
} catch (IOException e) { 
    // ... 
} 
+0

謝謝。我現在沒有時間檢查它,但也許它會幫助其他人。 –

+0

這個certianly爲我工作。謝謝! –

2

我碰到了同樣的問題,而非定義資源作爲共享模塊,我結束了在我的抗戰使用ServletContextListener來解決此工作。

在contextInitialized方法中,我從ServletContextEvent中獲取了ServletContext,並使用它的getResource(「/ WEB-INF/myResource」)來獲取我的WAR文件中的資源的URL。看起來,在ServletContextListener中,.getResource()方法按預期方式解析,而不是解析爲「/ modules/system/layers/base/org/jboss/as/ejb3/main/timers /」url。然後,該URL可以存儲在ServletContext中供以後使用,或者注入ApplicationScoped CDI bean。

@WebListener 
public class ServletInitializer implements ServletContextListener { 

    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     try { 
      final ServletContext context = sce.getServletContext(); 
      final URL resourceUrl = context.getResource("/WEB-INF/myResource"); 
      context.setAttribute("myResourceURL", resourceUrl); 
     } catch (final MalformedURLException e) { 
      throw new AssertionError("Resource not available in WAR file", e); 
     } 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) {} 
} 

@WebListener 
public class ServletInitializer implements ServletContextListener { 

    @Inject 
    private SomeApplicationScopedBean myBean; 

    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     try { 
      final ServletContext context = sce.getServletContext(); 
      final URL resourceUrl = context.getResource("/WEB-INF/myResource"); 
      myBean.setResourceUrl(resourceUrl); 
     } catch (final MalformedURLException e) { 
      throw new AssertionError("Resource not available in WAR file", e); 
     } 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) {} 
} 
0

最近,我試圖找出如何在Java中我自己的戰爭中訪問一個文件。以下是如何將java類和資源打包在war文件中:

WAR 
`-- WEB-INF 
     `-- classes (where all the java classes are) 
     `-- resourcefiles 
        `-- resourceFile1 

我的目標文件是resourceFile1。要獲取該文件,我只是做代碼如下:

InputStream inStream = this.class.getClassLoader().getResourceAsStream("resourcefiles/resourceFile1"); 

在這種情況下,資源文件將需要在同一文件夾作爲包含Java類的類文件夾。希望別人覺得這很有幫助。

0

此示例代碼適用於在openshift上部署和測試的wildfly。 我認爲這是一個野蠻的問題我低地野蠻,並試圖在本地我也得到錯誤。 例如:我在下面的鏈接嘗試了示例代碼,它適用於tomcat,但不適用於wildfly。 http://websystique.com/springmvc/spring-mvc-4-file-download-example/ 來自哪裏,你試圖訪問這個代碼把你的文件下的資源/文件

import org.springframework.web.bind.annotation.RequestMethod;  
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URLConnection; 

@Controller 
@RequestMapping 
public class FileDownloadController { 

    private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class); 

    private static final String DOC_FILE = "file/ibrahim-karayel.docx"; 
    private static final String PDF_FILE = "file/ibrahim-karayel.pdf"; 


    @RequestMapping(value = "/download/{type}", method = RequestMethod.GET) 
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, 
          @PathVariable("type") String type) throws IOException { 

     File file = null; 
     InputStream inputStream; 
     if (type.equalsIgnoreCase("doc")) { 
      inputStream = getClass().getClassLoader().getResourceAsStream(DOC_FILE); 
      file = new File(Thread.currentThread().getContextClassLoader().getResource(DOC_FILE).getFile()); 
     } else if (type.equalsIgnoreCase("pdf")) { 
      inputStream = getClass().getClassLoader().getResourceAsStream(PDF_FILE); 
      file = new File(Thread.currentThread().getContextClassLoader().getResource(PDF_FILE).getFile()); 
     } else{ 
      throw new FileNotFoundException(); 
     } 
     if (file == null && file.getName() == null) { 
      logger.error("File Not Found -> " + file); 
      throw new FileNotFoundException(); 
     } 

     String mimeType = URLConnection.guessContentTypeFromName(file.getName()); 
     if (mimeType == null) { 
      System.out.println("mimetype is not detectable, will take default"); 
      mimeType = "application/octet-stream"; 
     } 

     System.out.println("mimetype : " + mimeType); 
     response.setContentType(mimeType); 
     /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
      while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ 
     response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\"")); 

     /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ 
     //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); 

     response.setContentLength(inputStream.available()); 
     IOUtils.copy(inputStream, response.getOutputStream()); 
     response.flushBuffer(); 
     inputStream.close(); 
    } 
}