溫馨提示×

springboot中freemarker怎么生成文件

小億
151
2024-05-24 10:33:20
欄目: 編程語言

在Spring Boot中使用FreeMarker生成文件的步驟如下:

  1. 添加FreeMarker依賴:在pom.xml文件中添加FreeMarker的依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  1. 創(chuàng)建FreeMarker配置類:新建一個配置類用于配置FreeMarker的模板路徑和其他配置:
@Configuration
public class FreeMarkerConfig {

    @Autowired
    private Environment env;

    @Bean
    public FreeMarkerConfigurationFactoryBean freeMarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        bean.setTemplateLoaderPath("classpath:/templates");
        Properties settings = new Properties();
        settings.setProperty("template_update_delay", "0");
        settings.setProperty("default_encoding", "UTF-8");
        settings.setProperty("locale", "zh_CN");
        settings.setProperty("number_format", "0.##########");
        settings.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
        settings.setProperty("date_format", "yyyy-MM-dd");
        settings.setProperty("boolean_format", "true,false");
        settings.setProperty("time_format", "HH:mm:ss");
        settings.setProperty("whitespace_stripping", "true");
        settings.setProperty("auto_import", "ftl/common/common.ftl as common,ftl/common/functions.ftl as fun");
        settings.setProperty("url_escaping_charset", "UTF-8");
        settings.setProperty("output_format", "HTMLOutputFormat");
        settings.setProperty("tag_syntax", "auto_detect");
        settings.setProperty("template_exception_handler", "rethrow");
        settings.setProperty("classic_compatible", "true");
        bean.setFreemarkerSettings(settings);
        return bean;
    }

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() throws IOException {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setConfiguration(freeMarkerConfiguration().getObject());
        return configurer;
    }

    @Bean
    public FreeMarkerViewResolver freeMarkerViewResolver() {
        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(false);
        resolver.setSuffix(".ftl");
        resolver.setContentType("text/html; charset=UTF-8");
        resolver.setRequestContextAttribute("request");
        resolver.setExposeSpringMacroHelpers(true);
        return resolver;
    }

}
  1. 創(chuàng)建模板文件:在src/main/resources/templates目錄下創(chuàng)建FreeMarker模板文件(例如example.ftl)。

  2. 創(chuàng)建Controller:創(chuàng)建一個Controller類用于接收請求,并在請求處理方法中使用FreeMarker生成文件,例如:

@Controller
public class FileController {

    @Autowired
    private Configuration configuration;

    @GetMapping("/generate")
    public ResponseEntity<Resource> generateFile() throws Exception {
        // 獲取模板
        Template template = configuration.getTemplate("example.ftl");
        
        // 創(chuàng)建數(shù)據(jù)模型
        Map<String, Object> data = new HashMap<>();
        data.put("name", "John Doe");
        data.put("age", 30);

        // 創(chuàng)建輸出流
        StringWriter writer = new StringWriter();
        template.process(data, writer);

        // 生成文件
        byte[] bytes = writer.toString().getBytes();
        ByteArrayResource resource = new ByteArrayResource(bytes);
        
        return ResponseEntity.ok()
                .contentLength(bytes.length)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

}

在上述代碼中,使用Configuration類獲取模板對象,并將數(shù)據(jù)模型填充到模板中,最后使用ByteArrayResource返回生成的文件。

  1. 訪問生成文件:啟動Spring Boot應用,訪問http://localhost:8080/generate即可生成文件并下載。

通過以上步驟,您可以在Spring Boot中使用FreeMarker生成文件。

0