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>
相关推荐
_F_y3 小时前
C++重点知识总结
java·jvm·c++
打工的小王3 小时前
Spring Boot(三)Spring Boot整合SpringMVC
java·spring boot·后端
毕设源码-赖学姐3 小时前
【开题答辩全过程】以 高校体育场馆管理系统为例,包含答辩的问题和答案
java·spring boot
我真会写代码3 小时前
SSM(指南一)---Maven项目管理从入门到精通|高质量实操指南
java·spring·tomcat·maven·ssm
vx_Biye_Design3 小时前
【关注可免费领取源码】房屋出租系统的设计与实现--毕设附源码40805
java·spring boot·spring·spring cloud·servlet·eclipse·课程设计
DN金猿3 小时前
接口路径正确,请求接口却提示404
java·tomcat
Maynor9964 小时前
OpenClaw 玩家必备:用 AI 自动追踪社区最新动态
java·服务器·人工智能
堕2744 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
亓才孓4 小时前
[Class的应用]获取类的信息
java·开发语言
开开心心就好4 小时前
AI人声伴奏分离工具,离线提取伴奏K歌用
java·linux·开发语言·网络·人工智能·电脑·blender