我正在玩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是一个应用程序范围的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会话调用新用户加入的servlet时,我在第一次调用时就会得到这个响应(如预期的那样):
“您好,您的ID是:,这里还有1位玩家”
在同一会话中重复相同的servlet调用会给我相同的消息:
“您好,您的ID是:,这里还有两位玩家”
...
看起来用户会话状态的新实例正在一次又一次地创建。我做得对吗?
编辑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);
}