Thymeleaf StringTemplateResolver все переменные null - PullRequest
0 голосов
/ 02 октября 2019

Я пытаюсь создать концептуальное приложение 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, с AttributeMap и без * в функции TemplateEngine.process,Я попытался использовать TemplateSpec и попробовал просто строку для имени шаблона.

Я отладил код и подтвердил, что переменная reportType устанавливается и передается в функцию process. Но по какой-то причине, кроме меня, на самом деле это не внедрение данных в ответ. Я чувствую, что упускаю что-то действительно очевидное, но я не могу понять это. Любая помощь будет принята с благодарностью.

ПРИМЕЧАНИЕ: Причина, по которой я не могу просто использовать парадигму модели, заключается в том, что хотя сейчас она возвращает данные вызывающей стороне, конечной целью являетсяиспользовать эти данные.

1 Ответ

0 голосов
/ 03 октября 2019

Мне, наконец, удалось заставить это работать - хитрость была в том, что мне пришлось:

  • Использовать ClassLoaderTemplateResolver вместо StringTemplateResolver
  • Изменить ответ в контроллере сString до ResponseEntity
  • Удалить Model из подписи контроллера
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...