在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生成文件。