Я создаю сервер причала и хочу программно и динамически добавлять сервлеты.Как динамически добавлять сервлеты на причал?
протоколирования установки я и консоль затем приступить к созданию сервера следующим образом:
Connector httpConn = null;
Connector httpsConn = null;
HandlerCollection handlers = new HandlerCollection();
httpConn = new SelectChannelConnector();
httpConn.setPort(httpPort);
httpConn.setName("HTTPConnector"); // simillar setup for httpsConn if needed
contextHandlers = new ContextHandlerCollection();
if(launchServlets) {
// this is more or less the same servlet creation code as below but for launching
// static servlets (in this example, there are none)
holders = initializeServlets(configFilePath);
}
handlers.addHandler(contextHandlers);
server = new Server();
if(httpConn != null) {
server.addConnector(httpConn);
}
if(httpsConn != null) {
server.addConnector(httpsConn);
}
server.setGracefulShutdown(1000);/
server.setStopAtShutdown(true);
server.setHandler(handlers);
server.start();
if(launchServlets) {
// Catch any exception that occurs during servlet init()
// (must be called after server.start())
for(int i = 0; i < holders.length; i++) {
if(holders[ i ] != null) {
Exception initEx = holders[ i ].getUnavailableException();
if(initEx != null) {
server.stop();
throw initEx;
}
}
}
}
Так что, когда мне нужно, чтобы начать сервлет, я следующее:
boolean isSecureOnly = false; // function that decides suppressed for now
String[] connectors;
MyServlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
holder.setInitParameter(Constants.CONF_INIT_STRING_PARAM, configString);
holder.setInitParameter(Constants.CONF_INIT_NAME_PARAM, myName);
ServletContextHandler handler = new ServletContextHandler();
if(details != null) {
details.sch = handler;
}
String contextPath = MyConfig.getContextPath(myProps, myName);
handler.setContextPath(contextPath);
handler.setAllowNullPathInfo(true);
// bind the servlet to the connectors it should be listening to
if(isSsl) {
if(isSecureOnly) {
connectors = new String[ 1 ];
connectors[0] = Constants.CONF_HTTPS_CONNECTOR;
} else {
connectors = new String[ 2 ];
connectors[0] = Constants.CONF_HTTPS_CONNECTOR;
connectors[1] = Constants.CONF_HTTP_CONNECTOR;
}
} else {
if(isSecureOnly) {
throw new ConfigException(50051);
}
connectors = new String[ 1 ];
connectors[0] = Constants.CONF_HTTP_CONNECTOR;
}
handler.setConnectorNames(connectors);
if(myName != null) {
handler.setDisplayName(MyMessage.message(10025, myName));
} else {
handler.setDisplayName(MyMessage.message(10001));
}
handler.addServlet(holder, "/*");
contextHandlers.addHandler(handler);
contextHandlers.mapContexts();
Exception initEx = holder.getUnavailableException();
if(initEx != null) {
// deal with error
}
Хотя мои динамики код запуска сервлета работает без ошибок, консоль не показывает инициализацию сервлета. Когда у меня есть launchServlets = true, код статически запускает сервлеты, и все хорошо, но я хочу запустить их динамически.
Должен ли я вручную инициализировать сервлет (я думал, что сервлеты были изолированы в их собственное пространство памяти)? Как сообщить Jetty о запуске нового сервлета?
Обновление: До сих пор единственным способом, с помощью которого я смог запустить сервлет, является server.stop()/server.join()/server.start(). Я бы хотел добавить сервлеты (и удалить - но это бонусный вопрос), чтобы не прерывать обслуживание существующих сервлетов)?
Я использую Jetty-все-SERVER-8.1.3 и Servlet API 3.0
Заранее спасибо за вашу помощь/подсказки!
** Надгробный камень! ** Действительно! Я почти уверен, что большинство просмотров было моим! Люди, у которых есть вопросы о назначении CS, получают больше голосов здесь. –