Spring MVC獲取客戶端傳給的json數據
@RequestMapping(value = "/postRequest", method = RequestMethod.POST, headers = "Content-Type=application/json")
@ResponseBody
public Object postRequest(HttpServletRequest request) throws IOException {
//表示請求的內容區數據爲json數據
InputStream is = request.getInputStream();
byte bytes[] = new byte[request.getContentLength()];//可以得到請求頭的內容區數據的長度
is.read(bytes);
//得到請求中的內容區數據(以CharacterEncoding解碼)
String jsonStr = new String(bytes, request.getCharacterEncoding());
JSONObject jsonObject = JSON.parseObject(str);
System.out.println("json data:" + jsonStr);
Map<String, Object> map = new HashMap<String, Object>();
map.put("result", "ok");
return map;
}
spring-servlet.xml中配置:
<bean id = "stringHttpMessageConverter" class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id = "formHttpMessageConverter" class = "org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
<ref bean="stringHttpMessageConverter" />
<ref bean="formHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
</list>
</property>
</bean>