SpringMVC 报错The server refused this request because the request entity is in a format n...的解决办法

  最近开了个SSM的项目,在用JQuery通过ajax传json格式的数据给springMVC的接口时,一直报错415:The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

1、后台代码:

@RequestMapping(value="/getCustOrder",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public @ResponseBody String getJhtCustOrderById( @RequestBody JhtInfoVO jhtInfoVO){
		 

		List<JhtCustOrderView> list=null;
		try {
			list =         baseSearchJhtErrorDataServiceIml.getJhtCustOrderData(jhtInfoVO.getAgencyInfoId(), jhtInfoVO.getStartDate());		
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		if (list!=null) {
			 
			 
			return new JSONArray(list).toString();
		}else{
			
			return "1";
		}
		
		
		
	}

2、前台代码

	$.ajax({			
	        url: "getCustOrder.action",
	        type: "POST",
	        data: JSON.stringify(senddata), 
	        timeout:20000,
	        datatype:"json",
	        contentType:"application/json",
			success:function(data){

				var redata=	JSON.parse(data);
			
			
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				
				alert("错误,服务器异常,请稍后重试!");
			}
			
		});

 

上网搜了下类似问题大佬们的解决办法,把所有可能都试了个遍,结果还是.......依旧报错到怀疑人生。最后把spring的流程整个梳理了一遍,终于找到了问题发生的原因。这里总结下该报错发生的原因:

(1)ajax的请求头 contentType参数一定要是:"application/json",否则有可能会报该错误;

(2)项目路径要有Jackson的相关类包:jackson-databind-2.7.5.jar、jackson-annotations-2.7.0.jar及jackson-core-2.7.5.jar,有一点要注意的是如果spring版本不高,这几个包不要用2.7及以上的版本,不然会报错:java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.type.如果见到这种报错,建议jackson类包换成2.7以下的版本;

(3)spring的配置里面要有<mvc:annotation-driven />,即启用了注解识别;

(4)这一点也是我的报错的原因,spring的配置里面一定要加上Json转换器:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >    
	    <property name="messageConverters">    
	    <list>  
	    <!-- json转换器 --> 
	         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />  
	    </list>   
	    </property>    
</bean>  

不过这种配置方式其实有点过时了,相关内容可以参考:https://blog.csdn.net/yfisaboy/article/details/31755631

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章