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>
相关推荐
Le1Yu4 分钟前
黑马商城微服务项目准备工作并了解什么是微服务、SpringCloud
java·微服务·架构
ZhengEnCi6 分钟前
🚀创建第一个 SpringBoot 应用-零基础体验开箱即用的神奇魅力
java·spring boot
宠友信息10 分钟前
仿小红书短视频APP源码:Java微服务版支持小程序编译的技术解析
java·微服务·音视频
努力努力再努力wz12 分钟前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
敲代码的嘎仔28 分钟前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
夜晚中的人海40 分钟前
【C++】智能指针介绍
android·java·c++
正在走向自律1 小时前
RSA加密从原理到实践:Java后端与Vue前端全栈案例解析
java·前端·vue.js·密钥管理·rsa加密·密钥对·aes+rsa
咯哦哦哦哦1 小时前
关于QT 打印中文 乱码问题
java·数据库·qt
爱读源码的大都督1 小时前
天下苦@NonNull久矣,JSpecify总算来了,Spring 7率先支持!
java·后端·架构
木头没有瓜2 小时前
Slf4j 接口文档左侧菜单有显示,但是点击后空白
java