Spring MVC:@ResponseBody,415不支持的媒体类型 [英] Spring MVC: @ResponseBody, 415 Unsupported Media Type

查看:165
本文介绍了Spring MVC:@ResponseBody,415不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将JSON Post映射到特定的Java Object以通过 Hibernate 保存它



Ajax调用的标题为正确设置...

 接受application / json 
Content-Type application / json; charset = UTF-8

并且HTTP方法是 POST p>

这是我的配置...

我的Spring MVC函数映射看起来像这样

  @RequestMapping(value = {/save.json\"},method = RequestMethod.POST)
public ModelMap save(@RequestBody Seizure seizureObj,模型模型){
...
}

在我的容器中xml I有一个像这样的 ContentNegotiatingViewResolver

 < bean class =org.springframework.web.servlet。 view.ContentNegotiatingViewResolver> 
< property name =mediaTypes>
< map>
< entry key =htmlvalue =text / html/>
< entry key =jsonvalue =application / json/>
< / map>
< / property>
< property name =viewResolvers>
< list>
< bean id =viewResolver
class =org.springframework.web.servlet.view.InternalResourceViewResolver>
< property name =prefixvalue =/ WEB-INF / assets //>
< property name =suffixvalue =。jsp/>
< / bean>
< / list>
< / property>
< property name =defaultViews>
< list>
< bean
class =org.springframework.web.servlet.view.json.MappingJacksonJsonView>
< property name =prefixJsonvalue =false/>
< property name =objectMapperref =jacksonObjectMapper/>
< / bean>
< / list>
< / property>
< / bean>

在我的容器xml杰克逊部分

 < bean class =org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterConfigurer
init-method =init>

< property name =messageConverters>
< list>
< bean id =marshallingHttpMessageConverter
class =org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
>
< property name =objectMapperref =jacksonObjectMapper/>
< / bean>
< / list>
< / property>
< / bean>

< bean id =jacksonObjectMapperclass =org.codehaus.jackson.map.ObjectMapper/>

我有


  • jackson-core-asl-1.8.5

  • jackson-mapper-asl-1.8.5



在我的/ lib文件夹中



和Jackson适用于这样的简单情况

  public class Simple {
private int id;

public int getId(){
return id;
}

public void setId(int id){
this.id = id;


$ b @RequestMapping(value = {/saveSimple.json\"},method = RequestMethod.POST)
public ModelMap save(@RequestBody Simple simple ,模型模型){
...
}

当我测试它时curl

  curl -v -HAccept:application / json-HContent-type:application / json - X POST -d'{id:1}'http://< URL> /saveSimple.json 

没有问题,但是如果用Hibernate对象测试它,我会得到消息

  415不支持的介质类型

任何想法。

解决方案



首先,我必须设置 @JsonManagedReference @JsonBackReference 右键。我将ManagedReference设置为表示 ONE 关系的 ONE 的属性,但显然您必须将其设置为 MANY strong>属性(集合)



请参阅此处的说明
http://wiki.fasterxml.com/JacksonFeatureBiDirReferences



@JsonBackReference是引用的back部分:它将从序列化中被省略,并在反向引用的反序列化过程中重新构建。


  • 带注释的属性必须是bean类型
  • >

在我的例子中,问题是我没有在我的JSON POST中发送足够的信息来匹配Hibernate要求。



这导致了一个异常,即我的JSON POST中创建Hibernate对象的适当字段不存在。



我创建了一个测试网址,我自己创建了对象映射器,并试图手动对JSON进行反序列化。这引发了正确的错误信息。

在我看来,Spring很遗憾地抛出了415个Unsupported Media Type异常,这有点误导。



所以为了未来。

  ModelMap map = new ModelMap(); 
logger.info(HibernateAware);
HibernateAwareObjectMapper mapper = new HibernateAwareObjectMapper();
String jsonInput =
{+
\id \:\1 \,+
\matCountry \ :{+
\id \:\1 \+
}+
};
Seizure seizure = mapper.readValue(jsonInput,Seizure.class); //此行引发异常

希望这可以帮助别人。



问候JS


I'm having trouble mapping a JSON Post to a particular Java Object to save it via Hibernate

Headers of the Ajax call are correctly set...

Accept          application/json
Content-Type    application/json; charset=UTF-8

and the HTTP-Method is POST

Here comes my configuration...

My Spring MVC function mapping looks like this

@RequestMapping(value = {"/save.json"},method = RequestMethod.POST)
public ModelMap save(@RequestBody Seizure seizureObj,Model model) {
   ...
}

in my container xml I have a ContentNegotiatingViewResolver like this

<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 id="viewResolver"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/WEB-INF/assets/" />
                <property name="suffix" value=".jsp" />
            </bean>
        </list>
    </property>
    <property name="defaultViews">
        <list>
            <bean
                class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                <property name="prefixJson" value="false" />
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

in my container xml the part for jackson

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterConfigurer"
    init-method="init">

    <property name="messageConverters">
        <list>
            <bean id="marshallingHttpMessageConverter"
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"
          >
          <property name="objectMapper" ref="jacksonObjectMapper" />
          </bean>
        </list>
    </property>
</bean> 

<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" /> 

I have

  • jackson-core-asl-1.8.5
  • jackson-mapper-asl-1.8.5

in my /lib folder

and Jackson works for a simple case like this

public class Simple {
  private int id;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }   
}

@RequestMapping(value = {"/saveSimple.json"},method = RequestMethod.POST)
public ModelMap save(@RequestBody Simple simple,Model model) {
   ...
}

when I test it with curl

 curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":1}'  http://<URL>/saveSimple.json

No problems, but if I test it with the Hibernate object I get the message

415 Unsupported Media Type

any ideas.

解决方案

StanMax lead my in the right direction...

First I had to set the @JsonManagedReference and @JsonBackReference right. I set the ManagedReference to the attribute which represents the ONE of of the ONE-to-MANY relationship, but apparently you have to set it to the MANY attribute (the collection)

see the description here http://wiki.fasterxml.com/JacksonFeatureBiDirReferences

@JsonBackReference is the "back" part of reference: it will be omitted from serialization, and re-constructed during deserialization of forward reference.

  • Annotated property must be of bean type

The problem in my case was that I didn't send sufficient information in my JSON POST to match the Hibernate requirements.

This resulted in an Exception that the proper fields to create a Hibernate object out of my JSON POST, were not present.

I created a test url where I created the Object mapper myself and tried to de-serialize JSON by hand. This throw the right error message.

It seems to my that Spring unfortunately throws the 415 "Unsupported Media Type" exception which is a bit misleading.

So for the future. Try it out by hand first (see example included) and than go on.

 ModelMap map = new ModelMap();
 logger.info("HibernateAware");
 HibernateAwareObjectMapper mapper = new HibernateAwareObjectMapper();
 String jsonInput = 
 "{" +
   "\"id\":\"1\"," +
   "\"matCountry\":{" +
     "\"id\":\"1\"" +
   "}" +
 "}";
 Seizure seizure = mapper.readValue(jsonInput, Seizure.class); // this line throw the exception

Hope this helps someone.

Regards JS

这篇关于Spring MVC:@ResponseBody,415不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆