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"},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'}"; }原文链接:https://www.f2er.com/springmvc/161770.html