java - Thymeleaf StringTemplateResolver 所有变量为 null

标签 java spring spring-boot thymeleaf

我正在尝试创建一个概念验证 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})]

我最终从 map 中得到的是:

ReportType: "configReportType"

但是我最终从map2得到的是:

ReportType: 

我尝试在 Context 中设置属性,无论是否在 TemplateEngine.process 函数中使用 AttributeMap。我尝试过使用 TemplateSpec 并尝试仅使用字符串作为模板名称。

我已经调试了代码并确认 reportType 变量已设置并传递到 process 函数中。但由于某种超出我范围的原因,它实际上并没有将数据注入(inject)到响应中。我觉得我错过了一些非常明显的东西,但我无法弄清楚。任何帮助将不胜感激。

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

最佳答案

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

  • 使用ClassLoaderTemplateResolver而不是StringTemplateResolver
  • 将 Controller 中的响应从 String 更改为 ResponseEntity
  • 从 Controller 签名中删除 Model

关于java - Thymeleaf StringTemplateResolver 所有变量为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192620/

相关文章:

java - 你能为许多项目制作一个集中的 build.gradle 吗?

java - 无法在 AlertDialog/LoginDialog 期间隐藏导航栏

java - Mock() vs Spy() vs Stub() 之间的 Spock 区别

java - 如何从正在测试的方法中读取 application.properties 中的变量

java - 发生org.springframework.beans.factory.UnsatisfiedDependencyException。但我没有改变任何东西

Java react 器通量未根据预期进行映射

java - 检测物体颜色各种光照OpenCV Java

javascript - JS $http.POST 方法 405 错误

java - 在没有 WebMvcConfigurationSupport 的情况下注册 Spring HandlerInterceptor

java - 类需要一个类型为 'java.lang.String' 的 bean,但无法找到