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

2022-09-01 16:36:12

我正在使用带有JSON的Spring MVC,如Ajax Simplification Spring 3.0文章中所述。

根据在各种论坛上找到的建议,经过这么多次尝试和代码变化,我的代码仍然不起作用。

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

我在我的应用程序配置中.xml根据需要。

应用配置.xml

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

    <!-- Configures Spring MVC -->
    <import resource="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>

这就是我为我的控制器准备的

@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

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

我非常感谢就此问题提供任何意见。谢谢


答案 1

要从带注释的方法返回 JSON 响应,您需要两件事:@ResponseBody

您不需要 和 在 .ContentNegotiatingViewResolverheaders@RequestMapping


答案 2

在我将Spring从3.2.x升级到4.1.x后,我遇到了这个问题。我通过将Jackson从1.9.x升级到2.2.x(更快的xml)来修复

 <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.2.3</version>
</dependency>

推荐