如何在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";
}
}
我的测试用例:
- 打开主页
- 自动重定向到包含密码格式的页面
输入密码
- 自动重定向到主页,全部好,页面打开
- 刷新页面
- 获取需求密码
答案 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";
}