RequestBody註解--springMVC接收json串
阿新 • • 發佈:2019-02-15
JSON字串是目前前後端通訊的主流方案,本文粗略記錄,前端ajax怎麼給服務端傳json格式字串,
以及java服務端springMVC如何接收請求字串。
1. 前端ajax程式碼:
$.ajax({ type : 'POST', cache : false, url : 'your url',//如jsonStringSave.do,或者javaBeanSave.do dataType:'json', contentType:'application/json', data : JSON.stringify(jsonParam) success : function() { } error:function(){ } }
2springMVC端接收JSON格式的請求字串
2.1需要在springMVC的配置檔案中新加一個HttpMessageConverter:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value="0" /> <property name="messageConverters"> <util:list id="beanList"> ****此處是 你之前配置的converter**** 追加下面的converter <ref bean="mappingJackson2HttpMessageConverter" /> </util:list> </property> </bean> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean>
2.2 需要在pom.xml中額外引入如下jar包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-lgpl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-lgpl</artifactId> <version>1.9.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-lgpl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>1.9.13</version> </dependency>
2.3 經過上述處理後,到達服務端的請求引數已經是JSON格式,
接下來springMVC端java程式碼接收JSON格式請求引數,兩種方式:
/**
* 方式一
* @param cm
* @return
*/
@RequestMapping(value={"javaBeanSave"},method={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public String javaBeanSave(@RequestBody CheckModel cm)
{
System.out.println("javaBean-->"+cm.getField());
return "{'errno':'0'}";
}
/**
* 方式二
* @param paramStr
* @return
*/
@RequestMapping(value={"jsonStringSave"},method={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public String jsonStringSave(@RequestBody String paramStr)
{
System.out.println("paramStr:"+paramStr);
JSONObject paramJSON = JSON.parseObject(paramStr);
System.out.println("jsonString-->"+paramJSON.getString("field"));
return "{'errno':'0'}";
}
PS: 接收Json格式字串,請求方呼叫時有可能會拋如下異常:
Required request body is missing
解決方案:
1. 提醒呼叫方用Post請求
2. 從根源解決,拒絕接收GET請求,method={RequestMethod.POST}