@RequestBody,415Unsupported Media Type错误,真正有用的解决方案。

用了一上午查找问题解决方案,网上的试验了一遍都没用,最后终于解决~

我的答案在最后

问题:前端传json,后端也返回json,出现格式不匹配报415问题。

先罗列网友答案,也许适合你

1.maven引入jackson包,共3个【重要】
jackson-core
jackson-databind
jackson-annotations

2.springmvc的配置文件【重要】
在这里插入图片描述

3.有的网友在springmvc还加了bean配置【反正我没配置不影响】

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

还有这样加的

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- 设置返回字符串编码 -->
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name = "supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <!-- json转换器 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

4.前端【重要】
有网友提出:data要传JSON.stringify(你的data),不然json解析会出错
当然,最好在headers中限制一下传输和接收的内容格式
在这里插入图片描述

5.后端【很简单】
我的接口
在这里插入图片描述
我的Bean
在这里插入图片描述

一切配置后,最后发现我的问题是!!!
maven引入jackson包后,即使我重启服务器/重新打包,都没有自动将包导入WEB-INF/lib中,因此没注意到这个问题,我也是醉了~最后右键putinto就OK了在这里插入图片描述
在这里插入图片描述
完美解决~

猜你喜欢

转载自blog.csdn.net/g_y_x_/article/details/84339648