无法访问Thymeleaf中的会话属性

时间:2019-02-11 09:07:50

标签: java spring-boot thymeleaf

我在Springboot2.1.2中使用Thymeleaf,但是在访问模板中的会话属性时遇到问题。
以下是代码:

这是控制器之一:

@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";
}

以及相应的视图(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和其他方法,但是它们没有用。但是,在另一个控制器中,我可以使用Model来访问对象:

@GetMapping("/register/user")
public String registerUser(Model model) {
    model.addAttribute("user", new User());
    return "user/register";
}

视图就像:

<form th:object="${user}" method="post" action="#" th:action="@{/register/user}">
    //some code using the user object...
</form>

这让我发疯,因为我能找到的所有教程都告诉我可以通过${session.something}访问会话属性,实际上这是行不通的。
你能帮我吗?

2 个答案:

答案 0 :(得分:0)

您应该对 thymeleaf扩展使用 Spring-Security 来完成所需的工作。 example是您要执行的操作。如果您遵循该示例,则可以按以下方式访问用户信息:

<div sec:authentication="name"><!-- Display UserName Here --></div>

请注意,对于 spring-boot 2.1.X ,您应该使用以下依赖项:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

答案 1 :(得分:0)

您正在将信息保存在会话中,百里香叶看不到该信息。您需要为您的百里香模板创建一个模型,并将属性(或会话)添加到该模型中,然后将其返回。

@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;
}

请注意,要使百里香叶看到模板,它必须位于默认路径(资源/模板)中,否则您需要定义模板的存储位置。

如果您想再次使用会话,则解决方法类似。

@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做同样的事情,只是必须使用addObject()来代替addAttribute()