我正在玩w / EE并希望保持用户会话状态。我在这里有会话bean:
@Stateful(mappedName = "UserSessionState")
@Named("UserSessionState")
@SessionScoped
@StatefulTimeout(value = 5, unit = TimeUnit.MINUTES)
public class UserSessionState implements Serializable
{
private boolean hasPlayerId = false;
private String playerId = "";
public void setRandomPlayerId()
{
playerId = UUID.uuid();
hasPlayerId = true;
}
public boolean hasPlayerId()
{
return hasPlayerId;
}
public String getPlayerId()
{
return playerId;
}
}
这里有一个servlet(GameState是一个按预期工作的Application Scoped bean,CustomExtendedHttpServlet只是HttpServlet的一个简单扩展)
public class NewUserJoined extends CustomExtendedHttpServlet
{
@Inject
protected GameState gameState;
@Inject
protected UserSessionState user;
@Override
protected String doGetImpl(HttpServletRequest request, HttpServletResponse response, UserContext userLoginContext)
{
if (!user.hasPlayerId())
{
user.setRandomPlayerId();
}
String userId = user.getPlayerId();
if (!gameState.hasUser(userId))
{
gameState.addUser(userId, user);
return "Hi, your ID is: " + user.getPlayerId() + ", there are " + gameState.getUserCount() + " other players here";
}
else
{
return user.getPlayerId() + " you're already in the game, there are: " + gameState.getUserCount() + " other players here";
}
}
}
我不确定发生了什么,但每当我从同一个HTTP会话调用New User Joined servlet时,我会在第一次调用时得到此响应(如预期的那样):
“嗨,你的身份证是:,这里还有其他1名球员”
在同一个会话中重复相同的servlet调用会给出相同的消息: “嗨,你的身份证是:,这里还有其他2名球员” ...
看起来像是一次又一次地创建用户会话状态的新实例。我这样做了吗?
编辑1:这里是我用来发送请求的代码。看来我正在为每个请求获得一个新的会话ID,这可能是什么原因?
RequestCallback callback = new RequestCallback()
{
@Override
public void onResponseReceived(Request request, Response response)
{
log(response.getText());
}
@Override
public void onError(Request request, Throwable exception)
{
log(
"Response Error | "
+ "Exception: " + exception);
}
};
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, SERVLET_URL);
rb.setCallback(callback);
try
{
rb.send();
}
catch (RequestException e)
{
log("Response Error | "
+ "Exception: " + e);
}
答案 0 :(得分:1)
找出问题,
原来我在GWT客户端有一个旧的解决方法,正在更改主机以解决CORS问题。由于响应与原点不匹配,因此未将cookie与未来的servlet GET调用一起发送。
答案 1 :(得分:0)
您是否尝试过调用request.getSession(true)以确保在此处建立EE HTTPSession?