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

标签 java spring spring-boot autowired httpsession

我有一个简单的 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/

相关文章:

java - 在 MongoDb Morphia 中如何删除或替换数组对象

java - 为 Spring Data/hibernate 中的实体获取异常

docker - Spring Boot 应用程序独立运行良好,在 docker 中出错

java - HTTP 请求等待任务完成

java - @Where注解无法解析

java - 使用 GIT 的 IDEA 新 gradle spring boot 项目。正确的创建顺序是什么?

java - 使用 JVM 8 时 MySQL Java 连接器无法初始化

java - Android 文本文件导入

java - 正则表达式检查是否有句子

spring - 如何在 Spring 3 中的 Controller 内生成 URI