如何更新Spring MVC中的会话属性

时间:2017-02-18 14:08:34

标签: spring session model-view-controller

如何在Spring MVC中更新会话属性?我试过这段代码:

@Controller
@RequestMapping("/panel")
@SessionAttributes({"access"})
public class AdminController extends ErrorsController {

private final static String SECURE_ADMIN_PASS = "123123";

@ModelAttribute("access")
public Boolean getAccess() {
    return false;
}

@RequestMapping(value = {"/", ""}, method = RequestMethod.GET)
public String adminGeneralPage(@ModelAttribute("access") boolean access) {
    if (!access) return "adminPages/enterPassword";
    return "adminPages/home";
}

@RequestMapping(value = "/password", method = RequestMethod.POST)
public String enterPassword(@ModelAttribute("access") boolean access,
                            @RequestParam("password") String password, HttpServletRequest request) {
    if (password.equals(SECURE_ADMIN_PASS)) {
        request.getSession().setAttribute("access", true);
        return "adminPages/home";
    }
    return "adminPages/enterPassword";
}

}

我的测试用例:

- 打开主页

- 自动重定向到包含密码格式的页面

输入密码

- 自动重定向到主页,全部好,页面打开

- 刷新页面

- 获取需求密码

1 个答案:

答案 0 :(得分:0)

更新您的enterPassword()方法,如下所示:

@RequestMapping(value = "/password", method = RequestMethod.POST)
public String enterPassword(HttpServletRequest request, Model model, @ModelAttribute("access") boolean access,
                            @RequestParam("password") String password) {
    if (password.equals(SECURE_ADMIN_PASS)) {
        model.addAttribute("access", true);
        return "adminPages/home";
    }
    return "adminPages/enterPassword";
}