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>