• WebService 之CXF(rs)之HelloWorld


    1.建立mavenjava项目

     1 <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/xsd/maven-4.0.0.xsd">
     2   <modelVersion>4.0.0</modelVersion>
     3   <groupId>cn.itcast.maven</groupId>
     4   <artifactId>cxf_rs_HelloWorld</artifactId>
     5   <version>0.0.1-SNAPSHOT</version>
     6   <name>cxf_rs_HelloWorld</name>
     7   
     8   <dependencies>
     9         <dependency>
    10             <groupId>org.apache.cxf</groupId>
    11             <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    12             <version>3.0.1</version>
    13         </dependency>
    14  
    15         <dependency>
    16             <groupId>org.apache.cxf</groupId>
    17             <artifactId>cxf-rt-transports-http-jetty</artifactId>
    18             <version>3.0.1</version>
    19         </dependency>
    20 
    21         <dependency>
    22             <groupId>org.slf4j</groupId>
    23             <artifactId>slf4j-log4j12</artifactId>
    24             <version>1.7.12</version>
    25         </dependency>
    26         
    27         <dependency>
    28             <groupId>org.apache.cxf</groupId>
    29             <artifactId>cxf-rt-rs-client</artifactId>
    30             <version>3.0.1</version>
    31         </dependency>
    32 
    33         <dependency>
    34             <groupId>org.apache.cxf</groupId>
    35             <artifactId>cxf-rt-rs-extension-providers</artifactId>
    36             <version>3.0.1</version>
    37         </dependency>
    38 
    39         <dependency>
    40             <groupId>org.codehaus.jettison</groupId>
    41             <artifactId>jettison</artifactId>
    42             <version>1.3.7</version>
    43         </dependency>
    44   </dependencies>
    45 </project>
    pom.xml
     1 ### direct log messages to stdout ###
     2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
     3 log4j.appender.stdout.Target=System.out
     4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
     5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
     6 
     7 ### direct messages to file mylog.log ###
     8 log4j.appender.file=org.apache.log4j.FileAppender
     9 log4j.appender.file.File=c:/mylog.log
    10 log4j.appender.file.layout=org.apache.log4j.PatternLayout
    11 log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    12 
    13 ### set log levels - for more verbose logging change 'info' to 'debug' ###
    14 
    15 log4j.rootLogger=info, stdout
    log4j-properties

    2.创建实体类和服务接口

     1 package cn.itcast.cxf.domain;
     2 
     3 import javax.xml.bind.annotation.XmlRootElement;
     4 
     5 @XmlRootElement(name = "Car")
     6 public class Car {
     7     private Integer id;
     8     private String carName;
     9     private Double price;
    10 
    11     public Integer getId() {
    12         return id;
    13     }
    14 
    15     public void setId(Integer id) {
    16         this.id = id;
    17     }
    18 
    19     public String getCarName() {
    20         return carName;
    21     }
    22 
    23     public void setCarName(String carName) {
    24         this.carName = carName;
    25     }
    26 
    27     public Double getPrice() {
    28         return price;
    29     }
    30 
    31     public void setPrice(Double price) {
    32         this.price = price;
    33     }
    34 
    35     @Override
    36     public String toString() {
    37         return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
    38     }
    39 
    40 }
    Car
     1 package cn.itcast.cxf.domain;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import javax.xml.bind.annotation.XmlRootElement;
     7 //指定序列化(转换xml或json)对象的名字
     8 @XmlRootElement(name = "User")
     9 public class User {
    10     private Integer id;
    11     private String username;
    12     private String city;
    13 
    14     private List<Car> cars = new ArrayList<Car>();
    15 
    16     public Integer getId() {
    17         return id;
    18     }
    19 
    20     public void setId(Integer id) {
    21         this.id = id;
    22     }
    23 
    24     public String getUsername() {
    25         return username;
    26     }
    27 
    28     public void setUsername(String username) {
    29         this.username = username;
    30     }
    31 
    32     public String getCity() {
    33         return city;
    34     }
    35 
    36     public void setCity(String city) {
    37         this.city = city;
    38     }
    39 
    40     public List<Car> getCars() {
    41         return cars;
    42     }
    43 
    44     public void setCars(List<Car> cars) {
    45         this.cars = cars;
    46     }
    47 
    48     @Override
    49     public String toString() {
    50         return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
    51     }
    52 
    53 }
    User
     1 package cn.itcast.cxf.service;
     2 
     3 import java.util.List;
     4 
     5 import javax.ws.rs.Consumes;
     6 import javax.ws.rs.DELETE;
     7 import javax.ws.rs.GET;
     8 import javax.ws.rs.POST;
     9 import javax.ws.rs.PUT;
    10 import javax.ws.rs.Path;
    11 import javax.ws.rs.PathParam;
    12 import javax.ws.rs.Produces;
    13 
    14 import cn.itcast.cxf.domain.User;
    15 
    16 @Path("/userService")//服务访问资源路径
    17 @Produces("*/*")生成(返回值)可以不写
    18 public interface IUserService {
    19 
    20     @POST
    21     @Path("/user")///userService/user
    22     @Consumes({ "application/xml", "application/json" })  //消费(客户端传过来的数据,即接受的数据)
    23     public void saveUser(User user);
    24 
    25     @PUT
    26     @Path("/user")
    27     @Consumes({ "application/xml", "application/json" })
    28     public void updateUser(User user);
    29 
    30     @GET
    31     @Path("/user")
    32     @Produces({ "application/xml", "application/json" })//产生(返回到客户端的数据的格式)
    33     public List<User> findAllUsers();
    34 
    35     @GET
    36     @Path("/user/{id}")
    37     @Consumes("application/xml")
    38     public User finUserById(@PathParam("id") Integer id);
    39 
    40     @DELETE
    41     @Path("/user/{id}")
    42     @Consumes("application/xml")
    43     public void deleteUser(@PathParam("id") Integer id);
    44 }
    IUservice
     1 package cn.itcast.cxf.service;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import cn.itcast.cxf.domain.Car;
     7 import cn.itcast.cxf.domain.User;
     8 
     9 public class UserServiceImpl implements IUserService {
    10 
    11     public void saveUser(User user) {
    12         System.out.println("save user:" + user);
    13     }
    14 
    15     public void updateUser(User user) {
    16         System.out.println("update user:" + user);
    17     }
    18 
    19     public List<User> findAllUsers() {
    20         List<User> users = new ArrayList<User>();
    21         User user1 = new User();
    22         user1.setId(1);
    23         user1.setUsername("小明");
    24         user1.setCity("北京");
    25 
    26         List<Car> carList1 = new ArrayList<Car>();
    27         Car car1 = new Car();
    28         car1.setId(101);
    29         car1.setCarName("保时捷");
    30         car1.setPrice(1000000d);
    31         carList1.add(car1);
    32         Car car2 = new Car();
    33         car2.setId(102);
    34         car2.setCarName("宝马");
    35         car2.setPrice(400000d);
    36         carList1.add(car2);
    37         user1.setCars(carList1);
    38 
    39         users.add(user1);
    40 
    41         User user2 = new User();
    42         user2.setId(2);
    43         user2.setUsername("小丽");
    44         user2.setCity("上海");
    45         users.add(user2);
    46 
    47         return users;
    48     }
    49 
    50     public User finUserById(Integer id) {
    51         if (id == 1) {
    52             User user1 = new User();
    53             user1.setId(1);
    54             user1.setUsername("小明");
    55             user1.setCity("北京");
    56             return user1;
    57         }
    58         return null;
    59     }
    60 
    61     public void deleteUser(Integer id) {
    62         System.out.println("delete user id :" + id);
    63     }
    64 
    65 }
    UserviceImpl

    @GET 查询 @PUT 修改 @POST 增加 @DELETE 删除

    3.发布服务

     1 package cn.itcast.cxf.rs.server;
     2 
     3 import org.apache.cxf.interceptor.LoggingInInterceptor;
     4 import org.apache.cxf.interceptor.LoggingOutInterceptor;
     5 import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
     6 
     7 import cn.itcast.cxf.domain.Car;
     8 import cn.itcast.cxf.domain.User;
     9 import cn.itcast.cxf.service.IUserService;
    10 import cn.itcast.cxf.service.UserServiceImpl;
    11 
    12 public class RS_Server {
    13     public static void main(String[] args) {
    14         IUserService userService = new UserServiceImpl();
    15 
    16         JAXRSServerFactoryBean restServer = new JAXRSServerFactoryBean();
    17         restServer.setResourceClasses(User.class, Car.class);
    18         restServer.setServiceBean(userService);
    19         restServer.setAddress("http://localhost:9999/");
    20 
    21         // 打印日志
    22         restServer.getInInterceptors().add(new LoggingInInterceptor());
    23         restServer.getOutInterceptors().add(new LoggingOutInterceptor());
    24 
    25         restServer.create();
    26     }
    27 }
    Server

    4.客户端程序的编写Webclient工具类使用

     1 package cn.itcast.cxf.rs.client;
     2 
     3 import java.util.Collection;
     4 
     5 import javax.ws.rs.core.MediaType;
     6 
     7 import org.apache.cxf.jaxrs.client.WebClient;
     8 
     9 import cn.itcast.cxf.domain.User;
    10 
    11 public class RS_Client {
    12     public static void main(String[] args) {
    13         User user = new User();
    14         user.setId(3);
    15         user.setUsername("小美");
    16         user.setCity("深圳");
    17 
    18         // 根据id查询
    19         WebClient client = WebClient.create("http://localhost:9999/");
    20         User responseUser = client.path("userService/user/1").accept(MediaType.APPLICATION_XML).get(User.class);
    21         System.out.println(responseUser);
    22 
    23         // 增加
    24         WebClient.create("http://localhost:9999/").path("userService/user").accept(MediaType.APPLICATION_XML)
    25                 .post(user);
    26 
    27         // 修改
    28         WebClient.create("http://localhost:9999/").path("userService/user").type(MediaType.APPLICATION_JSON).put(user);
    29 
    30         // 删除
    31         WebClient.create("http://localhost:9999/").path("userService/user/1").accept(MediaType.APPLICATION_XML)
    32                 .delete();
    33 
    34         // 查询所有用户
    35         Collection<? extends User> users = WebClient.create("http://localhost:9999/").path("userService/user")
    36                 .accept(MediaType.APPLICATION_JSON).getCollection(User.class);
    37         System.out.println(users);
    38     }
    39 }
    Client

     

  • 相关阅读:
    拟阵交
    HEOI2021退役记
    退役划水一
    上下界网络流学习笔记
    扩展卢卡斯学习笔记
    扩展中国剩余定理(EXCRT)学习笔记
    插头DP学习笔记
    如何优雅地生成仙人掌图
    Powerful Number 筛学习笔记
    边分治学习笔记
  • 原文地址:https://www.cnblogs.com/wwwzzz/p/8037318.html
Copyright © 2020-2023  润新知