问题描述
我正在创建一个连接到Web服务器的Swing应用程序,运行一些servlet(由我自己创建)。在用户第一次连接时,他得到一个playerID,保存在servlet上的会话中。当我尝试从Swing应用程序再次调用servlet时,似乎无法识别PlyaerID。我正在进行简单的调用以获取PlayerID。 servlet识别这种类型的请求并发送带有playerID的JSON,如果它没有设置(null),则发送为-1。 swing应用程序总是从servlet获得-1回复。我尝试从浏览器运行它,一切都很好。
I'm creating a Swing application that connects to a web server, running some servlets (created by myself). On the 1st time a user connects, he get a "playerID" that is saved on his session on the servlets. When I try to make another call from the Swing application to the servlet, the "PlyaerID" seems not to be recognized. I'm making a simple call to get the PlayerID. The servlets recognize this type of request and send a JSON with the "playerID" and if it is not set (null) than it sends -1. The swing application always getting the "-1" reply from the servlet. I tried running it from a browser and everything was just fine.
我的Swing客户端是否有可能无法发出请求,并且会话不会保存在servlet上?
Is it possible that my Swing client can not make a request and a session will not be saved on the servlet?
我可以肯定地告诉你,与servlet通信的swing方法效果很好。
I can tell you for sure that the swing method that communicate with the servlet works well.
推荐答案
servlet会话由cookie支持。您基本上需要从第一个请求的响应中获取所有 Set-Cookie
标头,然后传递 name = value
成对后续请求的 Cookie
标头。
The servlet session is backed by a cookie. You basically need to grab all Set-Cookie
headers from the response of the first request and then pass the name=value
pairs back as Cookie
header of the subsequent requests.
目前还不清楚您使用的是哪个HTTP客户端,但是如果它的,然后你可以使用。
It's unclear what HTTP client you're using, but if it's java.net.URLConnection
, then you could use the java.net.CookieHandler
for this.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
参见:
- - 维护会话
- Using java.net.URLConnection to fire and handle HTTP requests - Maintaining the session
- How do servlets work? Instantiation, sessions, shared variables and multithreading
See also:
这篇关于从swing应用程序到servlet进行http调用,会话未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!