Java spring mvc 不返回 json 内容 - 错误 406

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4069903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:15:08  来源:igfitidea点击:

spring mvc not returning json content - error 406

javajqueryspringspring-mvcHymanson

提问by serena

I am using Spring MVC with JSON as specified in Ajax Simplification Spring 3.0 article.

我正在使用 Spring MVC 和 JSON,如Ajax Simplification Spring 3.0 文章中所述

After so many attempts and variations of my code depending on advice found on various forums, my code still doesn't work.

根据在各种论坛上找到的建议对我的代码进行了多次尝试和修改后,我的代码仍然无法正常工作。

I keep on getting the following error: (406) The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().

我不断收到以下错误:(406)此请求标识的资源只能生成具有根据请求“接受”标头()不可接受的特征的响应。

I have in my appconfig.xml as required.

我根据需要在我的 appconfig.xml 中有。

app-config.xml

应用程序配置文件

    <context:component-scan base-package="org.ajaxjavadojo" />

    <!-- Configures Spring MVC -->
    <import resource="mvc-config.xml" />

mvc-config.xml

mvc-config.xml

<mvc:annotation-driven />

<!-- Forwards requests to the "/" resource to the "index" view -->
<mvc:view-controller path="/" view-name="index"/>


<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
  <entry key="html" value="text/html"/>
  <entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</list>
</property>

</bean>

This is what I have for my controller

这是我的控制器

@Controller
@RequestMapping (value = "/convert")
public class ConversionController {

  @RequestMapping(method=RequestMethod.GET)
  public String getConversionForm(){
    return "convertView";
  }

  @RequestMapping(value = "/working", headers="Accept=application/json", method=RequestMethod.GET)
  public @ResponseBody Conversion getConversion(){
    Conversion d = new Conversion("d");
    return d;
  }
}

jsp jquery call

jsp jquery 调用

  function convertToDecimal(){
    $.getJSON("convert/working", {key: "r"}, function(aConversion){
      alert("it worked.");
      $('#decimal').val(aConversion.input);
    });
  }

I would really appreciate any input on this issue. Thank you

我真的很感激关于这个问题的任何意见。谢谢

采纳答案by Bozho

Try remove the header limitation for Accept, put a breakpoint and see what's the actual value. Or do this with FireBug.

尝试删除 的标头限制Accept,放置一个断点并查看实际值是多少。或者使用 FireBug 执行此操作。

Also take a look at this jquery issue

也看看这个jquery问题

回答by axtavt

To return JSON response from @ResponseBody-annotated method, you need two things:

要从@ResponseBody-annotated 方法返回 JSON 响应,您需要做两件事:

You don't need ContentNegotiatingViewResolverand headersin @RequestMapping.

你不需要ContentNegotiatingViewResolverheaders@RequestMapping.

回答by Iceman

As said by axtavt, mvc:annotation-driven and Hymanson JSON mapper are all that you need. I followed that and got my application to return both JSON and XML strings from the same method without changing any code, provided that there are @XmlRootElement and @XmlElement in the object you are returning from the controller. The difference was in the accept parameter passed in the request or header. To return xml, any normal invocation from the browser will do it, otherwise pass the accept as 'application/xml'. If you want JSON returned, use 'application/json' in the accept parameter in request.

正如 axtavt 所说,mvc:annotation-driven 和 Hymanson JSON mapper 就是你所需要的。我遵循了这一点,并让我的应用程序从同一方法返回 JSON 和 XML 字符串,而无需更改任何代码,前提是您从控制器返回的对象中有 @XmlRootElement 和 @XmlElement。不同之处在于在请求或标头中传递的 accept 参数。要返回 xml,来自浏览器的任何正常调用都会执行此操作,否则将接受作为“application/xml”传递。如果您希望返回 JSON,请在请求的接受参数中使用“application/json”。

If you use firefox, you can use tamperdata and change this parameter

如果你使用firefox,你可以使用tamperdata并改变这个参数

回答by user320550

I too got this error and while debugging deep down into the rabbit hole i came across this exception

我也遇到了这个错误,在深入调试兔子洞时,我遇到了这个异常

java.lang.IllegalArgumentException: Conflicting getter definitions for property "error": com.mycomp.model.OutputJsonModel#isError(0 params) vs com.mycomp.model.OutputJsonModel#getError(0 params)

java.lang.IllegalArgumentException:属性“错误”的 getter 定义冲突:com.mycomp.model.OutputJsonModel#isError(0 params) vs com.mycomp.model.OutputJsonModel#getError(0 params)

So basically in my java bean i had something like the following:

所以基本上在我的 java bean 中,我有如下内容:

private boolean isError;
private ErrorModel error;

public ErrorModel getError() {
return error;
}

public void setError(ErrorModel error) {
this.error = error;
}
public boolean isError() {
return isError;
}

public void setError(boolean isError) {
this.isError = isError;
}

Changing one of the error member variable name to something else solved the issues.

将错误成员变量名称之一更改为其他名称解决了问题。

回答by Raju Rathi

issue is not related to jquery . even bug is saying it is server side issue . please make sure that following 2 jar present in class path :-

问题与 jquery 无关。甚至错误都说这是服务器端问题。请确保类路径中存在以下 2 个 jar:-

Hymanson-core-asl-1.9.X.jar Hymanson-mapper-asl-1.9.X.jar

Hymanson-core-asl-1.9.X.jar Hymanson-mapper-asl-1.9.X.jar

回答by Thomas

Add org.springframework.http.converter.json.MappingHymansonHttpMessageConverterand org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterto DispatcherServlet-servlet.xml. and refer to the the first one in the second using

org.springframework.http.converter.json.MappingHymansonHttpMessageConverter和添加org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter到 DispatcherServlet-servlet.xml。并使用第二个引用第一个

<bean id="HymansonMessageConverter" class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="HymansonMessageConverter"/>
        </list>
    </property>
</bean>

回答by Daniel David Kovacs

Instead of @RequestMapping(...headers="Accept=application/json"...)use @RequestMapping(... , produces = "application/json")

而不是@RequestMapping(...headers="Accept=application/json"...)使用@RequestMapping(... , produces = "application/json")

回答by user3055311

Using jQuery , you can set contentType to desired one (application/json; charset=UTF-8' here) and set same header at server side.

使用 jQuery ,您可以将 contentType 设置为所需的一个(application/json; charset=UTF-8' here)并在服务器端设置相同的标头。

REMEMBER TO CLEAR CACHE WHILE TESTING.

记住在测试时清除缓存。

回答by Sivaguru Srinivas

I also faced this same issue and I downloaded this [jar]: (http://www.java2s.com/Code/Jar/j/DownloadHymansonall190jar.htm)! and placed in lib folder and the app works like a charm :)

我也遇到了同样的问题,我下载了这个 [jar]:(http://www.java2s.com/Code/Jar/j/DownloadHymansonall190jar.htm)!并放置在 lib 文件夹中,该应用程序就像一个魅力:)

回答by Stefanos T.

I had this problem too, you have to add <mvc:annotation-driven />in your configuration xml

我也有这个问题,你必须<mvc:annotation-driven />在你的配置xml中添加

and

<!-- Hymanson -->
        <dependency>
            <groupId>com.fasterxml.Hymanson.core</groupId>
            <artifactId>Hymanson-databind</artifactId>
            <version>${Hymanson.databind-version}</version>
        </dependency>

in your pom.xml

在你的 pom.xml