【问题标题】:How to store URLs in properties file and access them in templates using Spring and Thymeleaf如何将 URL 存储在属性文件中并使用 Spring 和 Thymeleaf 在模板中访问它们
【发布时间】:2016-01-21 21:22:55
【问题描述】:

我正在尝试使用 Spring Boot 和 Thymeleaf 创建一个简单的导航栏,其中包含指向其他网站/服务器的链接。我想将这些 URL 存储在我的“application.properties”中并通过 th:href 访问它们。当我尝试访问它们时,它不会将我重定向到此 URL。

这里是 HTML:

<li class="dropdown-submenu">
    <a tabindex="-1" href="#">Menu</a>
    <ul class="dropdown-menu">
        <li><a th:href="#{foo.bar}">Selection 1</a></li>

在 application.properties 中:

foo.bar=http://www.example.com

【问题讨论】:

    标签: html spring spring-boot thymeleaf


    【解决方案1】:

    /#{foo.bar} 应该指向 MessageSouce 中的一个值,该值不是由配置填充的(即 Spring Boot 中的 application.properties),而是查看 MessageSource 文件(即 Spring Boot 中的 messages.properties)。这将使您的模板保持不变。

    否则,如果您在配置中有 foo.bar 并且不希望复制该属性,您可以像这样注入 foo.bar

    //在控制器类中

    @Value("${foo.bar}")
    String myUrl;
    
    @RequestMapping("/mine")
    public ModelAndView viewWithFooBarLink() {
        ModelAndView mav = new ModelAndView("templateWithFooBarReference"):
        mav.put("linkRef", myUrl);
        return mav;
    }
    

    你的看法

    <li class="dropdown-submenu">
            <a tabindex="-1" href="#">Menu</a>
            <ul class="dropdown-menu">
              <li><a th:href="${linkRef}">Selection 1</a></li>
    

    此信息的良好参考。 http://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

    【讨论】:

      【解决方案2】:

      事实证明这个符号是有效的:

      <li class="dropdown-submenu">
      <a tabindex="-1" href="#">Menu</a>
      <ul class="dropdown-menu">
          <li><a th:href="@{${@environment.getProperty('foo.bar')}}>Selection 1</a></li>
      

      【讨论】:

      • 今天我也工作了${@environment.getProperty('foo.bar')}
      猜你喜欢
      • 2021-03-15
      • 1970-01-01
      • 2014-03-10
      • 2023-03-12
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      相关资源
      最近更新 更多