The javax.mail.Session object represents the session. It provides access to protocol implementations.
There are two alternative methods for obtaining a session object:
● Using resource injection
This approach has been available since Java EE 5. It requires you to annotate the Session object as a resource with the corresponding alias. The system will locate the respective resource.
This method is not applicable to JSP pages.
● Using JNDI resource location
This is the classical approach. You can use it in all types of components.
Declare the Session object in the source code and add the @Resource annotation before it. In the name argument of the annotation, set the resource name.
@Resource(name="mail/MailSession") private javax.mail.Session session; |
...
1. In the source code, look up the object using the javax.naming.InitialContext.
InitialContext ctx = new InitialContext(); Session ses = (Session)ctx.lookup("java:comp/env/mail/MailSession"); |
2. Add the respective resource description in the web.xml, or ejb-jar.xml (depending on whetheryou are using the session object inside servlet/JSP, or EJB respectively).
<resource-ref> <res-ref-name>mail/MailSession</res-ref-name> <res-type>javax.mail.Session</res-type> <res-auth>Container</res-auth> </resource-ref> |