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

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