ColorHttpMessageConverter但缺少Color的默认构造函数

时间:2019-06-12 10:07:16

标签: java spring spring-web jackson-databind

要解码颜色为颜色的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());
    }

}

然后,我编写一个具有此映射的rest-controller:

@Transactional
@RequestMapping("a.jpg")
public ResponseEntity<BufferedImage> getA(Color textcolor) throws IOException {

我调用了网址http://localhost:8080/myapp/rest/a.jpg?textcolor=ffffff,但在控制台中却只有这个:

No primary or default constructor found for class java.awt.Color

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

HttpMessageConverter的用途完全不同,它是将身体转化为其他事物的过程(反之亦然)。您想要的是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的方法参数时,应使用转换器。