欢迎来到天天文库
浏览记录
ID:56825802
大小:17.50 KB
页数:4页
时间:2020-07-15
《json格式的输入和输出.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、json格式的输入和输出Springmvc处理json需要使用jackson的类库,因此为支持json格式的输入输出需要先修改pom.xml增加jackson包的引用Xml代码<!--json--><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-core-lgpl</artifactId><version>1.8.1</version></dependen
2、cy><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-lgpl</artifactId><version>1.8.1</version></dependency>先修改之前的helloworld.jsp,增加客户端json格式的数据输入。Javascript代码varcfg={type:'POST',data:JSON.stringify({
3、userName:'winzip',password:'password',mobileNO:''}),dataType:'json',contentType:'application/json;charset=UTF-8',success:function(result){alert(result.success);}};functiondoTestJson(actionName){cfg.url=actionName;$.ajax(cfg);}根据前面的分析,在springmvc中解析输入为json格式的数据有两种方式1:使用@RequestB
4、ody来设置输入Java代码@RequestMapping("/json1")@ResponseBodypublicJsonResulttestJson1(@RequestBodyUseru){log.info("getjsoninputfromrequestbodyannotation");log.info(u.getUserName());returnnewJsonResult(true,"returnok");}2:使用HttpEntity来实现输入绑定Java代码@RequestMapping("/json2")publicResponse
5、Entity<JsonResult>testJson2(HttpEntity<User>u){log.info("getjsoninputfromHttpEntityannotation");log.info(u.getBody().getUserName());ResponseEntity<JsonResult>responseResult=newResponseEntity<JsonResult>(newJsonResult(true,"returnok"),HttpStatus.OK);retu
6、rnresponseResult;}Json格式的输出也对应有两种方式1:使用@responseBody来设置输出内容为contextbody2:返回值设置为ResponseEntity<?>类型,以返回contextbody另外,第三种方式是使用ContentNegotiatingViewResolver来设置输出为json格式,需要修改servletcontext配置文件如下Xml代码<beanclass="org.springframework.web.servlet.view.ContentNegotiatingViewR
7、esolver"><propertyname="order"value="1"/><propertyname="mediaTypes"><map><entrykey="json"value="application/json"/></map></property><propertyname="defaultViews"><list><beanclass="org.springframework.web.servlet.view.json.Ma
8、ppingJacksonJsonView"/></list></property><p
此文档下载收益归作者所有