java springboot 解决FreeMarker数字输出中的逗号问题

发布于:2024-06-17 ⋅ 阅读:(21) ⋅ 点赞:(0)

在Java中使用FreeMarker模板引擎时,如果遇到数字输出包含千位分隔符(逗号)的问题,可以通过以下三种方法解决:

方法1:在表达式中使用转换器

        直接在模板中的数字表达式后加上?c转换器,这会使得数字以标准的数字格式(无千位分隔符)输出。

例如:

${data.id?c}

        这里的?c是FreeMarker的一个内建转换器,它会将数字格式化为不带千位分隔符的形式。

方法2:修改FreeMarker配置

        如果你希望全局地改变数字的输出格式,避免每次都要在表达式后添加转换器,可以在FreeMarker的配置中设置number_format。

        这通常在初始化FreeMarker时完成,例如在Spring MVC的配置中:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

@Configuration
public class FreeMarkerConfig {

    @Bean
    public freemarker.template.Configuration freeMarkerConfiguration() throws TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        // 设置FreeMarker的目录路径,这里假设你的模板位于resources/templates下
        configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "templates");
        // 关闭默认的数字格式化,即不添加千位分隔符
        configuration.setNumberFormat("#");
        return configuration;
    }
}

        在这里,setNumberFormat("#")将数字格式设置为不包含千位分隔符的形式。

        #是一个格式字符串,指示FreeMarker以最紧凑的形式输出数字,不包含任何分隔符。

        确保应用这些配置更改后,FreeMarker在输出数字时将不再自动添加逗号作为千位分隔符。

方法3:更新Spring Boot配置

        如果使用的是Spring Boot 2.4及以上版本,并且使用了spring-boot-starter-freemarker starter,那么可以直接在application.properties或application.yml中配置FreeMarker的设置。

        例如:

spring:
  freemarker:
    number-format: '#'

这段配置同样会使得FreeMarker在输出数字时不添加千位分隔符。