spring mvc not returning json content - error 406

2020-01-27 03:26发布

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

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 ().

I have in my appconfig.xml as required.

app-config.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>

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

  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

14条回答
闹够了就滚
2楼-- · 2020-01-27 03:57

See my answer to a similar problem here with Spring MVC interpreting the extension of the URI and changing the expected MIME type produced behind the scene, therefore producing a 406.

查看更多
唯我独甜
3楼-- · 2020-01-27 03:59

Well, The answers on this page might be right but they didn't expatiate well. This is what I did

I added this to my pom.xml

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.8</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.8</version>  
</dependency>

Then I added headers to my RequestMapping like below

@RequestMapping(value="/admin/getGallery", method = RequestMethod.GET, headers={"Content-Type=application/json"})

Then in my jquery ajax I added - contentType: "application/json", so it looks like

jQuery.ajax({
            type:'GET',
            url:"getGallery.html",
            data: "designId="+designId,
            processData:false,
            contentType: "application/json",
            //dataType: "json",
           success:function(data){
              console.log(data);

           },
            error : function(e) {
                console.log("ERROR: ", e);
            },
        });

Then in my servlet I added

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
    <!-- Bind the return value of the Rest service to the ResponseBody. -->
    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
    <util:list id="beanList">
    <ref bean="jsonHttpMessageConverter" />
    </util:list>
    </property>
</bean> 

If you have problem with util tag in your servlet just just add in the same servlet file

xmlns:util="http://www.springframework.org/schema/util"

and

xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
查看更多
看我几分像从前
4楼-- · 2020-01-27 04:02

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

Also take a look at this jquery issue

查看更多
男人必须洒脱
5楼-- · 2020-01-27 04:08

As said by axtavt, mvc:annotation-driven and jackson 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.

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

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-01-27 04:10

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

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>
查看更多
Juvenile、少年°
7楼-- · 2020-01-27 04:10

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

and

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

in your pom.xml

查看更多
登录 后发表回答