我正在使用一个控制器,该控制器可将数据提取的CSV下载提供给我的用户,并且基于以下非常有用的文章,我有一个对象,控制器和HttpMessageConverter:https://stackoverflow.com/a/9961748/613559

我的CsvResponse对象:

public class CsvResponse {
    private final String filename;
    private final List<Object[]> records;
    private final List<String> columns;

    public CsvResponse(List<Object[]> records, List<String> columns, String filename) {
        this.records = records;
        this.filename = filename;
        this.columns = columns;
    }
    public String getFilename() {
        return filename;
    }
    public List<Object[]> getRecords() {
        return records;
    }
    public List<String> getColumns() {
        return columns;
    }
}


我的控制器:

@RequestMapping(value="/download", method = RequestMethod.POST, produces = "text/csv")
public @ResponseBody CsvResponse download (@RequestParam("jsonData") String jsonData) throws IOException {
    // populate dataset and columns, removed for simplicity

    return new CsvResponse(dataset, columns, "download_" + new SimpleDateFormat("yyyy.MM.dd_HH:mm:ss").format(new Date()) + ".csv");
}


我的HttpMessageConverter:

public class CsvMessageConverter extends AbstractHttpMessageConverter<CsvResponse> {
    public static final MediaType MEDIA_TYPE = new MediaType("text", "csv", Charset.forName("utf-8"));
    public CsvMessageConverter() {
        super(MEDIA_TYPE);
    }

    protected boolean supports(Class<?> clazz) {
        return CsvResponse.class.equals(clazz);
    }

    protected void writeInternal(CsvResponse response, HttpOutputMessage output) throws IOException, HttpMessageNotWritableException {
        OutputStream out;
        CsvWriter writer;
        List<Object[]> dataset;

        output.getHeaders().setContentType(MEDIA_TYPE);
        output.getHeaders().set("Content-Disposition", "attachment; filename=\"" + response.getFilename() + "\"");
        out = output.getBody();
        writer = new CsvWriter(new OutputStreamWriter(out), '\u0009');
        dataset = response.getRecords();
        for(Object[] datasetRow : dataset) {
            for(Object cell : datasetRow) {
                writer.write((cell instanceof String) ? "\"" + cell.toString() + "\"" : cell.toString());
            }
            writer.endRecord();
        }
        writer.flush();
        writer.close();
    }

    @Override
    protected CsvResponse readInternal(Class<? extends CsvResponse> type, HttpInputMessage him) throws IOException, HttpMessageNotReadableException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}


访问下载控制器时,出现错误消息org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation。调试显示未访问CsvMessageConverter。如果从控制器中删除produces = "text/csv"段,则会得到CsvResponse对象的JSON字符串表示形式(对于@ResponseBody批注而言是正确的),因此其余代码可以正常工作。我认为这里只是缺少一些非常简单的东西,但是整天把头撞在墙上之后,我仍然看不到它。我需要更改什么才能使服务器使用CsvMessageConverter

最佳答案

您应该通过将此块添加到spring-mvc.xml来注册csv转换器

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="com.xxx.utils.CsvMessageConverter"></bean>
    </mvc:message-converters>
</mvc:annotation-driven>


我写了一个例子,它可以工作。

10-06 03:37