【发布时间】:2015-11-27 20:13:52
【问题描述】:
我的控制器中有以下图片下载方法(Spring 4.1):
@RequestMapping(value = "/get/image/{id}/{fileName}", method=RequestMethod.GET)
public @ResponseBody byte[] showImageOnId(@PathVariable("id") String id, @PathVariable("fileName") String fileName) {
setContentType(fileName); //sets contenttype based on extention of file
return getImage(id, fileName);
}
下面的ControllerAdvice方法应该处理一个不存在的文件并返回一个json错误响应:
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Map<String, String> handleResourceNotFoundException(ResourceNotFoundException e) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put("error", e.getMessage());
return errorMap;
}
我的 JUnit 测试完美无缺
(EDIT这是因为扩展 .bla :这也适用于 appserver):
@Test
public void testResourceNotFound() throws Exception {
String fileName = "bla.bla";
mvc.perform(MockMvcRequestBuilders.get("/get/image/bla/" + fileName)
.with(httpBasic("test", "test")))
.andDo(print())
.andExpect(jsonPath("$error").value(Matchers.startsWith("Resource not found")))
.andExpect(status().is(404));
}
并给出以下输出:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Content-Type=[application/json]}
Content type = application/json
Body = {"error":"Resource not found: bla/bla.bla"}
Forwarded URL = null
Redirected URL = null
Cookies = []
但是在我的应用服务器上,当我尝试下载不存在的图像时收到以下错误消息:
(编辑这是因为扩展 .jpg :这在带有 .jpg 扩展的 JUnit 测试中也失败):
ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public java.util.Map<java.lang.String, java.lang.String> nl.krocket.ocr.web.controller.ExceptionController.handleResourceNotFoundException(nl.krocket.ocr.web.backing.ResourceNotFoundException)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
我在我的 mvc 配置中配置了 messageconverters,如下所示:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//objectMapper.registerModule(new JSR310Module());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
converter.setSupportedMediaTypes(getJsonMediaTypes());
return converter;
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getImageMediaTypes());
return arrayHttpMessageConverter;
}
我错过了什么?为什么 JUnit 测试有效?
【问题讨论】:
-
检查您的请求的“接受”标头(“真实”标头,对应用服务器)。它是否同时接受 image/* 和 application/json?如果它只接受 image/* 那么 Spring 不能生成 JSON 消息,因为它与请求接受的内容不兼容。
-
我有以下内容:Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
-
我该如何改变?添加到消息转换器 (
setSupportedMediaTypes)? -
客户端在期待图像时接收 JSON 是否可能/有用?通常在请求图像时,错误响应代码是客户端需要的所有信息(例如,在 Web 应用程序中)。尝试调试抛出异常的位置,可能是
AbstractMessageConverterMethodProcessor#writeWithMessageConverters()、RequestMappingInfoHandlerMapping#handleNoMatch或ServletHandlerMethodInvoker#writeWithMessageConverters -
我可以在我的 ajax 调用中处理 404 响应以显示错误消息而不是图像,所以那里没有问题。错误是从
AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:134)抛出的
标签: java spring spring-mvc junit