【问题标题】:views in thymeleaf spring boot templates sub folderthymeleaf spring boot templates 子文件夹中的视图
【发布时间】:2017-07-23 11:57:56
【问题描述】:

我在 spring boot 中使用 thymeleaf,并且有几个视图。我不想将所有视图保存在默认情况下为 src/main/resources/templates 的同一文件夹中。

是否可以移动 src/main/resources/templates/folder1 中的一些视图,我将通过 "folder1/viewname" 来访问该页面?

当我尝试http://localhost:8080/folder1/layout1 时,它没有在 src/main/resources/templates/folder1/ 中找到我的 html,但是当我将 html 移动到模板主文件夹 src/main/resources/templates/ 中时,http://localhost:8080/layout1工作正常。

我的控制器类看起来像:

@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
    return pagename;
}

所以,我想如果我通过 layout1,它会在模板中查找,如果我说“a/layout1”,它将在 /layout 文件夹中查找

谢谢, 马尼什

【问题讨论】:

  • 你试过了吗?
  • 是的,但没有奏效。我现在已将其添加到问题中。
  • 简短的回答是:可以,但这取决于您的 spring-boot 应用程序设置。我在 spring-mvc 中配置了类似的东西。您可能需要在 spring-boot 应用程序中配置视图解析器。为您的问题添加更多细节肯定会有所帮助。
  • 你的控制器方法是什么样的?请添加更多代码。
  • 刚刚添加了控制器代码

标签: spring spring-mvc spring-boot thymeleaf


【解决方案1】:

基本上,您的请求映射和视图名称是解耦的,您只需要注意语法即可。

例如,与

@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
    return "layout1";
}

http://localhost:8080/foobar 的请求将呈现位于src/main/resources/templates/layout1.html 中的模板。

如果您将模板放在子文件夹中也可以使用,只要您提供正确的视图路径:

@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
    return "a/layout1";
}

http://localhost:8080/foobar 的请求将呈现位于src/main/resources/templates/a/layout1.html 中的模板。

您还可以使用@PathVariable 参数化 url 端点:

@RequestMapping(value = "/foobar/{layout}", method = RequestMethod.GET)
    public String mf42_layout1(@PathVariable(value = "layout") String layout) { // I prefer binding to the variable name explicitely
        return "a/" + layout;
    }

现在对http://localhost:8080/foobar/layout1 的请求将呈现src/main/resources/templates/a/layout1.html 中的模板,而对http://localhost:8080/foobar/layout2 的请求将呈现src/main/resources/templates/a/layout2.html 中的内容

但要注意正斜杠充当 URL 中的分隔符,因此使用控制器:

@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
    return pagename;
}

我的猜测是当你点击http://localhost:8080/a/layout1 pagename 收到“a”并且“layout1”没有被捕获。所以控制器可能会尝试渲染src/main/resources/templates/a.html的内容

Spring MVC reference 详细描述了如何映射请求,您应该仔细阅读。

【讨论】:

    【解决方案2】:

    在 Linux 服务器中运行应用程序时,我遇到了类似的模板未找到问题。我将路径用作“return”/a/layout1。这在本地 Windows PC 中运行良好,但我必须删除起始“/”以使其在 Linux 机器中工作(即“return”a/layout1 ")。

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2014-11-21
      • 2021-09-14
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2017-02-25
      • 2017-04-14
      • 2020-07-30
      相关资源
      最近更新 更多