springboot

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. 创建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. 创建模板文件:在src/main/resources/templates目录下创建FreeMarker模板文件(例如example.ftl)。

  2. 创建Controller:创建一个Controller类用于接收请求,并在请求处理方法中使用FreeMarker生成文件,例如:

@Controller
public class FileController {

    @Autowired
    private Configuration configuration;

    @GetMapping("/generate")
    public ResponseEntity<Resource> generateFile() throws Exception {
        // 获取模板
        Template template = configuration.getTemplate("example.ftl");
        
        // 创建数据模型
        Map<String, Object> data = new HashMap<>();
        data.put("name", "John Doe");
        data.put("age", 30);

        // 创建输出流
        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类获取模板对象,并将数据模型填充到模板中,最后使用ByteArrayResource返回生成的文件。

  1. 访问生成文件:启动Spring Boot应用,访问http://localhost:8080/generate即可生成文件并下载。

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

0
看了该问题的人还看了