Spring MVC获取客户端传给的json数据

来源:互联网 发布:mysql offset查询优化 编辑:程序博客网 时间:2024/03/29 21:39

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> 


0 0