开发者

getSession v/s getDefaultSession and

1.) What is the difference between getSession() and getDefaultSession() ? I have read the Doc but i am not开发者_如何学编程 clear what is meant by gets the default session object .

2.) In the method public static Session getDefaultInstance(Properties props, Authenticator authenticator)

what is the second argument meant for , what does it do and how does it do ?

3.) I have often come across the snippet :

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("USERNAME_HERE", "PASSWORD_HERE");
    }
});

and i have seen that the merthod overriden here is never called. What does this method do ?


From the JavaMail FAQ:

Almost all code should use Session.getInstance. The Session.getDefaultInstance method creates a new Session the first time it's called, using the Properties that are passed. Subsequent calls will return that original Session and ignore any Properties you pass in. If you want to create different Sessions with different properties, Session.getDefaultInstance won't do that. If some other code in the same JVM (e.g., in the same app server) has already created the default Session with their properties, you may end up using their Session and your properties will be ignored. This often explains why your property settings seem to be ignored. Always use Session.getInstance to avoid this problem.

The second argument is a subclass that knows how to get the username and password that should be used to login to the mail server. It also holds on to the some of the additional context that could be required by the user such as the hostname that will receive the username and password. From the javax.mail.Authenticator documentation:

The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information.

The getPasswordAuthentication method is callback with hard coded username and password. Under the hood, this method gets called when javax.mail.Service.connect() is called. One example of this is when you call public static void Transport.send(Message).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜