在Spring Boot中使用FreeMarker生成文件的步驟如下:
pom.xml
文件中添加FreeMarker的依賴:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
@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;
}
}
創建模板文件:在src/main/resources/templates
目錄下創建FreeMarker模板文件(例如example.ftl
)。
創建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
返回生成的文件。
http://localhost:8080/generate
即可生成文件并下載。通過以上步驟,您可以在Spring Boot中使用FreeMarker生成文件。