gpt4 book ai didi

java - @Autowired HttpSession 不保存简单的字符串 - SpringBoot

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:42 25 4
gpt4 key购买 nike

我有一个简单的 SpringBoot RestController:

@RestController
public class PasswordController implements ErrorController {

private static final String ERROR_PATH = "/error";
public static final String IS_USER_LOGGED_IN = "isUserLoggedIn";
public static final String BAD_REQUEST_MESSAGE = "Bad Request ¯\\_(ツ)_/¯";

@Autowired
private PasswordService passwordService;

@Autowired
private HttpSession httpSession;

@RequestMapping(value = "/user/create/{name}/{password}", method = RequestMethod.GET)
public String createNewUserAndPassword(@PathVariable final String name, @PathVariable final String password) {
try {
return passwordService.createNewUserAndPassword(name, password);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
return ERROR_PATH;
}
}

@RequestMapping(value = "user/login/{name}/{password}", method = RequestMethod.GET)
public String loginUser(@PathVariable final String name, @PathVariable final String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
// return passwordService.loginUser(name, password);
final String result = passwordService.loginUser(name, password);
if (result.contains(PasswordService.WELCOME_MESSAGE)) {
this.httpSession.setAttribute("name", name);
}
return result;
}

@Override
public String getErrorPath() {
return ERROR_PATH;
}

@RequestMapping("/error")
public String error() {
return BAD_REQUEST_MESSAGE;
}

@RequestMapping(value = "getEnemies", method = RequestMethod.GET)
public String getEnemies() {
if (this.httpSession.getAttribute("name") != null) {
return "enemies List....";
} else {
return "(ง'̀-'́)ง";
}
}
}

如您所见,这非常简单,但是我在这里保存的字符串:

this.httpSession.setAttribute("name", name)

只要它始终为空,就可以永远在这里检索:

this.httpSession.getAttribute("name") != null

我调试了代码,您可以在set之后立即检索字符串。但是,当它到达其他方法时,它不会在 HttpSession 对象更改时起作用。 (它甚至还有另一个 ID)

可能是什么问题?谢谢

最佳答案

当您指的是其他方法时假设其他处理程序(getEnemies())

是的,对象发生了变化,因为它们都是在不同线程上运行的不同休息调用。我不确定您注入(inject)的 HttpSession 对象的根可能是什么,但您在其中存储的内容可能不是持久的(可能是该线程本地的)。这就是使您在另一个方法中获得空值的原因。

关于java - @Autowired HttpSession 不保存简单的字符串 - SpringBoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282674/

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