要将 url 参数解码为颜色,我使用此 HttpMessageConverter:
public class ColorHttpMessageConverter implements HttpMessageConverter<Color> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return clazz == Color.class;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return clazz == Color.class;
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return Collections.singletonList(MediaType.ALL);
}
@Override
public Color read(Class<? extends Color> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
byte[] buff = new byte[6];
if (inputMessage.getBody().read(buff) != buff.length) {
throw new HttpMessageNotReadableException("Must read 6 bytes.");
}
String c = new String(buff);
return Color.decode("#" + c);
}
@Override
public void write(Color t, MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(Integer.toHexString(t.getRGB()).substring(2).getBytes());
}
}
然后我编写一个具有以下映射的休息 Controller :
@Transactional
@RequestMapping("a.jpg")
public ResponseEntity<BufferedImage> getA(Color textcolor) throws IOException {
我调用 URL http://localhost:8080/myapp/rest/a.jpg?textcolor=ffffff
但我在控制台中只得到这个:
No primary or default constructor found for class java.awt.Color
有什么想法吗?
最佳答案
HttpMessageConverter
它有一个完全不同的目的,是将 body 转化为其他东西(反之亦然)。你想要的是 Converter<String, Color>
反之亦然,因为您想要将请求参数而不是正文转换为 Color
。
public class StringToColorConverter implements Converter<String, Color> {
public Color convert(String color) {
return Color.decode("#" + color);
}
}
反之亦然
public class ColorToStringConverter implements Converter<Color,String> {
public String convert(Color color) {
return Integer.toHexString(color.getRGB()).substring(2);
}
}
现在您可以使用 WebMvcConfigurer
注册它们
@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToColorConverter()):
registry.addConverter(new ColorToStringConverter()):
}
}
现在,当该方法参数的类型为 Color
时,应该使用转换器。检测到。
关于java - Color HttpMessageConverter 但缺少 Color 的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56559581/