要将网址参数解码为彩色,请使用以下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


有任何想法吗?

最佳答案

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的方法参数时,应使用转换器。

10-07 17:01