- 浏览: 969239 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
qq_15946053:
基于spring的项目要导出成jar怎么做呢用eclipse的 ...
Spring项目导出可运行的JAR -
flyfeifei66:
baseservice、dao代码是同一个,但是实例配置多个, ...
Spring通过父类注入公用属性的技巧 -
yuechao4039:
写得不错,望楼主再接再厉
Spring中配置和读取多个Properties文件 -
xinglianxlxl:
psubscribe对我有用
Jedis的Publish/Subscribe功能的运用 -
Fenix87:
js中怎么调用配置文件的参数呢
Spring中配置和读取多个Properties文件
个人学习参考所用,勿喷!
返回JSON
1) 用Maven构建web项目:
构建过程参考limingnihao的blog(写得相当的详细!!!):使用Eclipse构建Maven的SpringMVC项目
注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。由于Spring是采用对JSON进行了封装的jackson来生成JSON和返回给客户端,所以这里需要添加jackson的相关包。项目的pom.xml配置如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.watson</groupId> <artifactId>rest-spring</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>rest-spring Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- 省略其他配置,具体可以参考附件--> ...... <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.4.2</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.4.2</version> </dependency> </dependencies> </project>
2) 在web.xml配置Spring的请求处理的Servlet,具体设置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Spring-Rest</display-name> <servlet> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/rest-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3) 在rest-servlet.xml中配置如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.mkyong.common.controller" /> <mvc:annotation-driven /> </beans>
为了解决乱码问题,需要添加如下配置,并且这里可以显示的添加MappingJacksonHttpMessageConverter这个转换器。
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> </list> </property> </bean>
4) 编写自己的服务组件类,使用MVC的annotation风格,使用 @ResponseBody处理返回值。具体代码如下:
@RequestMapping("/jsonfeed") public @ResponseBody Object getJSON(Model model) { List<TournamentContent> tournamentList = new ArrayList<TournamentContent>(); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/")); tournamentList.add(TournamentContent.generateContent("中超", new Date(), "中超", "www.fifa.com/confederationscup/")); model.addAttribute("items", tournamentList); model.addAttribute("status", 0); return model; }
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed/,得到结果为:
{"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":1334559460940}]}
这里我们也可以利用Spring3MVC中对试图和内容协商的方法来处理返回JSON的情况,下面步骤接上面第2步:
3) 在rest-servlet.xml中对相关进行具体的设置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 自动搜索@Controller标注的类,包括其下面的子包 --> <context:component-scan base-package="com.watson.rest" /> <!-- 根据客户端的不同的请求决定不同的view进行响应, 如 /blog/1.json /blog/1.xml --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <!-- 设置为true以忽略对Accept Header的支持 --> <property name="ignoreAcceptHeader" value="true" /> <!-- 在没有扩展名时即: "/blog/1" 时的默认展现形式 --> <property name="defaultContentType" value="text/html" /> <!-- 扩展名至mimeType的映射,即 /blog.json => application/json --> <property name="mediaTypes"> <map> <entry key="html" value="text/html" /> <entry key="pdf" value="application/pdf" /> <entry key="xsl" value="application/vnd.ms-excel" /> <entry key="xml" value="application/xml" /> <entry key="json" value="application/json" /> </map> </property> <!-- 用于开启 /blog/123?format=json 的支持 --> <property name="favorParameter" value="false" /> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/pages" /> <property name="suffix" value=".jsp"></property> </bean> </list> </property> <property name="defaultViews"> <list> <!-- for application/json --> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> <!-- for application/xml --> <!-- <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> <property name="marshaller"> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"/> </property> </bean> --> </list> </property> </bean> </beans>
//FINAL package com.watson.rest.json; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.watson.rest.feeds.TournamentContent; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class FeedController { @RequestMapping("/jsonfeed") public String getJSON(Model model) { List<TournamentContent> tournamentList = new ArrayList<TournamentContent>(); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/")); tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "Confederations Cup", "www.fifa.com/confederationscup/")); model.addAttribute("items", tournamentList); model.addAttribute("status", 0); return "jsontournamenttemplate"; } }
public class TournamentContent { private static int idCounter = 0; private String author; private Date publicationDate; private String name; private String link; private int id; public static TournamentContent generateContent(String author, Date date, String name, String link) { TournamentContent content = new TournamentContent(); content.author = author; content.publicationDate = date; content.name = name; content.link = link; content.id = idCounter++; return content; } //省略getter、setter }
{"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":1334559460940}]}
@RequestMapping(value="/add",method=RequestMethod.POST) @ResponseBody public Object addUser(@RequestBody User user) { System.out.println(user.getName() + " " + user.getAge()); return new HashMap<String, String>().put("success", "true"); }
public class User { private String name; private String age; //getter setter }
$.fn.serializeObject = function(){ var o = {}; var a = this.serializeArray(); $.each(a, function(){ if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };
$(document).ready(function(){ jQuery.ajax({ type: 'GET', contentType: 'application/json', url: 'jsonfeed.do', dataType: 'json', success: function(data){ if (data && data.status == "0") { $.each(data.data, function(i, item){ $('#info').append("姓名:" + item.name +",年龄:" +item.age); }); } }, error: function(){ alert("error") } }); $("#submit").click(function(){ var jsonuserinfo = $.toJSON($('#form').serializeObject()); jQuery.ajax({ type: 'POST', contentType: 'application/json', url: 'add.do', data: jsonuserinfo, dataType: 'json', success: function(data){ alert("新增成功!"); }, error: function(){ alert("error") } }); }); });
参考:
官方文档:http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch18.html
badqiu的BOLG: 《spring REST中的内容协商(同一资源,多种展现:xml,json,html)》
liuweifeng的BOLG :http://blog.liuweifeng.net/archives/407
Gary Mark等的书籍:《Spring Recipes》2ed
- rest-spring.zip (14.3 KB)
- 下载次数: 1695
评论
jackson-all-1.8.10.jar 缺少这个包
你好,这是个没有找到类的BUG,很常见。原因是没有加入需要的jar,或者jar的版本不对。
发表评论
-
Spring项目导出可运行的JAR
2013-09-05 20:01 16221一、在使用MAVEN的打包插件。 1.背景 ... -
Spring Security3实践总结
2013-07-22 18:12 19194在线项目最近要对管理系统进行细粒度的权限控 ... -
Spring中配置和读取多个Properties文件
2013-05-31 16:45 61514一个系统中通常会存在如下一些以Properties形式存在 ... -
Spring多数据源的配置和使用(2)
2012-11-22 11:40 18673本文以Spring2.5 + Hibernat ... -
Spring定时任务的多种使用方法总结
2012-08-04 17:34 10379这里使用的是Spring2.5,需要的jar包:sprin ... -
Spring多数据源的配置和使用(1)
2012-08-04 14:51 22570最近开发一个数据同步的小功能,需要从A主机的Ora ... -
Spring通过父类注入公用属性的技巧
2012-06-19 13:22 29703XML配置方式提取父类 在 ... -
Spring3 MVC
2012-04-24 17:16 0个人学习参考所用,勿喷! 1.搭建一个基于S ... -
Spring3 MVC的最佳实践和理解(9)
2012-04-25 09:10 2490个人学习参考所用,勿喷! 9.创建一个资源多种实现的 ... -
Spring3 MVC的最佳实践和理解(8)
2012-04-25 09:10 2285个人学习参考所用,勿喷! 8.Bean的注解式 ... -
Spring3 MVC的最佳实践和理解(7)
2012-04-25 09:09 4083个人学习参考所用, ... -
Spring3 MVC的最佳实践和理解(6)
2012-04-25 09:09 1990个人学习参考所用, ... -
Spring3 MVC的最佳实践和理解(5)
2012-04-24 17:01 22019个人学习参考所用, ... -
Spring3 MVC的最佳实践和理解(4)
2012-04-24 16:59 4779个人学习参考所用,勿喷! 4.区域解析和外部化区 ... -
Spring3 MVC的最佳实践和理解(3)
2012-04-24 16:56 4471个人学习参考所用,勿喷! 3.使用拦截器 Sp ... -
Spring3 MVC的最佳实践和理解(2)
2012-04-24 16:55 5037个人学习参考所用,勿 ... -
Spring3 MVC的最佳实践和理解(1)
2012-04-24 16:53 3724个人学习参考所用,勿喷! 1.搭建一个基 ... -
Spring的JNDI数据源连接池配置示例及Spring对JNDI实现分析
2012-04-10 16:00 89418个人学习参考所用,勿喷! 在使用 Tomcat服 ... -
Spring属性注入和构造函数注入参考
2012-02-25 23:23 4379个人学习参考所用,勿喷! 1.Pojo如下: ...
相关推荐
delphi7使用IXMLHTTPRequest实现RESTful的访问及返回json数据的解析,推送消息段HMACSHA1加密编码
使用Spring4 MVC 构建RESTful服务器,输出JSON格式的数据结构
使用Spring4 MVC 构建RESTful服务器,输出JSON格式的数据结构
在本示例中,我们将向您展示如何将对象转换成json格式并通过spring mvc框架返回给用户。...spring和jackson的依赖: <project xmlns=http://maven.apache.org/POM/4.0.0 xmlns:xsi=http://www.w3.org/2001
最新spring3 mvc restful urlrewrite jquery json freemarker整合架构jar图片,欢迎下载: 说明比较少,群号:24172014,不懂来问,已懂讨论
cxf集成Spring的restful WebService接口以Json形式表现的完整代码,适合新入门在学WebService的小伙伴们参考,希望对你们有帮助!
Spring restful开发小例子,供初学者使用
使用Spring 实现RESTful Web 服务 demo
利用Spring对RESTful Web Service进行简单的实现demo。
使用Spring4.3.8开发的RESTful服务,请求和答复都是json格式。
Java使用Jersey框架构建 RESTful Web服务返回json数据所需的jar包。Jackson-core-asl.jar / Jackson-jaxrs.jar / Jackson-mapper-asl.jar / Jackson-xc.jar / jersey-media-json-Jackson.jar
使用Spring构建Restful的Web服务.pdf
android spring restful
利用spring 发布restful服务,该工程包含的有所使用的jar包,下载后可以直接运行的项目。欢迎下载
spring3.2。 restful访问方式: http://localhost:8080/jsp-rewrite/api/saveUser requestheader:Content-Type=application/json;charset=UTF-8 requestbody:{"id":3,"username":"王五","userpwd":"123456",...
利用CXF3.0.2+Spring3.2.14发布RESTFul,传递json数据格式的!需要源代码可以下载!
spring mvc restful service,支持string, json, xml, maven工程,可以直接运行
java jersey spring 集成 开发 restful API ,并将restful 返回的数据以JSON的格式返回,开发非常简单,易懂。欢迎小伙伴们 下载资源。