Spring MVC - HttpMediaTypeNotAcceptableException
当与 Spring MVC 和 JSON 一起使用时,我不断收到 AJAX 请求的 HttpMediaTypeNotAcceptableException 错误。错误的完整堆栈跟踪是..
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.writeWithMessageConverters(AnnotationMethodHandlerAdapter.java:1032)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.handleResponseBody(AnnotationMethodHandlerAdapter.java:972)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:921)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:438)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:863)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:756)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
我做了一点谷歌搜索,显示请求应该包含类似“accept:application/json”的内容,这确实有..这是来自 firebug 的请求标头..
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 2503
Date Thu, 25 Aug 2011 21:00:05 GMT
Connection close
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20 (.NET CLR 3.5.30729)
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/legaldirectory/index.html
Cookie JSESSIONID=5C97DA19AED4D5FA17F4A58470FAA93B
现在我完全迷失了这里发生的事情..这里还有什么可能出错来得到这个错误...
I keep getting this HttpMediaTypeNotAcceptableException error for AJAX requests when using with Spring MVC and JSON.. full stack trace of the error is..
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.writeWithMessageConverters(AnnotationMethodHandlerAdapter.java:1032)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.handleResponseBody(AnnotationMethodHandlerAdapter.java:972)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:921)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:438)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:863)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:851)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:756)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
little googling I did shows that the request should contain something like "accept: application/json" which is does have.. here is the request headers from firebug..
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 2503
Date Thu, 25 Aug 2011 21:00:05 GMT
Connection close
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20 (.NET CLR 3.5.30729)
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/legaldirectory/index.html
Cookie JSESSIONID=5C97DA19AED4D5FA17F4A58470FAA93B
Now I am completely lost at what is happening here.. what else can go wrong here to get thi error...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
需要记住的重要一点是:3.1.2 之前的 Spring 版本与 JACKSON 1.x 兼容,但与 JACKSON 2.x 不兼容。这是因为从 JACKSON 1.x 到 2.x,类的包名称发生了变化。在 JACKSON 1.x 中,类位于 org.codehaus.jackson 下,而在 JACKSON 2.x 中,它们位于 com.fasterxml.jackson 下。
为了解决这个问题,从 Spring 3.1.2 开始,他们添加了一个新的 MappingJackson2HttpMessageConverter 来替换 MappingJacksonHttpMessageConverter。
您可以在此链接中找到有关兼容性问题的更多详细信息: Jackson 注释被忽略春天
Just something important to keep in mind: Spring versions prior to 3.1.2 are compatible with JACKSON 1.x and NOT with JACKSON 2.x. This is because going from JACKSON 1.x to 2.x the classes's package names were changed. In JACKSON 1.x classes are under org.codehaus.jackson while in JACKSON 2.x they are under com.fasterxml.jackson.
To address this issue, starting with Spring 3.1.2 they added a new MappingJackson2HttpMessageConverter to replace MappingJacksonHttpMessageConverter.
You could find more details regarding compatibility issues in this link: Jackson annotations being ignored in Spring
就我而言 favorPathExtension(false) 帮助了我
}
in my case favorPathExtension(false) helped me
}
例如,在扩展 WebMvcConfigurerAdapter 的 Spring @Configuration 类中,重写方法 configureMessageConverters:
错误就会消失。
In your Spring @Configuration class which extends WebMvcConfigurerAdapter override the method configureMessageConverters, for instance:
And the error will be gone.
我遇到了同样的问题,但我已经弄清楚,当 spring 尝试渲染响应时,基本上会发生什么,它会尝试根据您指定的媒体类型并通过在类中使用 getter 和 setter 方法来序列化它
在我的课程之前,它看起来像下面这样
解决方案看起来像下面
这就是它对我有用的方式
I had the same issue, but i had figured out that basically what happens when spring is trying to render the response it will try to serialize it according to the media type you have specified and by using getter and setter methods in your class
before my class used to look like below
solution looks like below
that's how it worked for me
尝试将“jackson-databind”jar 添加到 pom.xml
并生成 ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} 到 @RequestMapping
Es。
@RequestMapping(value = "/api/xxx/{akey}/{md5}", 生成 ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
@RequestMapping(value = "/api/contraassegno/{akey}/{md5}", 生成 ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},...
Try to add "jackson-databind" jars to pom.xml
And
produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
to @RequestMappingEs.
@RequestMapping(value = "/api/xxx/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
@RequestMapping(value = "/api/contrassegno/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},...
正如 Alex 在答案之一中暗示的那样,您可以使用 ContentNegotiationManagerFactoryBean 将默认内容类型设置为“application/json” ”,但我觉得这种方法不适合我。
我想做的是将表单发布到这样的方法,
而我选择做的是将浏览器请求的“Accept”标头更改为“application/json”,从而使 SpringMVC 找到我的方法。
使用(尚未最终确定)Javascript Fetch API:
瞧瞧!现在 SpringMVC 找到该方法,验证表单,并让您返回一个 JSON POJO。
As Alex hinted in one of the answers, you could use the ContentNegotiationManagerFactoryBean to set the default content-type to "application/json", but I felt that that approach was not for me.
What I was trying to do was to post a form to a method like this
What I instead chose to do was to change the "Accept" header of the request from the browser to "application/json", thereby making SpringMVC find my method.
Using the (not yet finalized) Javascript Fetch API:
Et voilà! Now SpringMVC finds the method, validates the form, and lets you return a JSON POJO.
就我而言,只需添加
@ResponseBody
注解即可解决此问题。In my case, just add
@ResponseBody
annotation to solve this issue.在我的例子中,
是由以下原因引起的:
path = "/path/{VariableName}"
但我传入带有后缀的 VariableName,例如“abc.xml”,这使得它将 .xml 解释为某种类型格式化请求。在那里查看答案。In my case
was caused by:
path = "/path/{VariableName}"
but I was passing in VariableName with a suffix, like "abc.xml" which makes it interpret the .xml as some kind of format request instead. See answers there.对我来说,问题在于我试图访问的 URL。我有这样的网址:
当您以 .html 结尾网址时,这意味着您不会接受除 html 之外的任何其他有效负载。我需要从末尾删除 .html 才能使我的端点正常工作。 (您也可以在 url 末尾附加 .json,它也可以工作)
此外,您在
web.xml
中的 url-pattern 需要正确配置,以允许您访问资源。对我来说,以前我有
*.html*
并且它阻止我访问端点。For me the problem was the URL I was trying to access. I had url like this:
When you end url with .html it means that you will not accept any other payload than html. I needed to remove .html from the end for my endpoint to work properly. (You can also append .json at the end of url and it will work too)
Additionally your url-pattern in
web.xml
need to be configured properly to allow you to access the resource. For me it isPreviously I had
*.html*
and it was preventing me an access to the endpoint.更多的是评论而不是答案...
我正在使用 Lombok,并且正在开发一个(非常)骨架 API,而我的响应 DTO 还没有任何字段,并且我收到了
HttpMediaTypeNotAcceptableException
运行集成测试时出错。向响应 DTO 添加一个字段解决了该问题。
More of a comment than an answer...
I'm using Lombok and I was developing a (very) skeleton API and my response DTO didn't have any fields (yet) and I got the
HttpMediaTypeNotAcceptableException
error while running my integration tests.Adding a field to the response DTO fixed the issue.
请确保您的 Spring xml 文件中包含以下内容:
并且 POJO 的所有项目都应该具有 getters/setters。
希望有帮助
Please make sure that you have the following in your Spring xml file:
and all items of your POJO should have getters/setters.
Hope it helps
从:
http://georgovassilis.blogspot.ca/2015/10/spring- mvc-rest-controller-says-406.html
你已经有了这个 Spring @RestController 并映射了一个 URL包含电子邮件作为 URL 路径的一部分。您巧妙地解决了点截断问题 [1],现在就可以开始了。突然间,在某些 URL 上,Spring 将返回 406 [2],表示浏览器请求某种内容类型,Spring 无法序列化对该内容的响应类型。关键是,您多年来一直在开发 Spring 应用程序,并且您正确地完成了所有 MVC 声明,并且包含了 Jackson,但基本上您陷入了困境。更糟糕的是,它只会在 URL 路径中的某些电子邮件上吐出该错误,尤其是那些以“.com”域结尾的电子邮件。
问题 [3] 非常棘手:应用程序服务器执行一些内容协商,并让 Spring 相信浏览器请求了一个“application/x-msdownload”内容,尽管发生了这种情况浏览器实际提交的请求中没有任何地方。
解决方案是为 Web 应用程序上下文指定一个内容协商管理器:
From:
http://georgovassilis.blogspot.ca/2015/10/spring-mvc-rest-controller-says-406.html
You've got this Spring @RestController and mapped a URL that contains an email as part of the URL path. You cunningly worked around the dot truncation issue [1] and you are ready to roll. And suddenly, on some URLs, Spring will return a 406 [2] which says that the browser requested a certain content type and Spring can't serialize the response to that content type. The point is, you've been doing Spring applications for years and you did all the MVC declarations right and you included Jackson and basically you are stuck. Even worse, it will spit that error out only on some emails in the URL path, most notably those ending in a ".com" domain.
The issue [3] is quite tricky: the application server performs some content negotiation and convinces Spring that the browser requested a "application/x-msdownload" content, despite that occurring nowhere in the request the browser actually submitted.
The solution is to specify a content negotiation manager for the web application context:
确保将两个 Jackson jar 添加到类路径中:
另外,您的 Spring xml 文件中必须包含以下内容:
Make sure you add both Jackson jars to classpath:
Also, you must have the following in your Spring xml file:
因为这是谷歌第一次点击“HttpMediaTypeNotAcceptableException”,所以我想添加另一个我偶然发现的问题,该问题也导致了 HttpMediaTypeNotAcceptableException。
就我而言,它是一个指定“产生”的控制器,例如:
因为我想提供 XML 文件。同时,我使用带有“@ControllerAdvice”的类来捕获异常,例如,如果未找到请求的文件。异常处理程序返回 JSON,以便客户端(角度)应用程序可以在 SPA 中的某处显示错误消息。
现在控制器想要返回 XML,但异常处理程序正在返回 JSON,因此引发了 HttpMediaTypeNotAcceptableException。我通过添加 JSON 尽可能“产生”值来解决这个问题:
希望这对其他人有帮助。 :-)
Because this is the first google hit for "HttpMediaTypeNotAcceptableException" I like to add another problem that I've stumbled upon which resulted in HttpMediaTypeNotAcceptableException too.
In my case it was a controller that specified "produces", e.g.:
because I wanted to serve an XML file. At the same time I'm using a class with "@ControllerAdvice" to catch Exceptions, e.g. if the requested file wasn't found. The Exception handler was returning JSON so the client (angular) app could display the error message somewhere in the SPA.
Now the controller wanted to return XML but the Exception Handler was returning JSON so the HttpMediaTypeNotAcceptableException was raised. I solved this by adding JSON as possible "produces" value:
Hope this helps somebody else. :-)