SpringMVC的json数据绑定Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_25295611/article/details/70876436

总结一下今天遇到的问题:
第一个问题:在使用SpringMVC的时候,前台发送ajax请求传输json数据到后台报错

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 

前台代码:

$.ajax({
                url: "${pageContext.request.contextPath}/savePoints",
                type: "post",
                data: JSON.stringify(list),
                contentType: "application/json",
                success: function (result) {
                    alert("Ok!");
                },
                fail: function (result) {
                    alert("failed!");
                }

            });

后台:

@RequestMapping("/savePoints")
    @ResponseBody
    public void savePoints(@RequestBody List<Point> list){
        logger.info(list);
        //......
    }

原因应该是出在SpringMVC对json数据的接收上面。搜索了很多解决办法,有说加入jackson-mapper-asl.jar包的,然后在spring配置文件中加入如下内容

<!--<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list >
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

配置文件的配置信息跟jackson的版本有关:

第一种应该是spring3之前:
'org.springframework.http.converter.json.MappingJacksonHttpMessageConverter'
第二种是spring3之后:
'org.springframework.http.converter.json.MappingJackson2HttpMessageConverter'

运行之后又报了新的错误:

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException  

这个错误就好看懂了一点,应该是jackson的核心jar包没有引入,于是我又加入了这些jar包:
这里写图片描述
后面就没有报错了,数据也接收正常。
于是我删掉了jackson-mapper-asl.jar包,只保留了jackson的三个核心包,结果还是正常。

最新的配置是: jackson的三个jar包和spring文件里面的MappingJackson2HttpMessageConverter的配置。
展开阅读全文

关于SpringMVC返回Json数据报错:Content type 'application/json;charset=UTF-8' not support

05-16

[color=#FF0000][size=24px]今天用springMVC返回json数据是报错:Content type 'application/json;charset=UTF-8' not support,以下是代码[/size][/color]rnspringMVC的方法是:[code=java]@RequestMapping(value="/requestJson.action",method=RequestMethod.POST)rn @ResponseBodyrn public Student requestJson(@RequestBody Student student)rn return student; rn [/code]rnAjax的请求数据方式是使用jquery的:[code=javascript]function requestJson() rn $.ajax(rn type:'post',rn url:'/TestAjax/Ajax/requestJson.action',rn contentType:'application/json;charset=utf-8',rn dataType:'json',rn //数据格式是json串rn data:'"name":"木头人"', rn success:function(data) //测试能不能返回数据rn alert(data);rn rn ); rn[/code]rn搜过这个问题,有人说是有属性没有get方法引起的,但是我将bean注释只剩下一个属性了:[code=java]package com.testAjax.pojo;rnrnpublic class Student rn rn //private String id;rn rn private String name;rn rn //private int age;rn rn //private Date date;rnrn rn rn /*public String getId() rn return id;rn rn public void setId(String id) rn this.id = id;rn rn rn rnrn public int getAge() rn return age;rn rnrn public void setAge(int age) rn this.age = age;rn rnrn public Date getDate() rn return date;rn rnrn public void setDate(Date date) rn this.date = date;rn */rn rn public String getName() rn return name;rn rn public void setName(String name) rn this.name = name;rn rnrn[/code]rn另外,楼主试过了,如果只是接受字符串数据,springMVC没有报错,即这样:[code=java]@RequestMapping(value="/requestJson.action",method=RequestMethod.POST)rn @ResponseBodyrn public String requestJson(@RequestBody String name)rn rn rn return name;rn rn [/code]rn日志是显示接收成功的:[code=text]DEBUG [http-nio-8080-exec-4] - Read [class java.lang.String] as "application/json;charset=UTF-8" with [org.springframework.http.converter.StringHttpMessageConverter@779952f5]rnDEBUG [http-nio-8080-exec-4] - Written ["name":"木头人"] as "application/json" using [org.springframework.http.converter.StringHttpMessageConverter@779952f5]rnDEBUG [http-nio-8080-exec-4] - Null ModelAndView returned to DispatcherServlet with name 'springMVC': assuming HandlerAdapter completed request handlingrnDEBUG [http-nio-8080-exec-4] - Successfully completed request[/code]rn[size=24px][b]求救,这种错误应该怎么改,各位大神帮帮在下,分数奉上!!![/b][/size] 论坛

Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.问题

01-16

我写了一个WebPart,然后放于.aspx页中的WebPartZone中,webpart 中有如下代码:rn String tfsServer = "http://digihail-geewu/";rn tfsServer = tfsServer.Trim();rn TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(tfsServer);rn然后打开.aspx页是报下面错误:rnrnServer Error in '/WebTest' Application.rn--------------------------------------------------------------------------------rnrnClient found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.rnThe request failed with the error message:rn--rnrn rnrnErrorrnrn rn rn rnrn rn rnrnrn rnrnrn rn rn rn rn rn ………………………………rnrn--.]rn System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) +431431rn System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +204rn Microsoft.TeamFoundation.Proxy.BisRegistrationServiceProxyWsdl.GetRegistrationEntries(String toolId) +54rn Microsoft.TeamFoundation.Proxy.BisRegistrationProxy.GetRegistrationEntries(String toolId) +39rn Microsoft.TeamFoundation.Proxy.BisRegistrationService.RefreshMemoryCache() +90rn Microsoft.TeamFoundation.Proxy.BisRegistrationService.RefreshCachesIfNeeded(Boolean direct) +77rn Microsoft.TeamFoundation.Proxy.BisRegistrationService.GetRegistrationEntries(String toolId) +17rn Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore.GetMiddleTierUrls(String& serverUrl, String& configurationSettingsUrl) +68rn Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore.InitializeInternal() +68rn Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore.Microsoft.TeamFoundation.Client.ITeamFoundationServerObject.Initialize(TeamFoundationServer teamFoundationServer) +85rn Microsoft.TeamFoundation.Client.TeamFoundationServer.CreateITFSObjectInstance(Assembly assembly, String fullName) +111rn Microsoft.TeamFoundation.Client.TeamFoundationServer.GetService(Type serviceType) +359rn AddWorkItem.AddWorkItem.CreateChildControls() in E:\WICountWebPart\AddWorkItem\AddWorkItem.cs:70rn System.Web.UI.Control.EnsureChildControls() +87rn System.Web.UI.Control.PreRenderRecursiveInternal() +44rn System.Web.UI.WebControls.WebParts.WebPart.PreRenderRecursiveInternal() +42rn System.Web.UI.Control.PreRenderRecursiveInternal() +171rn System.Web.UI.Control.PreRenderRecursiveInternal() +171rn System.Web.UI.Control.PreRenderRecursiveInternal() +171rn System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842rnrn rnrnrn--------------------------------------------------------------------------------rnVersion Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053 论坛

springMVC求大神看下下面的报错log:Invalid mime type "text/html;charset = UTF-8":

04-25

我是在数据库里设的DEFAULT CHARSET=utf8 不知道是不是这个原因引起的rn贴上完整logrn[code=java] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.http.InvalidMediaTypeException: Invalid mime type "text/html;charset = UTF-8": Invalid token character ' ' in token "charset "rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)rn at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)rn at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)rn at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)rn at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)rn at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)rn at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)rn at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)rn at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)rn at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)rn at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)rn at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)rn at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)rn at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)rn at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)rn at javax.servlet.GenericServlet.init(GenericServlet.java:158)rn at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)rn at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)rn at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:828)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)rn at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)rn at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)rn at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)rn at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)rn at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)rn at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rn at java.lang.Thread.run(Thread.java:745)rn 论坛

没有更多推荐了,返回首页