今儿的Web项目中突然报错:
HttpMediaTypeNotAcceptableException: Could not find acceptable representation
涉及接口是
@RequestMapping(value = "/X/XX/", produces = "text/plain;charset=UTF-8")//
@ResponseBody
public String XXX(ModelAndView view, String XXX) {
return “”;
}
通过日志分析,return前均正常执行,且该部分代码本期未作改动,前期代码运行OK。
在网上查该异常的原因主要是jackson jar的缺少所致,但查询POM,jackson加载正常。
那必定和本期所加代码相关。本期却有其他功能代码加入,但功能代码均彼此独立,公用的只有配置代码,即:
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public void configureMessageConverters(List
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "html", UTF8)));
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "xml",
UTF8)));
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "json",
UTF8)));
converters.add(stringConverter);
}
仔细看代码 突然发现原本添加4中MediaType,其实最后生效的也只有一种,即最后一种,ResponseBody按次执行后,JS那边虽有收到返回数据,但因格式问题无法处理,因此报错404.后修改如下:
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public void configureMessageConverters(List
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
List
list.add(new MediaType("text", "plain", UTF8));
list.add(new MediaType("text", "html", UTF8));
list.add(new MediaType("application", "xml",UTF8));
list.add(new MediaType("application", "json",UTF8));
stringConverter.setSupportedMediaTypes(list);
//stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
//stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "html", UTF8)));
//stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "xml",
// UTF8)));
//stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "json",
// UTF8)));
converters.add(stringConverter);
}
运行Ok