小程序可以与 servlet 的实例通信吗 [英] Can an applet communicate with an instance of a servlet

查看:28
本文介绍了小程序可以与 servlet 的实例通信吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Http(不是套接字)与 servlet 通信的小程序.目前,小程序的每个实例(即,当每个小程序由不同计算机上的不同客户端运行时),所有实例都与同一个 servlet 通信.我想要的是applet 的每个实例与相同servlet 的不同实例进行通信.这可能吗?

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?

推荐答案

您不希望在 web 应用程序的生命周期中具有相同 servlet 的不同实例.通常的做法是使用 HttpSession 来区分客户端.您需要通过 HttpSession#getId() 作为相关小程序的参数:

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}">

然后,在 Applet 中连接 Servlet,如下所示:

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();
// ...

这里servleturl显然应该匹配web.xml中servlet的url-pattern.您也可以使用 URLConnection.setRequestProperty() 设置 Cookie 请求标头.

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

最后,在 Servlet 中,要获取和存储客户端特定的数据,请执行以下操作:

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");

希望这会有所帮助.

这篇关于小程序可以与 servlet 的实例通信吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆