无法通过classLoader.getResourceAsStream()从WEB-INF文件夹中检索图像

中午我试图让我的应用程序通过javamail发送html +图像,我只设法发送html,但与图像我有一些问题。 我决定创建一个多部分消息,一切顺利,但后来我使用类加载器从WEB-INF / resources / images检索.png文件我得到一个NullPointerExcetion,我不知道为什么会这样?

这是我的EJB(3.0)的样子。 我很欣赏这一个我没有太多经验的ClassLoader类(不太了解它)。

@Stateless(name = "ejbs/EmailServiceEJB") public class EmailServiceEJB implements IEmailServiceEJB { @Resource(name = "mail/myMailSession") private Session mailSession; public void sendAccountActivationLinkToBuyer(String destinationEmail, String name) { // Destination of the email String to = destinationEmail; String from = "dontreply2thismessage@gmail.com"; try { Message message = new MimeMessage(mailSession); // From: is our service message.setFrom(new InternetAddress(from)); // To: destination given message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("Uspijesna registracija"); // How to found at http://www.rgagnon.com/javadetails/java-0321.html message.setContent(generateActivationLinkTemplate(), "text/html"); Date timeStamp = new Date(); message.setSentDate(timeStamp); // Prepare a multipart HTML Multipart multipart = new MimeMultipart(); // Prepare the HTML BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(generateActivationLinkTemplate(), "text/html"); multipart.addBodyPart(htmlPart); // PREPARE THE IMAGE BodyPart imgPart = new MimeBodyPart(); String fileName = "/WEB-INF/resources/images/logoemailtemplate.png"; ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); if (classLoader == null) { classLoader = this.getClass().getClassLoader(); if (classLoader == null) { System.out.println("IT IS NULL AGAIN!!!!"); } } DataSource ds = new URLDataSource(classLoader.getResource(fileName)); imgPart.setDataHandler(new DataHandler(ds)); imgPart.setHeader("Content-ID", "the-img-1"); multipart.addBodyPart(imgPart); // Set the message content! message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } 

我想提一下,我正在使用glassfishV3进行JEE6,我不知道我的方法是否与此应用程序服务器兼容。


更新当我修改上面的代码时

 String fileName = "logoemailtemplate.png"; 

我收到一封电子邮件,它有效。

但现在我没有收到文字。 :)有什么错吗?

我认为你将ClassLoader#getResourceAsStream()ServletContext#getResourceAsStream()混淆。 前者仅从类路径加载资源,而后者仅从webcontent加载资源(您的/WEB-INF文件夹也在那里)。

您需要将这些资源放在类路径中。 如果您使用的是IDE,那么最简单的方法就是将它们放入Java源文件夹中的任何包中。 它将在构建之后进入/WEB-INF/classes ,这是类路径的一部分。

让我们假设您有一个包com.example.resources.images并且您已经在其中删除了logoemailtemplate.png文件,然后您可以通过以下fileName加载它。

 String fileName = "/com/example/resources/images/logoemailtemplate.png"; 

另一种方法是将/WEB-INF/resources文件夹添加到类路径中。 在像Eclipse这样的IDE中,您可以通过在项目的构建路径中将其添加为Source文件夹来实现。 然后,您可以通过以下fileName加载它。

 String fileName = "/images/logoemailtemplate.png"; 

然而,这不是常见做法。

据我所知,classLoader只能访问WEB-INF / classes和WEB-INF / lib,但不能访问WEB-INF /资源。 尝试将该文件放在classes子文件夹中。

您必须使用ServletContext.getResourceAsStream()从war加载文件。 ClassLoader.getResourceAsStream从类路径加载一个类。