首页 > 代码库 > (转)CXF开发RESTFUL的实例练习

(转)CXF开发RESTFUL的实例练习

根据上篇博客,我们知道WebService有两种实现规范,实现了JAX-RS这种规范的技术有CXF、RESTLET、JERSEY。这篇博客简单地介绍以CXF来实现WebService的实例。

   JAX-RS规范定义了创建RESTful服务的语法。JAX-RS使用annotations注解实现RESTful的服务,使用annotations注解POJO将它暴露为RESTful资源。

0.创建一个Web项目,引入jar包:

技术分享

包结构如图:

技术分享

1.使用@XmlRootElement注解POJO类

 

[java] view plain copy
  1. package entity;  
  2. import java.util.Set;  
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4. @XmlRootElement(name="Categorys")  
  5. public class Category {  
  6.     private String categoryId;  
  7.     private String categoryName;      
  8.     public String getCategoryId() {  
  9.         return categoryId;  
  10.     }  
  11.     public void setCategoryId(String categoryId) {  
  12.         this.categoryId = categoryId;  
  13.     }  
  14.     public String getCategoryName() {  
  15.         return categoryName;  
  16.     }  
  17.     public void setCategoryName(String categoryName) {  
  18.         this.categoryName = categoryName;  
  19.     }     
  20. }  

在POJO类Category中,注解@XmlRootElement指定Category为XML的根元素。Category类的属性默认指定映射为@XmlElement。@XmlElement用来定义XML中的子元素。@XmlRootElement和@XmlElement允许自定义命名空间和XML中元素的名称。如果没有定义的话,JAXB在运行的时候默认的使用同样的属性名和类名来定义XML元素。

该POJO类可以对应XML文件为:

 

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
  2.    <Category>  
  3.       <categoryId>005</categoryId>  
  4.       <categoryName>Fiction Series</categoryName>  
  5.   </Category>  

2、dao代码,未使用数据库存储数据,采用map容器存储数据。下面代码中有对Category增删改查四个方法。

 

[java] view plain copy
  1. package dao;  
  2. import java.util.HashMap;  
  3. import java.util.HashSet;  
  4. import java.util.Map;  
  5. import java.util.Set;  
  6. import entity.Category;  
  7. public class CategoryDao {  
  8.     private static Map<String,Category> categoryMap = new HashMap<String,Category>();  
  9.     static{  
  10.         Category c1  = new Category();  
  11.         c1.setCategoryId("001");  
  12.         c1.setCategoryName("java");  
  13.         categoryMap.put(c1.getCategoryId(), c1);          
  14.     }  
  15.     public void addCategory(Category category){  
  16.         categoryMap.put(category.getCategoryId(), category);  
  17.     }  
  18.     public Category getCategory(String id){  
  19.         Category cat = null;  
  20.         if(categoryMap.get(id) != null){  
  21.             cat = new Category();  
  22.             cat.setCategoryId(categoryMap.get(id).getCategoryId());  
  23.             cat.setCategoryName(categoryMap.get(id).getCategoryName());  
  24.         }  
  25.         return cat;  
  26.     }  
  27.     public void deleteCategory(String id) {    
  28.         categoryMap.remove(id);    
  29.         // Remove association of books    
  30.         bookMap.remove(id);    
  31.     }    
  32.     public void updateCategory(Category category) {    
  33.         categoryMap.put(category.getCategoryId(), category);    
  34.     }  
  35. }  

3.Service层

[java] view plain copy
  1. </pre><p></p><pre>  

 

[java] view plain copy
  1. package service;  
  2.   
  3. import javax.websocket.server.PathParam;  
  4. import javax.ws.rs.Consumes;  
  5. import javax.ws.rs.DELETE;  
  6. import javax.ws.rs.GET;  
  7. import javax.ws.rs.POST;  
  8. import javax.ws.rs.PUT;  
  9. import javax.ws.rs.Path;  
  10. import javax.ws.rs.Produces;  
  11. import javax.ws.rs.QueryParam;  
  12. import javax.ws.rs.WebApplicationException;  
  13. import javax.ws.rs.core.MediaType;  
  14. import javax.ws.rs.core.Response;  
  15. import javax.ws.rs.core.Response.ResponseBuilder;  
  16. import javax.ws.rs.core.Response.Status;  
  17.   
  18. import dao.CategoryDao;  
  19. import entity.Category;  
  20.   
  21. @Path("/categoryservice")  
  22. @Produces({"application/json","application/xml"})  
  23. public class CategoryService {  
  24.       
  25.     private CategoryDao categorydao = new CategoryDao();  
  26.   
  27.     public CategoryDao getCategorydao() {  
  28.         return categorydao;  
  29.     }  
  30.   
  31.     public void setCategorydao(CategoryDao categorydao) {  
  32.         this.categorydao = categorydao;  
  33.     }  
  34.       
  35.     @GET  
  36.     @Path("/category")  
  37.     @Produces(MediaType.APPLICATION_XML)  
  38.     public Category getCategory(@QueryParam("id") String id){  
  39.         System.out.println("获取的ID为"+id);  
  40.         Category category = categorydao.getCategory(id);  
  41.         if(category == null){  
  42.             ResponseBuilder builder = Response.status(Status.BAD_REQUEST);    
  43.             builder.type("application/xml");    
  44.             builder.entity("<error>Category Not Found</error>");    
  45.             throw new WebApplicationException(builder.build());  
  46.         }else{  
  47.             return category;  
  48.         }  
  49.     }  
  50.     /*@GET 
  51.     @Path("/category/{idno}") 
  52.     @Produces({"application/json","application/xml"}) 
  53.     public Category getCategory(@PathParam("idno") String id){ 
  54.         System.out.println("获取的ID为"+id); 
  55.         Category category = categorydao.getCategory(id); 
  56.         if(category == null){ 
  57.             ResponseBuilder builder = Response.status(Status.BAD_REQUEST);   
  58.             builder.type("application/xml");   
  59.             builder.entity("<error>Category Not Found</error>");   
  60.             throw new WebApplicationException(builder.build()); 
  61.         }else{ 
  62.             return category; 
  63.         } 
  64.     }*/  
  65.       
  66.     @POST  
  67.     @Path("/category")  
  68.     @Consumes({"application/json","application/xml"})  
  69.     public Response addCategory(Category category){  
  70.          Category cat = (Category) categorydao.getCategory(    
  71.                     category.getCategoryId());    
  72.         
  73.             if (cat != null) {    
  74.                 return Response.status(Status.BAD_REQUEST).build();    
  75.             } else {    
  76.                 categorydao.addCategory(category);    
  77.                 return Response.ok(category).build();    
  78.             }   
  79.     }  
  80.       
  81.          @DELETE    
  82.     @Path("/category/{id}")    
  83.     @Consumes({"application/json","application/xml"})    
  84.     public Response deleteCategory(@PathParam("id") String id) {    
  85.     
  86.         System.out.println("deleteCategory with category id : " + id);    
  87.     
  88.         Category cat = (Category) categorydao.getCategory(id);    
  89.         if (cat == null) {    
  90.             return Response.status(Status.BAD_REQUEST).build();    
  91.         } else {    
  92.             categorydao.deleteCategory(id);    
  93.             return Response.ok().build();    
  94.         }    
  95.     }    
  96.     
  97.     @PUT    
  98.     @Path("/category")    
  99.     @Consumes({"application/json","application/xml"})    
  100.     public Response updateCategory(Category category) {    
  101.     
  102.         System.out.println("updateCategory with category id : "    
  103.                 + category.getCategoryId());    
  104.     
  105.         Category cat = (Category) categorydao.getCategory(    
  106.                 category.getCategoryId());    
  107.         if (cat == null) {    
  108.             return Response.status(Status.BAD_REQUEST).build();    
  109.         } else {    
  110.             categorydao.updateCategory(category);    
  111.             return Response.ok(category).build();    
  112.         }    
  113.     }    
  114.     
  115.   
  116. }  



服务类注解:CategoryService的类声明上定义了@Path 和@Produces注解。@Path定义了URI路径,客户端可以通过这个路径访问到CategoryService对象。如@Path("/categoryservice"),那么URI请求,就可以是http://localhost:9000/categoryservice/。@Produces定义了服务类和方法生产内容的类型。如@Produces("application/xml"),那么CategoryService只会生产application/xml。方法注解:每个方法都和@Produces相关,它决定了这个方法生产什么样的响应。每个方法都有和HTTP方法映射的的注解,例如@GET 和@POST。方法中的@Path注解指定了该方法的URI。例如getCategory()方法上的@Path("/category/{id}"),可以使用http://localhost:9000/categoryservice/category/001,访问到category id 为001的分类。{id}就好比参数。接着,让我们看看@PathParam注解。@PathParam注解是用来给URI 路径一个模板变量,方法的输入参数。@PathParam("id") 就是URI中的 @Path ("/category/{id}")。

4.启动RESTFUL服务

 

[java] view plain copy
  1. package client;  
  2. import java.io.BufferedReader;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;  
  6. import entity.Category;  
  7. import service.CategoryService;  
  8. public class CategoryServerStart {  
  9.     public static void main(String[] args) {  
  10.         // Service instance  
  11.         CategoryService categoryService = new CategoryService();  
  12.         JAXRSServerFactoryBean restServer = new JAXRSServerFactoryBean();  
  13.         restServer.setResourceClasses(Category.class);  
  14.         restServer.setServiceBean(categoryService);  
  15.         restServer.setAddress("http://localhost:9000/");  
  16.         restServer.create();  
  17.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  18.         try {  
  19.             br.readLine();  
  20.         } catch (IOException e) {  
  21.         }  
  22.         System.out.println("Server Stopped");  
  23.         System.exit(0);  
  24.     }  
  25. }  

5.现在我们可以简单地测试一个查询方法。直接在浏览器中地址栏输入地址。采用@PathParam使用如下地址:http://localhost:9000/categoryservice/category/001,采用@QueryParam使用如下地址http://localhost:9000/categoryservice/category?id=001

看到的效果如下:

技术分享


原文(http://blog.csdn.net/wangyajin333/article/details/47175405)


(转)CXF开发RESTFUL的实例练习