J'ai simple SpringBoot RestController:@Autowired HttpSession pas simple économie String - SpringBoot
@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 "(ง'̀-'́)ง";
}
}
}
Il est tout à fait simple que vous pouvez voir, mais la chaîne je sauve ici:
this.httpSession.setAttribute("name", name)
peut-jamais être récupéré ici aussi longtemps qu'il est toujours nulle:
this.httpSession.getAttribute("name") != null
J'ai débogué le code, et vous pouvez récupérer la chaîne immédiatement après le set
. Cependant, quand il atteint l'autre méthode, il ne fonctionnera pas à HttpSession
changements d'objet. (Il a même un autre ID)
Quel peut être le problème? Merci
Ne pas '@ Autowire' le' HttpSession' juste l'ajouter comme un argument de méthode à la place. –