Cant retrieve an images from the WEB-INF folder ussing classLoader.getResourceAsStream()

淺唱寂寞╮ 提交于 2019-12-01 05:47:25

问题


The hold noon i was trying to make my app send both html+images via javamail, i only managed to send html, but with the image i am having a bit of problems. I decided to create a multipart message, and all was going ok, but then i use the class loader to retrieve the .png file from the WEB-INF/resources/images i get a NullPointerExcetion, i dont know why is that?

Here is how my EJB(3.0) looks like. Ill appreciate a hand on this one i dont have much experience with the ClassLoader class(Dont know much about it).

@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);
    }

}

I would like to mention that i am ussing JEE6 with glassfishV3 i dont know if my approach is compatible with this application server.


Update When i modify the above code to

String fileName = "logoemailtemplate.png";

I receive an email, it works.

But now I don't receive the text. :) Is there any mistake?


回答1:


I think you're confusing ClassLoader#getResourceAsStream() with ServletContext#getResourceAsStream(). The former only loads resources from the classpath while the later only loads resources from the webcontent (there where your /WEB-INF folder also is).

You need to put those resources in the classpath. If you're using an IDE, then most straightforward way is to just drop them in any package in the Java source folder. It'll end up in /WEB-INF/classes after build, which is part of the classpath.

Lets assume that you've a package com.example.resources.images and you've dropped logoemailtemplate.png file in there, then you can load it by the following fileName.

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

An alternative is to add /WEB-INF/resources folder to the classpath. In an IDE like Eclipse, you can do that by adding it as Source folder in project's build path. Then you can load it by the following fileName.

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

This is however not the common practice.




回答2:


As far as I know the classLoader can only access WEB-INF/classes and WEB-INF/lib but not WEB-INF/resources. Try to put the file in the classes sub-folder.




回答3:


You must use ServletContext.getResourceAsStream() to load a file from a war. ClassLoader.getResourceAsStream loads a class from the classpath.



来源:https://stackoverflow.com/questions/5250704/cant-retrieve-an-images-from-the-web-inf-folder-ussing-classloader-getresourceas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!