我有一个tomcat服务器,我用它作为一个restful服务器。
对于每个休息请求,我都需要提供一个 token 。提供 token 后,我将其存储在 session 中。问题是当我通过浏览器 url 检查某些请求时保存在 session 中的 token ,但是当我通过某些客户端(在我的例子中是 android 应用程序)执行此操作时,它总是创建新 session 。似乎来自同一客户端的每个请求都作为来自不同客户端的请求处理。
我需要在 tomcat 中配置一些东西吗?为什么我为同一个客户端获取新 session (当客户端不是浏览器时?
谢谢!
最佳答案
在第一次请求时,您的容器通常会告诉客户端通过这样的 header 设置 Cookie:
Set-Cookie: JSESSIONID=03f52fcdccdfd070be0ada8dw14b;
如果客户端想要加入这个 session ,他必须将这个 Cookie 与每个请求一起传回服务器。您的浏览器会自动为您执行此操作。其他客户端可能不会。 如果没有此 Cookie 信息,您的 Android 应用程序的每次调用对服务器来说都是新的。
将 Cookie 与 java.net.URLConnection 一起使用的简单示例
URLConnection connection = new URL(loginUrl).openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setDoOutput(true);
Map<String, String> formParams = new HashMap<String, String>();
formParams.put("username", "John"); // add your login Params
StringBuilder encodedParams = new StringBuilder();
for (Map.Entry<String, String> param : formParams.entrySet()) {
encodedParams
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append('=')
.append(URLEncoder.encode(param.getValue(), "UTF-8"));
}
OutputStream outputStream = connection.getOutputStream();
outputStream.write(encodedParams.toString().getBytes("UTF-8"));
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
String sessionCookie = null;
for (String cookie : cookies) {
if (cookie.startsWith("JSESSIONID")) {
sessionCookie = cookie.substring(0, cookie.indexOf(';')); // drop path, expires etc.
}
}
// reuse cookie for next page
connection = new URL(nextUrl).openConnection();
connection.addRequestProperty("Cookie", sessionCookie);
connection.getInputStream();
无关:Restful 应用程序通常是无状态的,意味着不基于 session 状态。
关于java - 不为非浏览器的设备保存 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23028899/