【问题标题】:Spring MVC + Thymeleaf: adding variable to all templates' contextSpring MVC + Thymeleaf:将变量添加到所有模板的上下文中
【发布时间】:2015-07-19 05:39:49
【问题描述】:

如何添加一个“全局”变量,例如用户名,以便在我的模板上下文中使用?

目前我正在为我的 TemplateController 中的每个 ModelAndView 对象显式设置这些。

【问题讨论】:

    标签: java spring-mvc thymeleaf


    【解决方案1】:

    这是 Spring Boot 和 Thymeleaf 的示例。

    首先,我们需要创建一个@ControllerAdvice

    @ControllerAdvice
    public class MvcAdvice {
    
        // adds a global value to every model
        @ModelAttribute("baseUrl")
        public String test() {
            return HttpUtil.getBaseUrl();
        }
    }
    

    现在,我们可以在模板中访问baseUrl

    <span th:text=${baseUrl}></span>
    

    【讨论】:

      【解决方案2】:

      @ControllerAdvice为我工作:

      @ControllerAdvice(annotations = RestController.class)
      public class AnnotationAdvice {
      
           @Autowired
           UserServiceImpl userService;
      
           @ModelAttribute("currentUser")
           public User getCurrentUser() {
               UserDetails userDetails = (UserDetails) 
               SecurityContextHolder.getContext()
                     .getAuthentication().getPrincipal();
      
            return userService.findUserByEmail(userDetails.getUsername());
           }
        }
      

      【讨论】:

        【解决方案3】:

        如果您只是想将 application.properties 中的某些内容添加到您的 thymeleaf 模板中,那么您可以使用 Spring 的 SpEL

        ${@environment.getProperty('name.of.the.property')}
        

        【讨论】:

          【解决方案4】:

          有几种方法可以做到这一点。

          如果你想为单个控制器服务的所有视图添加一个变量,你可以添加一个 @ModelAttribute 注释方法 - see reference doc

          请注意,您也可以使用相同的@ModelAttribute 机制,一次寻址多个控制器。为此,您可以在使用 @ControllerAdvice - see reference doc 注释的类中实现 @ModelAttribute 方法。

          【讨论】:

            【解决方案5】:

            你可能想看看@ModelAttribute。 http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

            块引用 在 Thymeleaf 中,可以使用以下语法访问这些模型属性(或 Thymeleaf 术语中的上下文变量):${attributeName},在我们的例子中,attributeName 是消息。这是一个 Spring EL 表达式。

            【讨论】:

              猜你喜欢
              • 2023-03-25
              • 1970-01-01
              • 2018-09-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-10-18
              • 1970-01-01
              • 2011-05-20
              相关资源
              最近更新 更多