21 Ekim 2019 Pazartesi

SpringMVC AbstractHttpMessageConverter Sınıfı

Giriş
Açıklaması şöyle
10. How to Create a Custom Implementation of the HttpMessageConverter to Support a New Type of Request/Response?
You just need to create an implementation of the AbstractHttpMessageConverter and register it using the WebMvcConfigurerAdapter#extendMessageConverters() methods with the classes that generate a new type of request/response.
writeInternal metodu
Örnek
Açıklaması şöyle.
You have to keep in mind that in our example, the defined HTTP message converter will always be applied when the handler method returns the value of type Team (see the supports method), and HTTP Accept header matches "application/vnd.ms-excel".
Şöyle yaparız
@Service
public class TeamToXlsConverter extends AbstractHttpMessageConverter<Team> {
  private static final MediaType EXCEL_TYPE =
    MediaType.valueOf("application/vnd.ms-excel");

  TeamToXlsConverter() {
    super(EXCEL_TYPE);
  }

  @Override
  protected Team readInternal(Class<? extends Team> clazz,
    HttpInputMessage inputMessage)
    throws IOException, HttpMessageNotReadableException {
    return null;
  }

  @Override
  protected boolean supports(Class<?> clazz) {
    return (Team.class == clazz);
  }

  @Override
  protected void writeInternal(Team team, HttpOutputMessage outputMessage)
    throws IOException, HttpMessageNotWritableException {

    try (Workbook workbook = new HSSFWorkbook()) {
      ...
      workbook.write(outputMessage.getBody());
    }
  }
}

Hiç yorum yok:

Yorum Gönder