javascript
SpringMVC接收Post的实体/JSon数据
接口代碼:
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST)/*只允許POST方式調(diào)用此接口*/
public returnType functionName(/*POST數(shù)據(jù)內(nèi)容*/@RequestBody parameterType parameterName,HttpServletRequest request) throws Exception {}
?
配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
?
依賴(lài)文件:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
?
邏輯代碼:
/*如果是List數(shù)據(jù) ?在接收到數(shù)據(jù)之后 ?需要轉(zhuǎn)換類(lèi)型*/
/*否則不需要轉(zhuǎn)換*/
ObjectMapper mapper = new ObjectMapper();
for (int i = 0; i < behaviorList.size(); i++) {
/*由于客戶(hù)端POST過(guò)來(lái)的List是LinkedHashMap類(lèi)型的數(shù)據(jù)
* 所以需要用ObjectMapper進(jìn)行解析轉(zhuǎn)換*/
ClassName clazz = mapper.convertValue(List.get(i),ClassName.class);
}
?
實(shí)體類(lèi):
如果訪問(wèn)端是C# ? DateTime類(lèi)型要重置為String類(lèi)型,否則服務(wù)端無(wú)法解析
?
?
訪問(wèn)端(C#):
/*POST之前 ?要先將實(shí)體類(lèi)轉(zhuǎn)換為JSon字符串 ? 然后再轉(zhuǎn)換成Byte數(shù)組*/
?HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri);
httpReq.Method = "POST";
httpReq.Accept = "*/*";
httpReq.ContentType = "application/json; charset=utf-8";
byte[] buffer = Encoding.UTF8.GetBytes(dataJsonString);
httpReq.ContentLength = buffer.Length;
httpReq.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
Stream respStream = httpResp.GetResponseStream();
StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
string result = respStreamReader.ReadToEnd();
?
?
以上是個(gè)人遇到問(wèn)題時(shí)候 ? ? 嘗試了一天時(shí)間找到的解決辦法 ? ?
本人java菜鳥(niǎo) ? 解決方案也許比較片面或老舊或笨拙 ? ?望大神指教?
也希望能夠幫到遇到同樣問(wèn)題的朋友
?
轉(zhuǎn)載于:https://www.cnblogs.com/JosephBee/p/5670571.html
總結(jié)
以上是生活随笔為你收集整理的SpringMVC接收Post的实体/JSon数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Eclipse反编译插件JadClips
- 下一篇: JavaScript(一)---- 概述