Spring+Thymeleaf自定义Formatter

Thymeleaf 关于自定义转换的文档 Configuring a Conversion Service 中,是通过WebMvcConfigurerAdapter 来配置的,但是目前最新版的Spring Boot(V3.2.5),已经没有这个类了,得用 WebMvcConfigurationSupport 配置,比如实现一个自定义的 Formatter

FloatArrayFormatter.java

java 复制代码
package com.example.demo;

import java.text.ParseException;
import java.util.Locale;

import org.springframework.format.Formatter;

public class FloatArrayFormatter implements Formatter<float[]> {

    @Override
    public String print(float[] object, Locale locale) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < object.length; i++) {
            sb.append(String.valueOf(object[i]));
            if(i < object.length - 1) {
                sb.append(", ");
            }
        }
        return sb.toString();
    }

    @Override
    public float[] parse(String text, Locale locale) throws ParseException {
        return null;
    }

}

然后创建一个配置类(实现addResourceHandlers是为了让资源可用,本人测试的时候就出现了static目录下的bootstrap加载不了):

java 复制代码
package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("classpath:/resources/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);
        registry.addFormatter(floatArrayFormatter());
    }

	@Bean
	public FloatArrayFormatter floatArrayFormatter() {
		return new FloatArrayFormatter();
	}
}

创建一个页面

HomeController.java

java 复制代码
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;


@Controller
public class HomeController {

    @ModelAttribute
    public void setModel(Model model) {
        model.addAttribute("arr", new float[]{ 3.141592f, 5.2f });
    }

    @GetMapping("/")
    public String home() {
        return "home";
    }
    
}

html页面中使用两层大括号 ${{arr}} 来调用自定义的Formatter显示 float 数组

home.html

html 复制代码
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
      xmlns:th = "http://www.thymeleaf.org">
  <head>
    <link href="/bootstrap-5.3.3-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="/bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <div class="input-group">
        <textarea style="white-space: pre-wrap;" class="form-control" th:text="${{arr}}"></textarea>
    </div>
  </body>
</html>
相关推荐
好家伙VCC14 分钟前
**发散创新:基于Python与ROS的机器人运动控制实战解析**在现代机器人系统开发中,**运动控制**是实现智能行为的核心
java·开发语言·python·机器人
程途知微1 小时前
ConcurrentHashMap线程安全实现原理全解析
java·后端
Mars酱1 小时前
1分钟编写贪吃蛇 | JSnake贪吃蛇单机版
java·后端·开源
devpotato1 小时前
人工智能(四)- Function Calling 核心原理与实战
java·人工智能
默 语1 小时前
Records、Sealed Classes这些新特性:Java真的变简单了吗?
java·开发语言·python
zjshuster1 小时前
墨西哥中央银行网联清算系统接入总结
java·财务对账
小锋java12341 小时前
SpringBoot 4 + Spring Security 7 + Vue3 前后端分离项目设计最佳实践
java·vue.js·spring boot
一 乐1 小时前
校园线上招聘|基于springboot + vue校园线上招聘系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园线上招聘系统
不懂的浪漫1 小时前
mqtt-plus 架构解析(四):MqttMessageInterceptor 的扩展点设计
java·spring boot·物联网·mqtt
西海天际蔚蓝1 小时前
AI配合写的第一个demo系统页面
java·人工智能