我将 Thymeleaf 与 Springboot2.1.2 结合使用,但在访问模板中的 session 属性时遇到问题。
代码如下:
这是 Controller 之一:
@GetMapping("/profile")
public String getProfile(HttpServletRequest request) {
HttpSession session = request.getSession(false);
String email = (String) session.getAttribute("userId");
User user = userService.getProfile(email);
session.setAttribute("user", user);
return "user/profile";
}
以及相应的 View (html):
<body th:object="${session.user}">
//some code using the user object here...
</body>
当我运行应用程序时,出现异常:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'session' available as request attribute
我也尝试过#session 和其他东西,但没有成功。但是,在另一个 Controller 中,我可以使用模型访问该对象:
@GetMapping("/register/user")
public String registerUser(Model model) {
model.addAttribute("user", new User());
return "user/register";
}
View 如下:
<form th:object="${user}" method="post" action="#" th:action="@{/register/user}">
//some code using the user object...
</form>
这让我发疯,因为我能找到的所有教程都告诉我可以通过 ${session.something}
访问 session 属性,但实际上,它不起作用。
你能帮我吗?
最佳答案
您正在 session 中保存信息,thymeleaf 不可见。您需要为 thymeleaf 模板创建一个模型,并将属性(或 session )添加到模型中,然后返回该模型。
@GetMapping("/profile")
public ModelAndView getProfile(HttpServletRequest request) {
User user = userService.getProfile(email);
ModelAndView model = new ModelAndView(NAME_OF_THYMELEAF_PROFILE_FILE);
model.addObject("user",user);
return model;
}
请注意, thymeleaf 要查看模板,它需要位于默认路径(资源/模板)中,或者您需要定义模板的存储位置。
如果您想再次使用 session ,解决方案类似。
@GetMapping("/profile")
public ModelAndView getProfile(HttpServletRequest request) {
HttpSession session = request.getSession(false);
User user = userService.getProfile(email);
session.setAttribute("user", user);
ModelAndView model = new
ModelAndView(NAME_OF_THYMELEAF_PROFILE_FILE);
model.addObject("session",session);
return model;
}
更新使用模型并返回字符串:
@GetMapping("/profile")
public String getProfile(HttpServletRequest request, Model model) {
HttpSession session = request.getSession(false);
String email = (String) session.getAttribute("userId");
User user = userService.getProfile(email);
session.setAttribute("user", user);
model.addAttribute("session", session);
return "user/profile";
}
我使用了ModelAndView
,您可以对Model
执行相同的操作,只是必须使用addAttribute()
而不是addObject()
。
关于java - 无法访问 Thymeleaf 中的 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54627089/