gpt4 book ai didi

java - getThreadLocalRequest().getSession(false) 始终为 null

转载 作者:行者123 更新时间:2023-12-01 15:48:41 24 4
gpt4 key购买 nike

我在尝试代码登录+cookies时遇到一些问题..当用户登录时我创建 session

getThreadLocalRequest().getSession(true)

当我想检查 session 是否仍然存在时总是返回 null

HttpSession session = getThreadLocalRequest().getSession(false);    
if (session != null) {
}

当我检查 HttpRequest 时(当我检查 session Activity 时),这有

Cookie: JSESSIONID=a1042a8e-9ebc-45b8-a3d8-12161885be96

cookie 没问题。

我使用Eclipse+开发模式

服务器端代码:

public String login(String rut, String pass) throws AuthenticationException {
//if UserPassMatch ...

session = this.getThreadLocalRequest().getSession(true);
//set user bean
session.setAttribute("beanSession", us);

HttpServletResponse response = getThreadLocalResponse();
Cookie usernameCookie = new Cookie("JSESSIONID", us.getSessionID());
usernameCookie.setPath("/");
usernameCookie.setMaxAge(60 * 60 ); //1 hora
response.addCookie(usernameCookie);


}

@Override
public String checkIfSessionStillActive(String token) {

HttpServletRequest request = getThreadLocalRequest();
//Here ALWAYS return null
HttpSession session = request.getSession(false);

if (session != null) {
//check sessionId and search User Bean
}

return token;
}

从客户端来说,没有什么特别的,只需调用 checkIfSessionStillActive 来检查 session 是否存在,然后抛出 token ,如果不存在则转到登录。当用户登录时仍然返回session NULL。我使用 MVP 模式,从 AppController 调用,并使用相同的 rpcService。用户登录后,我检查 session 及其是否存在,但如果我调用 checkIfSessionStillActive,则找不到任何 session 。真的,我读了很多代码,我发现它几乎是一样的,请问有什么可以帮助我吗?

最佳答案

您是否使用扩展RemoteServiceServlet的子类并调用在其他地方(例如在spring上下文中)创建的对象并扩展了RemoteServiceServlet?如果是的话以下将解决您的问题

对于每个请求,都会创建一个新的 RemoteServiceServlet 实例。问题是 RemoteServiceServlet 父类(super class)中定义的线程局部变量不是静态的,因此对于每个对象都有不同的变量。当您在上述场景中处理调用时,您的请求响应线程局部变量会为接收的对象进行初始化,但不会为您调用方法的对象设置内容。

我使用了一种解决方法,通过创建一个具有静态线程本地变量的类并在调用第二个对象之前设置值。现在 swcond 对象也可以访问它们。

关于java - getThreadLocalRequest().getSession(false) 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6575185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com