首页 > 解决方案 > Thymeleaf StringTemplateResolver 所有变量 null

问题描述

我正在尝试创建一个概念验证 Spring Boot 应用程序,该应用程序利用 Thymeleaf 根据属性和请求参数填充字符串结构。我让它使用模型实现工作,但只有在填充的模板是响应时才有效。在这种情况下,我希望在项目中使用填充的模板。



@Controller
@RequestMapping("/poc")
public class InfoController {
    @Autowired
    ThymeleafService thymeleafService;

    @Value("${reportType}")
    private String reportType;

    // This function works - the reportType variable is populated based upon application.properties
    @GetMapping("/map")
    public String testMap(@RequestParam(name = "id", required = false, defaultValue = "2")
                                          String id, Model model){

        model.addAttribute("reportType", "\"" + reportType  + "\"");
        return id + ".json";
    }

    // this function does not work - the reportType variable is null
    @RequestMapping(value = "/map2",method= RequestMethod.POST)
    public String testMap2(@RequestBody MapRequest request, @RequestParam(name = "id", required = false, defaultValue = "2")
            String id, Model model) {
        String output = thymeleafService.processTemplate(request, id);
        return output;


    }
}

ThymeleafService 非常简单。

@Component
public class ThymeleafService {

    @Value("${reportType}")
    private String reportType;

    private TemplateEngine templateEngine;

    public String processTemplate(MapRequest request, String templateId){
        templateEngine = new TemplateEngine();
        StringTemplateResolver resolver = new StringTemplateResolver();
        resolver.setTemplateMode(TemplateMode.TEXT);
        templateEngine.addTemplateResolver(resolver);
        // Map<String, Object> attributes = new HashMap<>();
        final Context ctxt = new Context(Locale.US);
        ctxt.setVariable("reportType", "\"" + reportType  + "\"");
   //     for (String name : ctxt.getVariableNames()){
////            attributes.put(name, ctxt.getVariable(name));
//        }
        TemplateSpec templateSpec = new TemplateSpec(templateId + ".json", null, TemplateMode.TEXT, attributes);

        StringWriter writer = new StringWriter();
        templateEngine.process(templateSpec, ctxt, writer);

        return writer.toString();
    }
}

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.poc</groupId>
    <artifactId>map</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mappoc</name>
    <description>POC</description>

    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

这是模板:

    ReportType: [(${reportType})]

我最终从地图上得到的是:

ReportType: "configReportType"

但我最终从 map2 得到的是:

ReportType: 

我试过在函数中设置属性Context,有和没有。我尝试过使用 a并尝试只使用一个字符串作为模板名称。AttributeMapTemplateEngine.processTemplateSpec

我已经调试了代码并确认 reportType 变量正在设置并传递给process函数。但由于某些超出我的原因,它实际上并没有将数据注入响应中。我觉得我错过了一些非常明显的东西,但我想不通。任何帮助将不胜感激。

注意:我不能只使用模型范式的原因是因为现在它将数据返回给调用者,最终目标是使用该数据。

标签: javaspringspring-bootthymeleaf

解决方案


我终于设法让这个工作 - 诀窍是我必须:

  • 使用ClassLoaderTemplateResolver代替StringTemplateResolver
  • 将控制器中的响应从更改StringResponseEntity
  • Model从控制器签名中删除

推荐阅读