[英]How can my webapp recognize a JAR from Tomcat libs
I'm currently developing a java webapp that sends emails. 我目前正在开发一个发送电子邮件的Java Web应用程序。 Since I'm deploying it on Tomcat 7 I configured the Resource
mail/Session
on my context.xml
file and copied the latest version of mail.jar
to Tomcat's lib folder. 由于我将其部署在Tomcat 7上,因此我在
context.xml
文件中配置了资源mail/Session
,并将最新版本的mail.jar
复制到Tomcat的lib文件夹中。
When I deploy my web app and run it I get the following exception: 部署并运行Web应用程序时,出现以下异常:
java.lang.ClassCastException: javax.mail.Session cannot be cast to javax.mail.Session
This is the code I'm using to send the email on my class: 这是我用来在课堂上发送电子邮件的代码:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress toIA[] = new InternetAddress[1];
toIA[0] = new InternetAddress(to);
message.setRecipients(Message.RecipientType.TO, toIA);
message.setSubject(subject);
message.setContent(mensagem, "text/plain");
Transport.send(message);
I understand that this is probably being thrown because I have the mail.jar
both in Tomcat lib folder and in my web app lib folder, the problem is that I can't simply remove the dependency from Maven's pom.xml
, because if I do so, Eclipse says that it can't find certain classes (such as Session
). 我知道这可能是因为我在Tomcat lib文件夹和Web应用程序lib文件夹中都有
mail.jar
引发的,问题是我不能简单地从Maven的pom.xml
删除依赖项,因为如果这样做因此,Eclipse表示找不到某些类(例如Session
)。
How can I use the classes responsible for sending an email if I can't have the corresponding JAR in my webapp? 如果我的Web应用程序中没有相应的JAR,如何使用负责发送电子邮件的类?
Mark scope of the specific dependency as provided
in pom.xml
: 标记
pom.xml
provided
的特定依赖项的范围:
<scope>provided</scope>
provided
提供
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime .
这很像编译,但是表明您希望JDK或容器在运行时提供依赖项 。 For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes.
例如,在为Java Enterprise Edition构建Web应用程序时,您将对Servlet API和相关Java EE API的依赖关系设置为提供的范围,因为Web容器提供了这些类。 This scope is only available on the compilation and test classpath, and is not transitive.
该作用域仅在编译和测试类路径上可用,并且不可传递。
Such a dependency won't be packaged along with your application on export because it is assumed that the container where the app will be deployed provides it. 在导出时,此类依赖项不会与您的应用程序打包在一起,因为假定要在其中部署应用程序的容器会提供它。 There is more information in the official documentation .
官方文档中有更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.