现在我们来到了HttpConnector的世界里,开始了解初始化之道。剑指初始化方法initialize:
public void initialize()
throws LifecycleException {
if (initialized)
throw new LifecycleException (
sm.getString("httpConnector.alreadyInitialized"));
this.initialized=true;
Exception eRethrow = null;
// Establish a server socket on the specified port
try {
serverSocket = open();
} catch (IOException ioe) {
log("httpConnector, io problem: ", ioe);
eRethrow = ioe;
} catch (KeyStoreException kse) {
log("httpConnector, keystore problem: ", kse);
eRethrow = kse;
} catch (NoSuchAlgorithmException nsae) {
log("httpConnector, keystore algorithm problem: ", nsae);
eRethrow = nsae;
} catch (CertificateException ce) {
log("httpConnector, certificate problem: ", ce);
eRethrow = ce;
} catch (UnrecoverableKeyException uke) {
log("httpConnector, unrecoverable key: ", uke);
eRethrow = uke;
} catch (KeyManagementException kme) {
log("httpConnector, key management problem: ", kme);
eRethrow = kme;
}
if ( eRethrow != null )
throw new LifecycleException(threadName + ".open", eRethrow);
}
从源码上可以知道,其实这个方法就是调用了自身的open方法,并返回了一个ServerSocket给成员属性serverSocket而已,我们再深入了解open方法
private ServerSocketopen()
throws IOException, KeyStoreException,NoSuchAlgorithmException,
CertificateException,UnrecoverableKeyException,
KeyManagementException
{
// Acquire the server socket factoryfor this Connector
ServerSocketFactory factory =getFactory();
// If no address is specified, open aconnection on all addresses
if (address == null) {
log(sm.getString("httpConnector.allAddresses"));
try {
return(factory.createSocket(port, acceptCount));
} catch (BindException be) {
throw newBindException(be.getMessage() + ":" + port);
}
}
// Open a server socket on thespecified address
try {
InetAddress is =InetAddress.getByName(address);
log(sm.getString("httpConnector.anAddress", address));
try {
return(factory.createSocket(port, acceptCount, is));
} catch (BindException be) {
throw newBindException(be.getMessage() + ":" + address +
":" + port);
}
} catch (Exception e) {
log(sm.getString("httpConnector.noAddress", address));
try {
return(factory.createSocket(port, acceptCount));
} catch (BindException be) {
throw newBindException(be.getMessage() + ":" + port);
}
}
}
这个方法首先是获取接口ServerSocketFactory,然后再调用接口的createSocket方法。
很明显这里是采用了工厂设计模式:
1, 定义了一个抽象的工厂接口:ServerSocketFactory,在接口上定义了三个同名createSocket方法,每个方法都是返回serverSocket
2, 实现ServerSocketFactory接口的工厂目前有2个:SSLServerSocketFactory和DefaultServerSocketFactory
1, 我们从HttpConnector的getFactory()方法可以知道,这里采用了DefaultServerSocketFactory这儿实现类
至此我们的初始化工作就完成咯!我们做个小综述:
1, 当standardService将初始化动作传递给HttpConnector时,HttpConnector采用了工厂设计模式获取了抽象工厂ServerSocketFactory
2, 通过调用ServerSocketFactory工厂实现类DefaultServerSocketFactory的createSocket方法获取了ServerSocket对象,并赋值给成员变量serverSocket
流程图如下: