You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用中Freemarker将Long转为带空格字符串,如何解决?

Spring+Freemarker中Long类型渲染出现千分位空格问题的原因与解决方法

问题描述

在Spring应用中使用Freemarker时遇到异常:Freemarker会将Long类型转换为带千分位空格的字符串。例如分类id为1029,在HTML中被渲染成"1 029",出现在<a href="/categories/update/1 029">和<td>1 029</td>中,预期结果应为无空格的"1029"。数据库中Id列类型为Bigint。

相关代码片段

Categories.ftl 部分代码

<#list categories as category>
<tr>
    <td>
        <div class="btn btn-group-sm" role="group">
            <a class="btn btn-outline-primary" href="/categories/update/${category.id}">Update</a>
            <form action="/categories/delete/${category.id}" method="POST">
                <button class="btn btn-outline-danger" type="submit">Delete</button>
            </form>
        </div>
    </td>
    <td>${category.id}</td>
    <td>${category.title}</td>
    <td>${category.createdDate}</td>
    <td>${category.modifiedDate}</td>
    <td>${category.user.username}</td>
</tr>
</#list>

Controller 代码

@GetMapping("")
public ModelAndView getCategoriesPage(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("categories");

    modelAndView.addObject("categories", categoryService.findAll());
    // 从数据库获取分类数据

    return modelAndView;
}

Category.java 代码

@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    /* 其他字段 */
}

问题原因

Freemarker默认会根据当前应用的**区域设置(Locale)**对数字类型(包括Long、BigInteger等)进行格式化。如果应用使用的Locale是需要千分位分隔的地区(如英语系、部分欧洲地区),数字会被自动添加空格或逗号作为千分位分隔符,导致1029被渲染成"1 029"。

解决方法

方法1:模板内强制转为无格式字符串

在Freemarker模板中,使用内置指令?c将数字转为无格式的纯字符串,保留原始数字形式:
修改后的ftl代码片段:

<a class="btn btn-outline-primary" href="/categories/update/${category.id?c}">Update</a>
<form action="/categories/delete/${category.id?c}" method="POST">
    <button class="btn btn-outline-danger" type="submit">Delete</button>
</form>
<!-- 表格中的id同步修改 -->
<td>${category.id?c}</td>

方法2:全局配置禁用数字格式化

在Spring配置文件中设置Freemarker的数字格式为无格式输出:
如果使用application.properties:

spring.freemarker.settings.number_format=0

如果使用Java配置类:

@Configuration
public class FreemarkerConfig {
    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates/");
        Properties settings = new Properties();
        // 设置数字格式为无千分位的纯数字
        settings.setProperty("number_format", "0");
        configurer.setFreemarkerSettings(settings);
        return configurer;
    }
}

方法3:设置Locale为无千分位分隔的地区

将应用的Locale设置为中文(如zh_CN),中文环境下数字默认不会添加千分位分隔符:
在application.properties中添加:

spring.freemarker.settings.locale=zh_CN

内容的提问来源于stack exchange,提问作者Kirill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:11:29