Вопросик из области Web-Programmierung, Java
-----
Угу... Будет вместо поиска решения проблемы - Один хост = Одна сессия, поиск решения - Много Сессий = Много Юзеров... и все - без идентификации, чисто по ИП, без СИДов. Удачки, как говорится...
не подскажешь?
------
Увы - ТомКат, вроде, появился после того, как Я перестал работать с Жабой...
Тогда была ВебСфера от ИБМ и что-то еще. Что - не помню - мне не до этих
моментов было - код надо было делать.
Ты лучше бы сам подумал своей головой.
------
Я и думаю - над своими задачами. Еще чуток и на твои отвлекаюсь. Могу - не отвлекаться.
В боевых условиях вместо RMI используется сервлет.
------
Ты запутал пожалуй уже всех.
У тебя при обрезке на файрволе всего, кроме 80 порта, приложение работает?
Если - НЕТ - это не заявленный веб. Что именно и когда у тебя используется - надо сидеть
и разбираться. Насколько при этом то, что ты описываешь соответствует той (а она использовалась
15 лет назад и подзабыта основательно) терминологии которой Я оперирую - тоже очень большой
вопрос. Так что есть смысл коротко описать что-есть-что и показать на минимальных примерах.
Какой еще IP у Юникса, тыачем, ау?
------
Он в Сети? К нему коннектятся по <tcp/ip> протоколу? - там без ИП не работает...
Если еще проще - веб-сервер/апп-сервер без ИП не запускается - ему требуется ИП для открытия
порта для прослушки... Ау?
Угу... Будет вместо поиска решения проблемы - Один хост = Одна сессия, поиск решения - Много Сессий = Много Юзеров... и все - без идентификации, чисто по ИП, без СИДов. Удачки, как говорится...
Ну, это ты не мне объясняй, а нашим юзерам.
Им надо в одном окне изменения делать, а в другом валидировать.
Сессий будет всего две, ничего страшного не вижу.
Я и думаю - над своими задачами. Еще чуток и на твои отвлекаюсь. Могу - не отвлекаться.
Сорри. Но ты тоже не обзывайся.
Ты запутал пожалуй уже всех.
У тебя при обрезке на файрволе всего, кроме 80 порта, приложение работает?
Понятия не имею.
Насколько при этом то, что ты описываешь соответствует той (а она использовалась
15 лет назад и подзабыта основательно) терминологии которой Я оперирую - тоже очень большой
вопрос. Так что есть смысл коротко описать что-есть-что и показать на минимальных примерах.
Ну, какие еще примеры-то нужны?
Сидят, допустим, три юзера, у каждого свой комп с виндой, ходят через браузер на одну Юникс-машину (на самом деле не на одну, а на кучу, но для простоты будем считать, что на одну).
Какой еще IP у Юникса, тыачем, ау?
------
Он в Сети? К нему коннектятся по <tcp/ip> протоколу? - там без ИП не работает...
В логе стоит мой личный IP, который я в ipconfig вижу.
Если еще проще - веб-сервер/апп-сервер без ИП не запускается - ему требуется ИП для открытия
порта для прослушки... Ау?
В науке о портах и гаванях я не силен, запускать веб-сервер - не моя забота, я его одной командой (кнопкой) запускаю, а на продукционной и прочих боевых машинах он и так всегда запущен. Мы говорим только про запуск апплета.
------
Твои юзера есть ТВОИ юзера. У меня есть МОИ юзера которым приходится обьяснять "элементарные" вещи. Обьяснять по многу раз ибо с выполняемой ими работой мои обьяснения связаны только косвенно. И вариантов у меня два - бегать за каждым юзером или сделать так, чтобы они не имели возможность что-то сломать... ну или при сломе можно было восстановить на раз-два. По этому если Я не могу различить юзеров в сессии - то будет одна сессия на комп.
Им надо в одном окне изменения делать, а в другом валидировать.
Сессий будет всего две, ничего страшного не вижу.
-----
Сессий бывает - Ноль, Одна и МНОГО. Страшного ничего не будет - ты будешь в той же позиции, что и в начале - никаких других сложностей не будет.
Сорри. Но ты тоже не обзывайся.
-----
Мне - можно - Я старый и раздражительный... и этикет у меня времен ФИДО. Он не мешает сказать оппоненту, что тот не прав.
ходят через браузер на одну Юникс-машину
Соединение с Томкатом через сервлет по IP виндокомпутера.
------
Хммм... Эквивалентно - Едя по автобану на Юг мы пешком по буеракам идем север.
В каком же направлении движение то?
В науке о портах и гаванях я не силен
------
Да, это видно. Потому тебя и тыкаю носом в несоответствия - что бы задумался и осознал. Там, если не углублятся до уровня сокетов и ниже, не сложно, но понимать что и как, хотя бы схематично - надо.
запускать веб-сервер - не моя забота, я его одной командой (кнопкой) запускаю
------
Угу... где-то в самом начале тебе рекомендовалось разобраться что и на какой машине выполняется. Когда ты запускаешь веб-сервер локально у тебя - учитывая твой сишный опыт и непонимание "портов и гаваней" - не получается точно осознать где какой кусок кода выполняется. Ну а код состоит из двух частей: одна работает на сервере, а вторая - на клиенте. Плюс - коммуникация через "порты и гавани".
Мы говорим только про запуск апплета.
------
Про отслеживание повторного запуска апплета тебе уже все разжевали - решения на клиенте нет и быть не может. А каким образом ты ходишь на сервер мне пока не понятно. Предположения - да, есть, но вариантов много...
Надо не давать больше чем одному логину работать в одной и той же сессии. В разных сессиях можно сколько угодно разных логинов, но одна сессия - один логин.
Надо надежно отслеживать что пользователь прекратил работу, даже если он не делал логаут, а просто закрыл окно браузера.
сессия - на Томкате, с http, и абсолютно точно привязана к IP, это я проверил.
А как вы проверили? Лично я не знаю такой реализации Manager-а, который заставит томкат использовать одну и ту же сесстю для одного IP. Как у вас сконфигурирован Manager в Context-е?
Покажите код сервлета, который вызывается когда пользователь логинится. До логина апплет обращается к сервлету?
Допустим все именно так, у нас HttpSession, привязанная к IP и живущая 10 дней (кто ж до такого догадался-то...)
Кто виноват - понятно, аффтар жжот. Что делать? Ничего хорошего.
Апплет у вас как-то идентифицируется, несмотря на то что общение с сервером идет в одной сессии, или нет?
Т.е. если на одной машине открыты два окна, в обоих юзер залогинится используя один и тот же логин X, на сервлет пришел какой-то запрос, вы можете понять от какого из двух апплетов он пришел?
Если мы может разделять пользователей (для каждого запроса, пришедего на сервлет, мы можем прочитать из запроса или создать идентификатор клиента uniqueClientId), то сработает такое:
1. При логине смотрим в HttpSession (метод getAttribute(String))- есть ли у нас аттрибут CURRENT_LOGIN
1.1 нет аттрибута. Значит в этой сессии никто не залогинен. Разрешаем логин
session.setAttribute("CURRENT_LOGIN", uniqueClientId);
session.setAttribute("LAST_ACTION_TIME", System.currentTimeMillis());
1.2 есть аттрибут. Проверяем не вылетел ли этот пользоватль по таймауту. Читаем из сессии LAST_ACTION_TIME
final long currentTime = System.currentTimeMillis();
final boolean loginTimedOut;
if(session.getAttribute("LAST_ACTION_TIME")==null){
loginTimedOut = false;
} else {
final long lastActionTime = (Long)session.getAttribute("LAST_ACTION_TIME");
loginTimedOut = currentTime > lastActionTime + inactivityTimeout; // inactivityTimeout, например, равен 15*60*1000 (15 минут)
}
1.2.1 loginTimedOut == true. Пользователь с этим логином слишком долго ничего не делал. Меняем его логин.
session.setAttribute("CURRENT_LOGIN", uniqueClientId);
session.setAttribute("LAST_ACTION_TIME", System.currentTimeMillis());
1.2.2 loginTimedOut = false Логин активен - новый логин запрещен
2. При каждом запросе от апплета смотрим от кого он пришел, если ID логина (uniqueClientId) совпадает с тем, что в сессии в аттрибуте CURRENT_LOGIN лежит, актуализируем LAST_ACTION_TIME и выполняем запрос.
Если не совпадает (запрос может придти от старого апплета, с логином, который был замещен новым из-за неактивности) собщаем об ошибке и закрываем апплет.
А как вы проверили?
В сессии проверяется IP.
public class AuthenticationData
...
public void reset ()
{
...
if (Current- -Context.getC_local_ip() != null )
localIP = Current- -Context.getC_local_ip();
else
localIP = "";
}
public class LogonPanel
locUser = User.logon(m_efUserID.getText(), strEncrypt, strNewEncrypt, curMandant.getId(),
Current- -Context.getC_local_ip());
Ну, и т.д.
лично я не знаю такой реализации Manager-а, который заставит томкат использовать одну и ту же сесстю для одного IP. Как у вас сконфигурирован Manager в Context-е?
public class Current- -Context
private static GeneralSaveInBufferManager c_saveInBuffer = null;
private Current- -Context()
{
c_saveInBuffer = GeneralSaveInBufferManager.getInstance();
}
public static void putSaveInBuffer- - (General- - obj) throws GeneralException
{
if (c_saveInBuffer == null)
{
c_saveInBuffer = GeneralSaveInBufferManager.getInstance();
}
c_saveInBuffer.addGeneralData- -(obj);
}
public static GeneralSaveInBufferManager getSaveInBufferManager()
{
if (c_saveInBuffer == null)
{
c_saveInBuffer = GeneralSaveInBufferManager.getInstance();
}
return (c_saveInBuffer);
}
public static String getC_local_ip() {
return c_local_ip;
}
public static void setC_local_ip(String c_local_ip) {
Current- -Context.c_local_ip = c_local_ip;
}
Покажите код сервлета, который вызывается когда пользователь логинится. До логина апплет обращается к сервлету?
public synchronized InputStream sendRequest(Serializable obj) throws Throwable
{
showInfo("Open connection to servlet: " + m_servlet.toString());
m_connection = m_servlet.openConnection();
// Prepare for both input and output
m_connection.setDoInput(true);
m_connection.setDoOutput(true);
// Turn off caching
m_connection.setUseCaches(false);
// Set the content type to be java-internal/classname
m_connection.setRequestProperty("Content-Type",
"java-internal/" + obj.getClass().getName());
// Write the serialized - - as post data
- -OutputStream out = new - -OutputStream(m_connection.getOutputStream());
out.write- -(obj);
out.flush();
out.close();
return m_connection.getInputStream();
}
public void prepareCommunicationAdapter() throws GeneralException
{
super.prepareCommunicationAdapter();
// set mappings for used client personalities dependent on current communication
if (ndController.isServletCommunication())
{
GeneralServerAdapter_Servlet.setDefaultServletClass(ndServlet.class);
MessageProcessingServerAdapter_Servlet msgProcessingServletAdapter = new MessageProcessingServerAdapter_Servlet();
ndDate.setServerForClass(ndDate.class, new ndDateServerAdapter_Servlet());
DccAccount.setServerForClass(DccAccount.class, new DccAccountServerAdapter_Servlet());
Settlement.setServerForClass(Settlement.class, new SettlementServerAdapter_Servlet());
DreCatiSettlement.setServerForClass(DreCatiSettlement.class, new DreCatiSettlementServerAdapter_Servlet());
DreCatiCurrencyManager.setServerForClass(DreCatiCurrencyManager.class, new DreCatiCurrencyManagerServerAdapter_Servlet());
DreCatiAccount.setServerForClass(DreCatiAccount.class, new DreCatiAccountServerAdapter_Servlet());
DreCatiAccount.setServerForClass(DreCatiTrancheControl.class, new DreCatiTrancheControlServerAdapter_Servlet());
DiAccount.setServerForClass(DiAccount.class, new DiAccountServerAdapter_Servlet());
ndAcknowledgement.setServerForClass(ndAcknowledgement.class, new AcknowledgementServerAdapter_Servlet());
ApplParameter.setServerForClass(ApplParameter.class, new ApplParameterServerAdapter_Servlet());
ClientApplParameter.setServerForClass(ClientApplParameter.class, new ClientApplParameterServerAdapter_Servlet());
ClientBackendParameter.setServerForClass(ClientBackendParameter.class, new ClientBackendParameterServerAdapter_Servlet());
Authentication.setServerForClass(Authentication.class, new AuthenticationServerAdapter_Servlet());
BackendAccess.setServerForClass(BackendAccess.class, new BackendAccessServerAdapter_Servlet());
Branch.setServerForClass(Branch.class, new BranchServerAdapter_Servlet());
Currency.setServerForClass(Currency.class, new CurrencyServerAdapter_Servlet());
CurrentState.setServerForClass(CurrentState.class, msgProcessingServletAdapter);
Customer.setServerForClass(Customer.class, new CustomerServerAdapter_Servlet());
DataManager.setServerForClass(DataManager.class, new DataManagerServerAdapter_Servlet());
EventLog.setServerForClass(EventLog.class, new EventLogServerAdapter_Servlet());
dccEventLog.setServerForClass(dccEventLog.class, new dccEventLogServerAdapter_Servlet());
History.setServerForClass(History.class, new HistoryServerAdapter_Servlet());
Holiday.setServerForClass(Holiday.class, new HolidayServerAdapter_Servlet());
InRoutingConfig.setServerForClass(InRoutingConfig.class, new InRoutingConfigServerAdapter_Servlet());
InvalidPassword.setServerForClass(InvalidPassword.class, new InvalidPasswordServerAdapter_Servlet());
Language.setServerForClass(Language.class, new LanguageServerAdapter_Servlet());
LocalUser.setServerForClass(LocalUser.class, new UserServerAdapter_Servlet());
Log.setServerForClass(Log.class, new LogServerAdapter_Servlet());
Mandant.setServerForClass(Mandant.class, new MandantServerAdapter_Servlet());
ndMandant.setServerForClass(ndMandant.class, new MandantServerAdapter_Servlet());
Message.setServerForClass(Message.class, new MessageServerAdapter_Servlet());
ndMessage.setServerForClass(ndMessage.class, new ndMessageServerAdapter_Servlet());
MessagePrefix.setServerForClass(MessagePrefix.class, new MessagePrefixServerAdapter_Servlet());
MissingState.setServerForClass(MissingState.class, msgProcessingServletAdapter);
MsgAccess.setServerForClass(MsgAccess.class, new MsgAccessServerAdapter_Servlet());
ndProcess- -.setServerForClass(ndProcess- -.class, new ndProcessServerAdapter_Servlet());
ProcessedState.setServerForClass(ProcessedState.class, msgProcessingServletAdapter);
Program.setServerForClass(Program.class, new ProgramServerAdapter_Servlet());
Reconciliation.setServerForClass(Reconciliation.class, new ReconciliationServerAdapter_Servlet());
Queue.setServerForClass(Queue.class, new QueueServerAdapter_Servlet());
SystemParameter.setServerForClass(SystemParameter.class, new SystemParameterServerAdapter_Servlet());
ndTargetApplication.setServerForClass(ndTargetApplication.class, new ndTargetApplicationServerAdapter_Servlet());
TextHandler.setServerForClass(TextHandler.class, new TextHandlerServerAdapter_Servlet());
TextResourceBundle.setServerForClass(TextResourceBundle.class, new TextHandlerServerAdapter_Servlet());
User.setServerForClass(User.class, new UserServerAdapter_Servlet());
UserGroup.setServerForClass(UserGroup.class, new UserGroupServerAdapter_Servlet());
ConcHistory.setServerForClass(ConcHistory.class, new ConcHistoryServerAdapter_Servlet());
Country.setServerForClass(Country.class, new CountryServerAdapter_Servlet());
SysRouteDelete.setServerForClass(SysRouteDelete.class, new SysRouteDeleteServerAdapter_Servlet());
Statistics.setServerForClass(Statistics.class, new StatisticsServerAdapter_Servlet());
Department.setServerForClass(Department.class, new DepartmentServerAdapter_Servlet());
OutsourcingControl.setServerForClass(OutsourcingControl.class, new OutsourcingControlServerAdapter_Servlet());
ndPricingRemittance.setServerForClass(ndPricingRemittance.class, new ndPricingRemittanceServerAdapter_Servlet());
Pricing.setServerForClass(Pricing.class, new PricingServerAdapter_Servlet());
AccountLength.setServerForClass(AccountLength.class, new AccountLengthServerAdapter_Servlet());
ReorganisationDB.setServerForClass(ReorganisationDB.class, new ReorganisationDBServerAdapter_Servlet());
IntdualcAccount.setServerForClass(IntdualcAccount.class, new IntdualcAccountServerAdapter_Servlet());
IntdualcSettlement.setServerForClass(IntdualcSettlement.class, new IntdualcSettlementServerAdapter_Servlet());
DiSettlement.setServerForClass(DiSettlement.class, new DiSettlementServerAdapter_Servlet());
OrgaDb.setServerForClass(OrgaDb.class, new OrgaDbServerAdapter_Servlet());
}
else ...
Придется опять постить большой кусок текста, который вызовет у Вас недобрые чуйства

public static void setGeneralParameters(J- - - -)
{
String temp;
// set product logo name if available
if ((temp = - -.getParameter("productLogo")) != null)
{
GeneralServerAdapter.setProductLogoForLogonPanel(temp);
Trace.traceInfo("productLogo:"
+ temp);
}
// set client name if available
if ((temp = - -.getParameter("productName")) != null)
{
GeneralServerAdapter.setProductNameForLogonPanel(temp);
Trace.traceInfo("productName:"
+ temp);
}
// trace on/off?
if ((temp = - -.getParameter("Trace")) != null)
Trace.setTraceLevel(Integer.parseInt(temp));
// Security: Is the connection over HTTPS?
if ((temp = - -.getParameter("Security")) != null)
{
GeneralServerAdapter.setSecurityLevel(Integer.parseInt(temp));
Trace.traceInfo("Security level:"
+ temp);
}
// get the https-Port of the server:
if ((temp = - -.getParameter("httpsPort")) != null)
{
GeneralServerAdapter.setSecurityPort(Integer.parseInt(temp));
Trace.traceInfo("https port:"
+ temp);
}
// get the http-Port of the server:
if ((temp = - -.getParameter("httpPort")) != null)
{
GeneralServerAdapter.setHttpPort(Integer.parseInt(temp));
Trace.traceInfo("http port:"
+ temp);
}
if ((temp = - -.getParameter("WriteOutfile")) != null)
{
if (Integer.parseInt(temp) > 0)
{
GeneralBasePanel.setAllowWriteToOutfile(true);
Trace.traceInfo("Write to outfile enabled.");
}
}
// get the http-Port of the server:
if ((temp = - -.getParameter("rmiPort")) != null)
{
GeneralServerAdapter.setRMIPort(Integer.parseInt(temp));
Trace.traceInfo("rmi port:"
+ temp);
}
// get the location of the server
if ((temp = - -.getParameter("HostName")) != null)
{
// if there is a port number in the hostname:
// dismember it and set the separate properties:
int indexOfColon = temp.indexOf(':');
if (indexOfColon >= 0)
{
int port = 0;
if (indexOfColon + 1 < temp.length())
{
port = Integer.parseInt(temp.substring(indexOfColon + 1));
}
// only set the normal http-Port if it isn't set wit "httpPort":
if (GeneralServerAdapter.getHttpPort() <= 0)
{
GeneralServerAdapter.setHttpPort(port);
GeneralServerAdapter.setRMIPort(port);
}
if (indexOfColon > 0)
{
temp = temp.substring(0, indexOfColon);
}
else
{
temp = "";
}
}
GeneralServerAdapter.setHostName(temp);
}
//get the prefix of the servername
if ((temp = - -.getParameter("Product")) != null)
{
GeneralServerAdapter.setProduct(temp);
String stringInstanceNr;
if ((stringInstanceNr = - -.getParameter("Instance")) != null) {
temp = temp + "_" + stringInstanceNr;
}
// this is client side so we can set it globally
GeneralServerAdapter.setGlobalServerNamePrefix(temp + ".");
}
if ((temp = - -.getParameter("Servlet")) != null)
{
c_fServlet = !(temp.equals("0"));
}
//gets the state for the polling mechanism, the default value is true (enabled)
if ((temp = - -.getParameter("Polling")) != null)
{
try
{
c_iPollingOn = (new Integer(temp)).intValue();
}
catch (Exception e)
{
Trace.traceInfo("Error: The defined polling delay is not of type integer !");
c_iPollingOn = 0;
}
}
//is the AccessControl enabled, the default is true!
if ((temp = - -.getParameter("AccessControl")) != null)
{
c_fAccessControllOn = !(temp.equals("0"));
}
//new for JRun 3.1
if ((temp = - -.getParameter("WebApplication")) != null)
GeneralServerAdapter.setWebApplicationMapping(temp);
// Get the ip from the calling client or local host (dev-enviroment)
String ip = "";
// Get IP A: First try over the network interfaces
try
{
Enumeration <NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
outmost:
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "HostAddress: " +addr.getHostAddress() + " Hostname: " + addr.getHostName() + " CanonicalHostName: " +addr.getCanonicalHostName());
if (addr instanceof Inet6Address)
{
Trace.traceInfo("Found IP6 Address (IP: " + addr.getHostAddress() + "). Check it...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "Found IP6 Address (IP: " + addr.getHostAddress() + "). Check it...");
if (addr.isSiteLocalAddress())
{
Trace.traceInfo("IP6 Address (IP: " + addr.getHostAddress() + ") is a site local address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP6 Address (IP: " + addr.getHostAddress() + ") is a site local address. Search forward...");
}
else if (addr.isLoopbackAddress())
{
Trace.traceInfo("IP6 Address (IP: " + addr.getHostAddress() + ") is a loopback address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP6 Address (IP: " + addr.getHostAddress() + ") is a loopback address. Search forward...");
}
else if (addr.isLinkLocalAddress())
{
Trace.traceInfo("IP6 Address (IP: " + addr.getHostAddress() + ") is a link local address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP6 Address (IP: " + addr.getHostAddress() + ") is a link local address. Search forward...");
}
else
{
Trace.traceInfo("IP6 Address (IP: " + addr.getHostAddress() + " Host: " + addr.getHostName() + ") detected.");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP6 Address (IP: " + addr.getHostAddress() + " Host: " + addr.getHostName() + ") detected.");
ip = addr.getHostAddress();
break outmost;
}
}
if (addr instanceof Inet4Address)
{
Trace.traceInfo("Found IP4 Address (IP: " + addr.getHostAddress() + "). Check it...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "Found IP4 Address (IP: " + addr.getHostAddress() + "). Check it...");
if (addr.isSiteLocalAddress())
{
Trace.traceInfo("IP4 Address (IP: " + addr.getHostAddress() + ") is a site local address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP4 Address (IP: " + addr.getHostAddress() + ") is a site local address. Search forward...");
}
else if (addr.isLoopbackAddress())
{
Trace.traceInfo("IP4 Address (IP: " + addr.getHostAddress() + ") is a loopback address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP4 Address (IP: " + addr.getHostAddress() + ") is a loopback address. Search forward...");
}
else if (addr.isLinkLocalAddress())
{
Trace.traceInfo("IP4 Address (IP: " + addr.getHostAddress() + ") is a link local address. Search forward...");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP4 Address (IP: " + addr.getHostAddress() + ") is a link local address. Search forward...");
}
else
{
Trace.traceInfo("IP4 Address (IP: " + addr.getHostAddress() + " Host: " + addr.getHostName() + ") detected.");
// Anzeige über Messagedialog für Debugging in Citrix-Umgebung (dort ist keine Java-Konsole aktiv)
//JOptionPane.showMessageDialog(null, "IP4 Address (IP: " + addr.getHostAddress() + " Host: " + addr.getHostName() + ") detected.");
ip = addr.getHostAddress();
break outmost;
}
}
}
}
} catch (SocketException e) {
Trace.traceException(e);
Trace.traceStack();
}
// Get IP B: Second try over Socket
if ( ip.isEmpty() )
{
Socket socket = null;
int port = 0;
if(- -.getDocumentBase().getPort()!=-1)
{
port = - -.getDocumentBase().getPort();
}
else
{
port = 80;
}
try
{
socket = new Socket(- -.getDocumentBase().getHost(), port);
if (socket != null)
{
ip = socket.getLocalAddress().getHostAddress();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Check ip - is loopback ip?
if ( ip.isEmpty() || "127.0.0.1".equals(ip) )
{
Trace.traceInfo("Cannot determine local IP address !");
ip = "0.0.0.0";
Trace.traceInfo("Use default ip: " + ip );
}
Current- -Context.setC_local_ip(ip);
// now we have to define the mapping between some client personality classes and their
// corresponding adapter classes (the ones which are used in this base class)
if (isServletCommunication())
{
Trace.traceInfo("Use Servlet Communication ...");
Authentication.setServerForClass(Authentication.class, new AuthenticationServerAdapter_Servlet());
}
else
{
Trace.traceInfo("Use RMI Communication ...");
Authentication.setServerForClass(Authentication.class, new AuthenticationServerAdapter_RMI());
}
if ((temp = - -.getParameter("DefaultTimeZone")) != null)
GeneralServerAdapter.setDefaultTimeZone(temp);
if ((temp = - -.getParameter("ShellTimezone")) != null)
{
CurrentDateSupport.setTimeSupport(temp);
}
Trace.traceInfo("set param ShellTimezone: "
+ CurrentDateSupport.getTimeSupport());
}
Апплет у вас как-то идентифицируется, несмотря на то что общение с сервером идет в одной сессии, или нет?
Т.е. если на одной машине открыты два окна, в обоих юзер залогинится используя один и тот же логин X, на сервлет пришел какой-то запрос, вы можете понять от какого из двух апплетов он пришел?
Очевидно, нет, если IP один и тот же.
Но обычно юзер логинится под двумя разными аккаунтами, под одним не имеет смысла.
Большое спасибо за конкретное предложение

Мне надо сделать обеденную паузу и подумать над ним.
Хммм... Эквивалентно - Едя по автобану на Юг мы пешком по буеракам идем север.
В каком же направлении движение то?
Я надеюсь, из приведенного выше кода это стало немного понятно?
Там даже про сокеты есть.
У вас в классе AuthenticationData хранится локальный IP-адрес. Наверное, в этом AuthenticationData у вас и имя пользователя и пароль в каком-то виде хранится. Только это не говорит о том что у вас на томкате сессия по ип выдается.
Вангую: у апплета есть метод который вызывает sendRequest(Object) и передает кму как параметр объект типа AuthenticationData. Это и есть метод для логина.
Как у вас сконфигурирован Manager в Context-е?
Я имел в виду томкат, где ваш deployment descriptor для вашего сервлета. Ищите context.xml
Вы же мне накидали класс, который у вас в буфере объекты хранит.
public synchronized InputStream sendRequest(Serializable obj) throws Throwable
Это не
код сервлета, который вызывается когда пользователь логинится.
Это код апплета, которым он связывается с сервлетом.
setGeneralParameters тоже похож на код апплета. На мои вопросы не отвечает.
Вы знаете, вы похоже думаете, что вы накидаете куски кода а вам - раз и выложат решение. Это вряд ли. Прошла неделя а вы так и не удосужились разобраться где же у вас сервлет, где апплет а где томкат с сессией.
Подсказать направление я вам могу, а за вас делать меньше сотни за час не возьму.
Две подсказки:
- у вас нет никакой HttpSession на томкате. Вы с сервлетом по URLConnection общаетесь, куки не передаете, ;jsessionid к URL не приписываете, из InputStream-а кукине читаете.
- код вашего сервлета ищите в классе, который extends HttpServlet
------
Нее, не на много.
Пока понятно что у тебя либо дуальная - <HTTP & RMI> или потенциально дуальная коммуникация с сервером.
Когда и какая - надо смотреть... Проимплементил бы фабрику коммуникаторов - понимать было бы легче.
Одно ясно - не чисто <HTTP(S)>.
-----
У меня ощущение, что у него нет доступа к этой части. Есть какой-то самописный <rmi-2-http> прокси и на этом все - дальше не пускают.
где же у вас сервлет, где апплет а где томкат с сессией.
-----
Хи-хи-кс...

Только это не говорит о том что у вас на томкате сессия по ип выдается.
Я у шефа спрашивал, он сказал, что 100% по IP

Да и как еще, если всегда одна сессия на рыло?
Вангую: у апплета есть метод который вызывает sendRequest(- -) и передает кму как параметр объект типа AuthenticationData. Это и есть метод для логина.
Ванговать не надо, sendRequest(- -) у меня выше описан

Вызывается он с объектом типа ServletTransfer- -.
Я имел в виду томкат, где ваш deployment de- -or для вашего сервлета. Ищите context.xml
Есть, но он практически пустой:
less server.xml
<Server port="18160" shutdown="SHUTDOWN" debug="0">
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
debug="0"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
debug="0"/>
<GlobalNamingResources>
<Context className="org.apache.catalina.core.StandardContext"
cachingAllowed="true"
charsetMapperClass="org.apache.catalina.util.CharsetMapper"
cookies="true"
crossContext="false"
debug="0"
displayName="ICM-6 Entwicklung"
docBase="/home/icm6/dcc/web/lib"
mapperClass="org.apache.catalina.core.StandardContextMapper"
path="/ICM6"
privileged="true"
reloadable="true"
swallowOutput="false"
useNaming="true"
wrapperClass="org.apache.catalina.core.StandardWrapper">
<Resources className="org.apache.naming.resources.FileDirContext"
allowLinking="true" />
</Context>
</Host>
</Engine>
</Service>
</Server>
setGeneralParameters тоже похож на код апплета. На мои вопросы не отвечает.
Код public class ndServlet extends HttpServlet ниже, а здесь сначала еще один класс, который этим занимается:
public class GeneralServerAdapter_Servlet extends GeneralServerAdapter
implements IGeneralServerAdapter
{
private URL m_servlet = null;
..........
/**
* Special method to return the result data of the request.
*
* This is handled in a separate method to support advanced communication
* issues like e.g. multi block data transfer.
*/
protected - - getResultData(ServletTransfer- - reqObj,
ServletTransfer- - resObj) throws GeneralException
{
- - obj = resObj.getData- -();
// if there is a special communication - - returned
// -> this is a multi block data transfer
if (obj == null)
return (obj);
if (!(obj instanceof ndCommunication- -))
return (obj);
// special communication required - multi block data transfer
ndCommunication- - ndComm = (ndCommunication- -)obj;
// The result we receive can take two different forms:
// - a normal vector, which contains data elements and we
// have to append following data blocks to this vector
// - a special vector containing exactly two elements
// -> a de- -ion - -
// -> a data vector (where we have to append the following data)
- - objResult = ndComm.getData();
Assertion.verify(objResult instanceof Vector<?>);
Vector<?> vecResult = (Vector<?>) objResult;
// locate the relevant data vector to which we will add the following
// data blocks
@SuppressWarnings("unchecked")
Vector<- -> vecReceivedData = (Vector<- ->) vecResult;
// if the result vector as two elements and the second element is a vector
// the "real" result is the second element
if ((vecResult.size() == 2) && (vecResult.elementAt(1) instanceof Vector<?>))
{
@SuppressWarnings("unchecked")
Vector<- -> realResultVec = (Vector<- ->) vecResult.elementAt(1);
vecReceivedData = realResultVec;
}
// NOTE: if we now add data to vecReceivedData, we add it indirectly either
// to vecResult (in case vecResult is the "real" data vector) or to
// the second element of vecResult (in case the second element is the
// "real" data vector)
// prepare the special transfer - - to communicate with the servlet
reqObj.setAdapterMethod("getNextDataBlock");
reqObj.setArgumentClass(ndComm.getClass().getName());
while (ndComm.isMoreDataAvailable())
{
// read the next data block
reqObj.setData- -(ndComm);
ndComm.setDataCompressed(false);
ndComm.setData(null);
resObj = (ServletTransfer- -)doRequest(reqObj);
if (resObj.getException() != null)
throw resObj.getException();
obj = resObj.getData- -();
// append data of the current block to the result vector
Assertion.verify(obj instanceof ndCommunication- -);
ndComm = (ndCommunication- -)obj;
Vector<?> vecNewData = (Vector<?>) ndComm.getData();
VectorSupport.addAllFrom(vecNewData, vecReceivedData);
}
return vecResult;
}
public synchronized - - doRequest(ServletTransfer- - obj)
throws GeneralException
{
// the method is synchronized for this - - which means there can only
// be one request via this - - at a time
// -> but to be sure that there is only one request at a time from
// -> the virtual machine (from the Client) we synchronize
// -> via a static - -
- - objResult = null;
synchronized(c_fSyncSendRequest)
{
try
{
getServlet();
// Send the request
// sometimes there occurs an IOException in IE context so we'll
// try it several times
int iTries = 1;
boolean fOk = false;
InputStream in = null;
while (!fOk)
{
try
{
iTries++;
in = sendRequest(obj);
fOk = true;
}
catch (IOException ex)
{
// we allow three tries...
if (iTries >= 3)
throw ex;
Trace.traceInfo("IOException occurred - try again...");
}
}
// now get the result
- -InputStream result = new - -InputStream(in);
// and build the result - -
objResult = result.read- -();
in.close();
m_connection = null;
}
catch (Throwable e)
{
...
}
}
return (objResult);
}
public URL getServlet() throws GeneralException
{
// if it is already there - use it - but only if security hasn't changed...
if (m_servlet != null && m_iLastSecurityLevel == getCurrentServletSecurityLevel())
{
return (m_servlet);
}
// try to get the servlet
try
{
showInfo("Servlet-Name: " + getServletName());
m_servlet = new URL(getServletName());
m_iLastSecurityLevel=getCurrentServletSecurityLevel();
}
catch (Throwable e)
{
m_servlet = null;
throw new GeneralException(e);
}
return (m_servlet);
}
public synchronized InputStream sendRequest(Serializable obj) throws Throwable
{
showInfo("Open connection to servlet: " + m_servlet.toString());
m_connection = m_servlet.openConnection();
// Prepare for both input and output
m_connection.setDoInput(true);
m_connection.setDoOutput(true);
// Turn off caching
m_connection.setUseCaches(false);
// Set the content type to be java-internal/classname
m_connection.setRequestProperty("Content-Type",
"java-internal/" + obj.getClass().getName());
// Write the serialized - - as post data
- -OutputStream out = new - -OutputStream(m_connection.getOutputStream());
out.write- -(obj);
out.flush();
out.close();
return m_connection.getInputStream();
}
Вы знаете, вы похоже думаете, что вы накидаете куски кода а вам - раз и выложат решение.
Нет, я так не думаю. Вы меня просили показать код, я показал. Ну, ошибся разок, извините.
Прошла неделя
Еще не прошла. Я только в пятницу открыл ветку
Учтите, что я в этом деле профан и иду, как по минному полю.
Подсказать направление я вам могу, а за вас делать меньше сотни за час не возьму.
Направление мне и надо.
Две подсказки:
- у вас нет никакой HttpSession на томкате.
Да, видимо, это верно. Я покопался в логах томката, никакой HttpSession там не нашел. В коде она есть, в том самом пакете Servlet и классе ndServlet extends HttpServlet:
* The ndServlet class provides transport functionality from the client
* side to the RMI-server.
*
* @version 1.00 03.12.1999
* @see HttpServlet
*/
public class ndServlet
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
showInfo("session got: " + session.getId());
if (session.getAttribute(KEY_BINDING_LISTENER) != this)
session.setAttribute(KEY_BINDING_LISTENER, this);
else
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
public void init(ServletConfig config) throws ServletException
{
super.init(config);
String hostname;
String maxBlockSize;
int tracelevel;
//In the Moment, we set no Security! It remains to check, if you can do it with policy-files
//System.setSecurityManager(new NoSecurityManager());
// Trace on/off?
if (config.getInitParameter("Trace") != null)
{
tracelevel = Integer.parseInt(config.getInitParameter("Trace"));
if ((tracelevel > Trace.TRACE_OFF) &&
(tracelevel <= Trace.FUNCTION_TRACE))
Trace.setTraceLevel(tracelevel);
}
showInfo("ndServlet.init: init called ...");
// set the server for the RMI-Communication
if ((hostname = config.getInitParameter("HostName")) != null)
{
GeneralServerAdapter.setHostName(hostname);
showInfo("hostname for RMI set to: " + hostname);
}
// enable own support for communication
if (config.getInitParameter("HandleCommunication") != null)
{
String str = config.getInitParameter("HandleCommunication");
boolean fEnable = (Integer.parseInt(str) != 0);
c_fSpecialCommunicationSupport = fEnable;
if (fEnable)
showInfo("Special support for communication enabled");
}
// handle special parameters for special communication (if this is enabled)
if (c_fSpecialCommunicationSupport)
{
// set the max transfer block size
if ((maxBlockSize = config.getInitParameter("TransferBlockSize")) != null)
{
setMaxTransferBlockSize(Integer.parseInt(maxBlockSize));
}
showInfo("Transfer block size: " + c_iMaxBlockSize);
// enable compression for data transfer if requested
if (config.getInitParameter("TransferCompression") != null)
{
String str = config.getInitParameter("TransferCompression");
boolean fEnable = (Integer.parseInt(str) != 0);
setUseCompressionForTransfer(fEnable);
if (fEnable)
showInfo("Compression activated for transfer");
else
showInfo("Compression deactivated for transfer");
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
showInfo("doGet called...");
}
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
super.service(req, resp);
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try
{
AnalyzeSupport timeSup = new AnalyzeSupport();
showInfo("doPost started");
// first get the request - -
- -InputStream objIn = new - -InputStream(request.getInputStream());
ServletTransfer- - objTransfer = (ServletTransfer- -)objIn.read- -();
objIn.close();
- - objResult;
// now handle special case: multi block transfer
// (in case of own support for communication)
if (!(objTransfer.getData- -() instanceof ndCommunication- -) ||
!c_fSpecialCommunicationSupport)
{
// now fulfill the request which is described in the transfer - -
// -> first build the requested instance
Class<?> clsAdapter = Class.forName(objTransfer.getAdapterClass());
- - objAdapter = clsAdapter.newInstance();
// -> and then call the method to get the result
Class<?> paramClasses[] = null;
- - params[] = null;
if (objTransfer.getData- -() != null)
{
paramClasses = new Class[1];
paramClasses[0] = Class.forName(objTransfer.getArgumentClass());
params = new - -[1];
params[0] = objTransfer.getData- -();
}
Method met = clsAdapter.getMethod(objTransfer.getAdapterMethod(), paramClasses);
// set binding listener for session if it's not already done...
HttpSession session = request.getSession(true);
showInfo("session got: " + session.getId());
if (session.getAttribute(KEY_BINDING_LISTENER) != this)
session.setAttribute(KEY_BINDING_LISTENER, this);
else
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
// save the Prefix to be used for server communication from this servlet
setServerNamePrefix(objTransfer.getServerNamePrefix());
if (objAdapter instanceof GeneralServerAdapter)
{
GeneralServerAdapter adapt = (GeneralServerAdapter)objAdapter;
adapt.setServerNamePrefix(this.getServerNamePrefix());
}
// set current sessionid in Adapter as the access key
if (objAdapter instanceof GeneralServerAdapter_RMI)
{
GeneralServerAdapter_RMI adapt = (GeneralServerAdapter_RMI)objAdapter;
adapt.setAccessKey(session.getId());
showInfo("ndServlet.doPost, SessionID(access key) set: " + session.getId());
// also use the session id as request id
adapt.setRequestId(session.getId());
// the adapter should handle special communication issues
// in case the servlet should also do it on its own
adapt.setHandleSpecialCommunication(c_fSpecialCommunicationSupport);
}
AnalyzeSupport timeSup2 = new AnalyzeSupport();
showInfo("ndServlet.doPost, Method: " + met.getName());
objResult = met.invoke(objAdapter, params);
timeSup2.showTimeUsage("ndServlet.doPost RMI-Invocation-Time:");
}
else
{
// special communication
showInfo("getNextDataBlock...");
objResult = this.getNextDataBlock((ndCommunication- -)objTransfer.getData- -());
}
if (objResult != null)
{
// now build the response - -
objTransfer.setData- -((Serializable)this.getResult- -(objResult));
// ...and send it back to the requestor
response.setContentType("java-internal/" + objResult.getClass().getName());
}
else
{
objTransfer.setData- - (null);
response.setContentType("java-internal/null");
}
// now write the - - to the response output stream
this.write- -(response, objTransfer);
timeSup.showTimeUsage("PP_Servlet Request-Time:");
}
catch (Throwable e)
{
GeneralException ex;
if (e instanceof GeneralException)
ex = (GeneralException)e;
else
ex = new GeneralException(e);
// ...and send it back to the requestor
response.setContentType("text/html");
ServletTransfer- - objTransfer = new ServletTransfer- -();
objTransfer.setData- -(new Vector<- ->());
objTransfer.setException(ex);
// now write the - - to the response output stream
this.write- -(response, objTransfer);
}
}
/**
* Special handling for returning the result - -
* created for the current request.
*/
protected - - getResult- -(- - result) throws GeneralException
{
boolean fCachedSearch = false;
boolean fVectorResult = false;
Vector<- -> vecResult = new Vector<- ->();
if (result == null) {
return (result);
}
// if the servlet is advised not to do its own
// communication we return the result - - directly
// (in case of a vector we look for a ndCommunication- - as only
// element and return this)
if (!c_fSpecialCommunicationSupport)
{
if (result instanceof Vector<?>)
{
Iterator<?> iterator = ((Vector<?>) result).iterator();
while (iterator.hasNext()) {
vecResult.add((- -)iterator.next());
}
if (vecResult.size() == 1)
{
- - obj1 = vecResult.firstElement();
if (obj1 instanceof ndCommunication- -) {
return (obj1);
}
}
}
return (result);
}
// if this is a special search the result - - is a vector
// which contains two elements:
// 1. GeneralSearchDe- -ion- - (to describe the search)
// 2. Vector (result data)
if (result instanceof Vector<?>)
{
Iterator<?> iterator = ((Vector<?>) result).iterator();
while (iterator.hasNext()) {
vecResult.add((- -)iterator.next());
}
fVectorResult = true;
if (vecResult.size() == 2)
{
- - obj1 = vecResult.firstElement();
- - obj2 = vecResult.elementAt(1);
if ( (obj1 instanceof GeneralSearchDe- -ion- -)
&& (obj2 instanceof Vector<?>))
{
fCachedSearch = true;
}
}
}
// now in case of returning a vector we have to check the size
// against the given block size to support the transfer of
// large vectors in multiple data blocks
// -> this approach only makes sense for external requests due to
// -> slow data transfer...
if ((c_iMaxBlockSize > 0) && fVectorResult)
{
if (fCachedSearch)
{
Vector<?> vecData = (Vector<?>) vecResult.elementAt(1);
if (vecData.size() > c_iMaxBlockSize)
{
// in this case the second element (the data vector) has to be
// replaced by a vector containing the first data block of this vector
Vector<- -> vecNewData = new Vector<- ->();
// multi block transfer is necessary
// -> we have to encapsulate the data in a special communication
// -> - - which has to be used for these purposes
ndCommunication- - ndComm = new ndCommunication- -();
ndComm.setAccessKey(VectorStore.addVector(vecData));
ndComm.setMoreDataAvailable(VectorStore.getNextBlockFromVector(ndComm.getAccessKey(),
vecNewData,
c_iMaxBlockSize));
// fill in the new data block in the result vector
vecResult.removeElementAt(1);
vecResult.addElement(vecNewData);
ndComm.setDataCompressed(c_fUseCompressionForTransfer);
ndComm.setData(vecResult);
result = ndComm;
}
}
else
{
if (vecResult.size() > c_iMaxBlockSize)
{
// multi block transfer is necessary
// -> we have to encapsulate the data in a special communication
// -> - - which has to be used for these purposes
ndCommunication- - ndComm = new ndCommunication- -();
ndComm.setAccessKey(VectorStore.addVector(vecResult));
Vector<- -> vecData = new Vector<- ->();
ndComm.setMoreDataAvailable(VectorStore.getNextBlockFromVector(ndComm.getAccessKey(),
vecData,
c_iMaxBlockSize));
ndComm.setDataCompressed(c_fUseCompressionForTransfer);
ndComm.setData(vecData);
result = ndComm;
}
else if (c_fUseCompressionForTransfer)
{
// -> we have to encapsulate the data in a special communication
// -> - - which has to be used for these purposes (compression)
ndCommunication- - ndComm = new ndCommunication- -();
Vector<- -> vecData = vecResult;
ndComm.setDataCompressed(c_fUseCompressionForTransfer);
ndComm.setData(vecData);
result = ndComm;
}
}
}
// compress vector results on request
else if (fVectorResult && c_fUseCompressionForTransfer)
{
// -> we have to encapsulate the data in a special communication
// -> - - which has to be used for these purposes (compression)
ndCommunication- - ndComm = new ndCommunication- -();
Vector<- -> vecData = vecResult;
ndComm.setDataCompressed(c_fUseCompressionForTransfer);
ndComm.setData(vecData);
result = ndComm;
}
return (result);
}
/**
* Special method to handle multi block data transfer - this method
* fetches the next data block which is part of a vector.
*/
protected ndCommunication- - getNextDataBlock(ndCommunication- - ndComm) throws GeneralException
{
Vector<?> vecData = new Vector<- ->();
ndComm.setMoreDataAvailable(VectorStore.getNextBlockFromVector(ndComm.getAccessKey(),
vecData,
c_iMaxBlockSize));
ndComm.setDataCompressed(c_fUseCompressionForTransfer);
ndComm.setData(vecData);
return (ndComm);
}
...
И этот класс ndServlet вызывается в том коде, который я Вам показал выше, но только 1 раз:
GeneralServerAdapter_Servlet.setDefaultServletClass(ndServlet.class);
В остальном он используется только для репортов.
куки не передаете
Ява-консоль пишет, что соединение с куками:
network: Connecting http://.../servlet.jar with cookie
network: Connecting http:/.../jakarta-oro-2.0.jar with cookie
security: Checking if certificate is in Deployment session certificate store
security: Checking if SSL certificate is in Deployment permanent certificate store
security: Possible use of Secure cookies blocked for
security: To use secure cookie (HTTPS), consider signing the application or host application with HTTPS
security: Possible use of Secure cookies blocked for https://.../servlet/de.novadata.pp.servlet.ndServlet
network: Connecting http://.../servlet/de.novadata.pp.servlet.ndServlet with cookie "JSESSIONID=A4C73477D9C1B454F601463D8C5F07A1"
Но у себя на компе я ни одного куки на эту темку не нашел
Я у шефа спрашивал, он сказал, что 100% по IP
И 100% томкатовская HttpSession? Эт врядли.
Да и как еще, если всегда одна сессия на рыло?
Легко и ненапряжно 100500-ми способами. Кто ж знает что у вас используется, ни кода ни конфигурации я пока что не увидел.
Ванговать не надо, sendRequest(- -) у меня выше описан Как и про пароль с логином.
ну так посмотрите на этот метод, который вызывает sendRequest и передает ему пароль с логином. Может это User.logon(...) делает? Или все работает исключительно через GeneralServerAdapter_Servlet.doRequest(ServerTransferObject)?
Это будет сторона клиента (апплета) Мне интересно что происходит на стороне сервера (сервлета).
sendRequest посылает данные на URL, который хранится в поле m_servlet. Проверьте что именно этот метод используется для общения с сервлетом. С каким URL-ем он открывает соединение? Что именно шлет серверу? Дебаггер или просто систем.аутов понапихайте.
У сервлета должен вызываться метод doPost(...)
Найдите у себя класс, который extends HttpServler (или у вас своя реализация интерфейса Servlet? тогда implements Servlet) и посмотрите что же он делает c входящими данными.
Может, у вас как-то кусками копируется текст, и ndServlet все же extend HttpServlet? Еще раз спрашиваю - вы вообще смотрите что и как вставляете? Это же понять невозможно... ndServlet.doPost оборвался в середине метода. Что происходит после
if (session.getAttribute(KEY_BINDING_LISTENER) != this)
session.setAttribute(KEY_BINDING_LISTENER, this);
else
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
У вас в логи выводится session got: xxxxxxx (на 01.09.2015 12:27:23 DCC_4 (25) I: request for access key: 540C407B5B9122D19AFC1588C2A49579 не похоже) из
showInfo("session got: " + session.getId());
?
Какой там ID? Постоянно при каждом запросе тот же самый?
P.S. Вставляйте код в тэги [pre][/pre]
Тебе Мурр и Сандерс верно написали - нет решения на клиенте - только на сервере.
Что у тебя за серверное ява-приложение - м б какой фреймворк стоит что то вроде спринга или гвт или что другое.
Вообще раскрой подробно задачу - ибо те объемы кода что ты постишь как то ни фига на решение не похоже. Почти в любом норм. ява фреймворке есть стандартное управление сессиями.
А не то что ты нагородил.
Как сишник не подскажешь решение проблемки
http://foren.germany.ru/postlist.pl?Cat=&Board=programmer&page=0&view=collapsed&...
Кстати чего в диполе не появляешься? устал от ....даков аленей и курбанов с лешиками и юнонками? (пты и мой оппонент)
Кстати чего в диполе не появляешься?
Во-первых, хамства не люблю, типа вот этого:
несусветное наворотил
нагородил
Во-вторых, больше мне делать нечего, как с ДК-шными модерами-ублюдками бодаться, да плюс к тому еще с "добровольными помощниками милиции" вроде отсоса Курбана, ты его с его гнилой "аргументацией" вежливо мокнул, а он с помощью своей подружки-училки тут же натянул на себя презик Модератора1 и в бан тебя на неделю. Такого маразма даже на ДК в его худшие времена не бывало.
Вообще раскрой подробно задачу - ибо те объемы кода что ты постишь как то ни фига на решение не похоже.
Задачу я давно уже раскрыл, кроме тебя все ее тут давно уже поняли.
Код я пощу, когда просят.
Никаких решений я этим кодом не предлагал, это уже имеющийся код, а если б у меня было решение, я б сюда не полез, короче, сначала разберись, потом помогай

Как сишник не подскажешь решение проблемки
http://foren.germany.ru/postlist.pl?Cat=&Board=programmer&page=0&view=collapsed&...
Доска "Программирование" является для тебя проблемкой?

Как то так делается
public String getIpAddress(String host) {
try {
ifcfg = NetworkInterface.getByName(host);
addresses = ifcfg.getInetAddresses();
while (addresses.hasMoreElements()) {
address = addresses.nextElement().toString();
address = address.replace("/", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return ifcfg.toString();
}
И дальше сравнивай с IP уже зашедших юзеров
http://foren.germany.ru/programmer/f/28923558.html?Cat=&page=0&view=collapsed&sb...
мой вопрос
Легко и ненапряжно 100500-ми способами. Кто ж знает что у вас используется, ни кода ни конфигурации я пока что не увидел.
Не понял. Я ведь запостил код сервлета, который Вы просили, а что еще надо?
ну так посмотрите на этот метод, который вызывает sendRequest и передает ему пароль с логином. Может это User.logon(...) делает?
Это doRequest(ServletTransfer- - obj) делает.
Или все работает исключительно через GeneralServerAdapter_Servlet.doRequest(ServerTransfer- -)?
Да.
Это будет сторона клиента (апплета) Мне интересно что происходит на стороне сервера (сервлета).
sendRequest посылает данные на URL, который хранится в поле m_servlet. Проверьте что именно этот метод используется для общения с сервлетом. С каким URL-ем он открывает соединение? Что именно шлет серверу? Дебаггер или просто систем.аутов понапихайте.
Да, пришлось понапихать, поскольку Эклипс с сервлетом не работает:
m_servlet2: http://sv........com:8160/ICM6/servlet/de.novadata.pp.servlet.ndServlet
in = sendRequest(obj);
System.out.println("doRequest2: doRequest: " + in):
doRequest2: doRequest: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@396c7
System.out.println("doRequest3: doRequest: " + obj);
doRequest3: doRequest: de.novadata.pp.base- -s.ServletTransfer- -@5f3bad
У сервлета должен вызываться метод doPost(...)
Дык и вызывается:
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
Найдите у себя класс, который extends HttpServler (или у вас своя реализация интерфейса Servlet? тогда implements Servlet) и посмотрите что же он делает c входящими данными.
Нет, extends, я ж постил уже:
public class ndServlet extends HttpServlet implements SingleThreadModel,
HttpSessionBindingListener
Может, у вас как-то кусками копируется текст, и ndServlet все же extend HttpServlet? Еще раз спрашиваю - вы вообще смотрите что и как вставляете? Это же понять невозможно... ndServlet.doPost оборвался в середине метода. Что происходит после
if (session.getAttribute(KEY_BINDING_LISTENER) != this)
session.setAttribute(KEY_BINDING_LISTENER, this);
else
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
Привожу конец эту методу с этого места и до конца:
if (session.getAttribute(KEY_BINDING_LISTENER) != this)
session.setAttribute(KEY_BINDING_LISTENER, this);
else
showInfo("ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this");
// save the Prefix to be used for server communication from this servlet
setServerNamePrefix(objTransfer.getServerNamePrefix());
if (objAdapter instanceof GeneralServerAdapter)
{
GeneralServerAdapter adapt = (GeneralServerAdapter)objAdapter;
adapt.setServerNamePrefix(this.getServerNamePrefix());
}
// set current sessionid in Adapter as the access key
if (objAdapter instanceof GeneralServerAdapter_RMI)
{
GeneralServerAdapter_RMI adapt = (GeneralServerAdapter_RMI)objAdapter;
adapt.setAccessKey(session.getId());
showInfo("ndServlet.doPost, SessionID(access key) set: " + session.getId());
// also use the session id as request id
adapt.setRequestId(session.getId());
// the adapter should handle special communication issues
// in case the servlet should also do it on its own
adapt.setHandleSpecialCommunication(c_fSpecialCommunicationSupport);
}
AnalyzeSupport timeSup2 = new AnalyzeSupport();
showInfo("ndServlet.doPost, Method: " + met.getName());
objResult = met.invoke(objAdapter, params);
timeSup2.showTimeUsage("ndServlet.doPost RMI-Invocation-Time:");
}
else
{
// special communication
showInfo("getNextDataBlock...");
objResult = this.getNextDataBlock((ndCommunication- -)objTransfer.getData- -());
}
if (objResult != null)
{
// now build the response - -
objTransfer.setData- -((Serializable)this.getResult- -(objResult));
// ...and send it back to the requestor
response.setContentType("java-internal/" + objResult.getClass().getName());
}
else
{
objTransfer.setData- - (null);
response.setContentType("java-internal/null");
}
// now write the - - to the response output stream
this.write- -(response, objTransfer);
timeSup.showTimeUsage("PP_Servlet Request-Time:");
}
catch (Throwable e)
{
GeneralException ex;
if (e instanceof GeneralException)
ex = (GeneralException)e;
else
ex = new GeneralException(e);
// ...and send it back to the requestor
response.setContentType("text/html");
ServletTransfer- - objTransfer = new ServletTransfer- -();
objTransfer.setData- -(new Vector<- ->());
objTransfer.setException(ex);
// now write the - - to the response output stream
this.write- -(response, objTransfer);
}
}
У вас в логи выводится session got: xxxxxxx (на 01.09.2015 12:27:23 DCC_4 (25) I: request for access key: 540C407B5B9122D19AFC1588C2A49579 не похоже) из
showInfo("session got: " + session.getId());
Тут я сначала херню написал, прошу пардонов.
Просто это место на консоль не выводится, но есть в томкатовском логе:
05.09.2015 02:57:25 I: PP_Servlet (02:57:25):ndServlet.doPost, Method: getAttentionLogs
at de.novadata.pp.servlet.ndServlet.doPost(ndServlet.java:231)
05.09.2015 02:57:38 I: PP_Servlet (02:57:38):ndServlet.doPost, getAttribute(KEY_BINDING_LISTENER) <> this
05.09.2015 02:57:38 I: PP_Servlet (02:57:38):ndServlet.doPost, SessionID(access key) set: 10C7257FBFB48F1755DDEC4A20194520
System.out.println("session got: " + session.getId());
09.09.2015 16:59:27 I: PP_Servlet (16:59:27):session got: 596099E13516A03E708161FEE9B16F99
session got: 596099E13516A03E708161FEE9B16F99
P.S. Cлово "<\Object>" тут почему-то не перевариваривается из него делается "- -". Там, где эта фигня встречается, надо читать ее как <Обжект>. \[/pre] тоже где-то выполняется, где-то нет.