@Autowired HttpSession没有保存简单的String - SpringBoot

时间:2017-05-31 10:47:28

标签: 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)

只要始终为null,永远就可以在此处检索

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

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

可能是什么问题?感谢

1 个答案:

答案 0 :(得分:0)

假设其他处理程序(getEnemies())意味着其他方法

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

相关问题