Can an applet communicate with an instance of a servlet

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

I have an applet that communicates with a servlet using Http (Not sockets). Currently, each instance of the applet (i.e. when each applet is run by a different client on a different computer), all the instances communicate with the same servlet. What I want is that each instance of the applet communicate with different instances of the same servlet. Is this possible?

回答1:

You don't want to have different instances of the same servlet in webapp's lifetime. The normal practice is to use the HttpSession to distinguish between clients. You need to pass the HttpSession#getId() as parameter to the applet in question:

<param name="jsessionid" value="${pageContext.session.id}"> 

Then, in the Applet connect the Servlet as follows:

String jsessionid = getParameter("jsessionid"); URL servlet = new URL(getCodeBase(), "servleturl;jsessionid=" + jsessionid); URLConnection connection = servlet.openConnection(); // ... 

Here servleturl obviously should match servlet's url-pattern in web.xml. You can alternatively also set a Cookie request header using URLConnection.setRequestProperty().

Finally, in the Servlet, to get and store client specific data, do as follows:

// Store: request.getSession().setAttribute("data", data); // Get: Data data = (Data) request.getSession().getAttribute("data"); 

Hope this helps.



回答2:

From your question it seems that your servlet contains state. Every applet will have a session with the servlet container which your servlet can access. You can create an object that holds the state per session and place that object as attribute in the session of the caller. This way the servlet container is free to share one servlet instance among many clients.



回答3:

The usual way to handle instance-specific actions is to have information stored in the session scope made available by the servlet container, not by having information stored in the servlet itself.

For it to work, your applet must correctly send cookies or the JSESSIONID attribute as provided by the web container or the applet must request a instance specific URL inside the servlet.

I would suggest you familiarize yourself further with the Servlet API specification in order to learn more about what is available to you.

Also note that some application servers support the notion of "clients" which are programs invoked with code served from the application server which have direct access to the inside of the application server code. The actual communication is handled by libraries also provided by the applcation server so this is simple. Glassfish and Trifork can do this.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!