1. 程式人生 > >關於spring-mvc中使用ajax呼叫後臺接口出現400 bad request的問題解決方案

關於spring-mvc中使用ajax呼叫後臺接口出現400 bad request的問題解決方案

經過一段時間的學習。發現之前寫的這篇部落格

關於ajax 呼叫後臺 出現400bad request  有很大問題。特地重新編輯。

先描述下我的問題:

前端程式碼:

function test() {
        $.ajax({
            url:'../app/bg/shop/updateShopByShopId',
            type:'POST',
            data:{shopId:"000003",address:"廣東省深圳市深大地鐵站"},
            dataType:"JSON",
            contentType:"application/json",
            async:'true',
            success:function(result) {
                console.info(JSON.stringify(result))
            }
        })
    }

後臺程式碼:


錯誤提示:400 bad request.    'xxx'   parameter is not present。

錯誤解釋:這個錯誤  說明  後臺 沒有接收到 xxx 這個引數。

可是大家都看到了,ajax中含有引數。

錯誤原因:通過對spring的瞭解,發現 @RequestParam 這個註解  是通過 request.getParameter() 這個方法來獲取引數的。而你的contentType型別決定了後臺要以什麼方式進行解析。

當contentType型別為 application/json 時,如果你配置了spring 的 Json轉換器。那麼它會按照你宣告的型別進行解析,這個時候需要使用註解@RequestBody 來進行接收,比如@RequestBody Map<String,Object> map ,或者 @RequestBody JSONObject json.

當contentType型別為 application/x-www-form-urlencoded,它相當於form表單提交,資料會被編碼為key/value格式傳送到伺服器(表單預設的提交資料的格式),而這個時候後臺就可以 通過 request.getParameter()方法來進行接收,所以用@RequestParam註解也就可以了

總結:

1.如果後臺是使用註解@RequestParam 來進行接收引數的話,那麼 ajax 就不用新增contentType為application/json,它預設的application/x-www-form-urlencoded就是我們所需要的。

2.如果後臺你聲明瞭具體的型別來接收引數,那麼你就需要設定  contentType型別為 application/json。同時配置Spring的 Json轉換器,它的作用是 將傳遞過來的Json進行序列化成你宣告的型別。

下面講下springmvc 關於 Json 轉換的配置:

<mvc:annotation-driven>
		<!-- 不使用預設的訊息轉換器 -->
		<mvc:message-converters register-defaults="false">
			<!-- 配置Spring的轉換器 -->
			<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
			<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
			<!-- 配置fastjson中實現HttpMessageConverter介面的轉換器 -->
			<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
				<!-- 加入支援的媒體型別,返回contentType -->
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

呼叫成功案例:

前端-

function test() {
        $.ajax({
            url:'../app/bg/product/addSery',
            type:'POST',
            data:JSON.stringify({name:"尊享咖啡",shopId:"000001"}),
            dataType:"JSON",
            contentType:"application/json",
            async:'true',
            success:function(result) {
                console.info(JSON.stringify(result))
            }
        })
    }

後端接收-


後端接收 model,ProductSery


歡迎大家點贊!!