Java 作为变量传递时无法解析Thymeleaf片段,即<;分区th:replace="${page}"&燃气轮机;

Java 作为变量传递时无法解析Thymeleaf片段,即<;分区th:replace="${page}"&燃气轮机;,java,spring,web-services,spring-mvc,thymeleaf,Java,Spring,Web Services,Spring Mvc,Thymeleaf,我正在用sping mvc 4.2.2和thymeleaf-spring4 2.1.2构建一个web应用程序,并且大多数页面共享相同的标题、侧栏等。因此,我决定只有一个视图(.html),它将替换子div,这取决于url中的参数页面 控制器将页面名称转换为片段名称: //SpringTestHello.java @Controller public class SpringTestHello { @RequestMapping("/test") public Stri

我正在用sping mvc 4.2.2和thymeleaf-spring4 2.1.2构建一个web应用程序,并且大多数页面共享相同的标题、侧栏等。因此,我决定只有一个
视图(.html),它将替换子
div
,这取决于url中的参数
页面

控制器将页面名称转换为片段名称:

//SpringTestHello.java
@Controller
public class SpringTestHello {      
    @RequestMapping("/test")
    public String testMap(@RequestParam(value="page", required=false, defaultValue="overview") String page, Model model) {
        if (page.equalsIgnoreCase("overview"))
            page = "overview :: overview";
        if (page.equalsIgnoreCase("user"))
            page = "overview :: user";
        model.addAttribute("page", page);       
        return "main_page";
    }
}
主页面将用
page
属性替换子div:

<!--main_page.html-->
<div id="pageContent" th:if="${!page.isEmpty()}" 
    th:replace="${page}">Main Content here</div>
<!--This causes exception-->
使用字符串文字时,效果与预期一致:

<!--main_page.html-->
<div id="pageContent" th:replace="overview :: overview"></div>
<!--This shows the correct fragment-->

当片段名称作为参数传递时,为什么它无法解析模板?

您应该在replace语句中预处理()
${page}
,以便它发生在任何其他处理之前,从而允许正确包含片段

您的替换将变成(请注意,
${page}
周围的双下划线):

这里的主要内容

我还建议您看一看非常适合您当前使用情形的,即使用一些标准内容装饰不同的页面。

这非常有效!谢谢在阅读了相关内容后,我还将切换到布局方言
<!--main_page.html-->
<div id="pageContent" th:replace="overview :: overview"></div>
<!--This shows the correct fragment-->
<div id="pageContent" th:if="${!page.isEmpty()}"
    th:replace="__${page}__">Main Content here</div>