所谓Web Service是一个平台独立的,低耦合的,自包含的、可编程的Web应用程序,有了Web Service异构系统之间就可以通过XML或JSON来交换数据,这样就可以用于开发分布式的互操作的应用程序。Web Service使得运行在不同机器上的不同应用无须借助附加的、专门的第三方软件或硬件就可相互交换数据或集成,无论它们各自所使用的语言、平台或内部协议是什么,都可以相互交换数据。Web Service为整个企业甚至多个组织之间的业务流程的集成提供了一个通用机制。 
  REST(REpresentational State Transfer)是Roy Fielding博士于2000年在他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。近年来,越来越多的Web Service开始采用REST风格设计和实现。例如,亚马逊提供接近REST风格的Web Service进行图书查找;雅虎提供的Web Service也是REST风格的。

  如果要对REST有更深入的了解和更深刻的认识,推荐大家阅读InfoQ上面的一篇文章《理解本真的REST架构风格》。相信很多自以为懂REST的人看完这篇文章之后才知道什么是真正的REST。在IBM的开发者社区中有一篇非常好的文章,名为《使用Spring 3来创建RESTful Web Services》,讲解如何用springWeb和Spring MVC来创建REST风格的Web Service。由于这篇文章已经讲得很好了,这里我就不再赘述其中的内容。

  这里要讲的是基于Apache CXF来创建RESTful Web Service。可以在Apache的网站下载到CXF的发行版本。Apache的官网是这样介绍CXF的:

Apache CXF is an open source services framework. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.

  下载完成后解压并找到lib目录,将其中的jar文件添加你的Java项目中,接下来就可以开始编写你的Web Service程序了。话不多说,直接上代码。

package com.lovo.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Student")
public class Student {
private Integer id;
private String name;
private String birthday; public Student() {
} public Student(Integer id, String name, String birthday) {
this.id = id;
this.name = name;
this.birthday = birthday;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getBirthday() {
return birthday;
} public void setBirthday(String birthday) {
this.birthday = birthday;
} }
package com.lovo.infrastructure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.lovo.domain.Student; public class StudentRepository {
private Map<Integer, Student> map = new HashMap<>(); public StudentRepository() {
map.put(1001, new Student(1001, "骆昊", "1980-11-28"));
map.put(1002, new Student(1002, "王大锤", "1992-2-2"));
map.put(1003, new Student(1003, "张三丰", "1930-3-3"));
} public void save(Student student) {
if (student != null) {
map.put(student.getId(), student);
}
} public void delete(Student student) {
if (student != null && map.containsKey(student.getId())) {
map.remove(student.getId());
}
} public void update(Student student) {
delete(student);
save(student);
} public Student findById(Integer id) {
return map.get(id);
} public List<Student> findAll() {
return new ArrayList<Student>(map.values());
}
}
package com.lovo.service;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import com.lovo.domain.Student;
import com.lovo.infrastructure.StudentRepository; @Path("/service")
@Produces("application/json")
public class StudentService {
private StudentRepository studentRepo = new StudentRepository(); @GET
@Path("/stu/{id}")
@Consumes("application/json")
public Student getStudent(@PathParam("id") Integer id) {
return studentRepo.findById(id);
} @GET
@Path("/stu")
@Consumes("application/json")
public List<Student> getAllStudents() {
return studentRepo.findAll();
} @POST
@Path("/stu")
@Consumes("application/json")
public boolean addStudent(Student student) {
if (getStudent(student.getId()) == null) {
studentRepo.save(student);
return true;
}
return false;
} @PUT
@Path("/stu/{id}")
@Consumes("application/json")
public boolean updateStudent(@PathParam("id") Integer id, Student student) {
if (getStudent(id) != null) {
studentRepo.update(student);
return true;
}
return false;
} @DELETE
@Path("/stu/{id}")
@Consumes("application/json")
public boolean deleteStudent(@PathParam("id") Integer id) {
Student student = getStudent(id);
if (student != null) {
studentRepo.delete(student);
return true;
}
return false;
}
}

  最后来启动Web Service的服务器并进行测试

package com.lovo;

import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;

import com.lovo.domain.Student;
import com.lovo.service.StudentService; public class MyRestServer { public static void main(String[] args) {
JAXRSServerFactoryBean myRESTfulServer = new JAXRSServerFactoryBean();
myRESTfulServer.setResourceClasses(Student.class);
myRESTfulServer.setServiceBean(new StudentService());
myRESTfulServer.setAddress("http://localhost:9999/");
myRESTfulServer.create();
}
}

  在浏览器中分别输入以下两个URI查看结果: 
http://localhost:9999/service/stu/1002 

http://localhost:9999/service/stu 

如何封装RESTful Web Service的更多相关文章

  1. 怎样封装RESTful Web Service

    所谓Web Service是一个平台独立的,低耦合的.自包括的.可编程的Web应用程序.有了Web Service异构系统之间就能够通过XML或JSON来交换数据,这样就能够用于开发分布式的互操作的应 ...

  2. MEAN Stack:创建RESTful web service

    本文在个人博客上的地址为URL,欢迎品尝. 前段时间做了DTREE项目中的前后端数据存储功能,在原有的ngController上进行HTTP请求,后端接受到请求后再存储到mongoDB上.现将学习所得 ...

  3. day01(RESTful Web Service、SVN)

    今日大纲 搭建SSM环境 基于SSM环境实现用户管理系统 学习RESTful Web Service 学习SVN 统一开发环境 JDK1.7 32? 64? -- 64 Eclipse 使用4.4.1 ...

  4. Django实战(15):Django实现RESTful web service

    曾几何时,Ajax已经统治了Web开发中的客户端,而REST成为web世界中最流行的架构风格(architecture style).所以我们的选择变得很简单:前端ajax访问后端的RESTful w ...

  5. WCF实现RESTFul Web Service

    共同学习了前面一些概念,终于开始正题了哈.RESTful的Web Service调用直观,返回的内容容易解析.这里先会描述一个简单的场景--Web Service提供一个方法来搜索个人信息,传入人名, ...

  6. 用Jersey为Android客户端开发Restful Web Service

    平时在做Android客户端的时候经常要与服务器之间通信,客户端通过服务端提供的接口获取数据,然后再展示在客户端的界面上,作为Android开发者,我们平时更多的是关注客户端的开发,而对服务端开发的关 ...

  7. 【转】基于CXF Java 搭建Web Service (Restful Web Service与基于SOAP的Web Service混合方案)

    转载:http://www.cnblogs.com/windwithlife/archive/2013/03/03/2942157.html 一,选择一个合适的,Web开发环境: 我选择的是Eclip ...

  8. 【转】 Build a RESTful Web service using Jersey and Apache Tomcat 2009

    Build a RESTful Web service using Jersey and Apache Tomcat Yi Ming Huang with Dong Fei Wu, Qing GuoP ...

  9. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

随机推荐

  1. NET Core写了一个轻量级的Interception框架[开源]

    NET Core写了一个轻量级的Interception框架[开源] ASP.NET Core具有一个以ServiceCollection和ServiceProvider为核心的依赖注入框架,虽然这只 ...

  2. java类在eclipse上打jar包,Linux上成功运行的实例

    1 eclipse下的java项目结构如下图所示: 2 打包的步骤如下: 3 修改minifest.mf文件:  4 .上传需要的三方jar包们和主类打的jar(案例是topV.jar)并且执行jav ...

  3. 从0到1分步实现一个出生日期的正则表达式(JavaScript)

    简言 在表单验证中,经常会用正则表达式做出生日期校验.本文把出生日期分割成几个部分,分步地介绍了实现一个出生日期校验的完整过程.相信您在理解了本篇的内容后,对如何编写和如何应用正则表达式会有进一步的理 ...

  4. If people in the communications only think about gains and losses of interest, then the pleasure of knowing each other will cease to exist.

    If people in the communications only think about gains and losses of interest, then the pleasure of ...

  5. Arduino ESP8266编程深入要点

    Arduino for ESP8266的话,如果不修改代码,默认没有办法进入轻睡眠的省电模式,只能进入Modem Sleep,也就是说Wifi可以暂时睡眠但是CPU没法睡,Modem Sleep最低功 ...

  6. Windows 8 / win8 拼音输入法/搜狗输入法 visual Studio 2010 / VS2010 不兼容

    是visual assist X 的问题,更新到VA_X_Setup 2001 解决问题 老版本处理:Tools-->Extension Manager-->Uninstall

  7. Android笔记--Bitmap(二)内存管理

    Bitmap(二) 内存管理 1.使用内存缓存保证流畅性 这种使用方式在ListView等这种滚动条的展示方式中使用最为广泛, 使用内存缓存 内存缓存位图可以提供最快的展示.但代价就是占用一定的内存空 ...

  8. eclipse的垂直选择功能

    快捷键:Alt+Shift+A切换. 光标会变成十字,就可以垂直选择了.

  9. C语言的sprintf()和snprintf()

    1.sprintf()函数 送格式化输出到字符串中,返回实际输出到字符串中的个数. 例如: char buffer[80]; sprint(buffer,"1234567890") ...

  10. 【Python图像特征的音乐序列生成】思路的转变

    关于生成网络这边,可能会做一个深度的受限玻尔兹曼机,这样可以保证生成的音乐不会太相似. 情绪识别网络和生成网络的耦合,中间变量可能直接就是一个one-hot向量,用来标注指定的情绪,不做成坐标那种难以 ...