天天看点

cxf实现restful风格的webservice

cxf实现restful风格的webservice

restful风格的webservice基于http协议使用xml或json传输数据,而不需要使用soap、wsdl、uuid。

涉及到比较重要的注解:

注解 作用
@XmlRootElement 指定根元素,作用:客户端与服务端传递对象数据时候,序列化为xml或json的根元素的名称
@Path 访问当前服务接口的方法路径
@Consumes 服务端支持的请求的数据格式
@Produces 服务端支持的响应数据格式

服务端

pom文件中添加的依赖

<dependencies>
  <!--jaxrs 支持包-->
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.0.1</version>
  </dependency>
  <!--内置的jetty服务器-->
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http-jetty</artifactId>
    <version>3.0.1</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
  </dependency>
  <!--客户端调用时候使用的包(WebClient工具类调用服务端)-->
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-rs-client</artifactId>
    <version>3.0.1</version>
  </dependency>

    <!--基于restful风格的webservice,客户端与服务端之间可以传递
    json,这个就是json支持相关包cxf‐rt‐rs‐extension‐providers-->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-extension-providers</artifactId>
      <version>3.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jettison</groupId>
      <artifactId>jettison</artifactId>
      <version>1.3.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <pluginManagement>
      <plugins>
<!--         maven的jdk编译插件-->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven‐compiler‐plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF‐8</encoding>
            <showWarnings>true</showWarnings>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
           

实体类

@XmlRootElement(name = "Car")
public class Car {

    private Integer id;

    private String carName;

    private Double price;

    public Car() {
    }

    public Car(Integer id, String carName, Double price) {
        this.id = id;
        this.carName = carName;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}
           
@XmlRootElement(name = "User")
public class User {

    private Integer id;

    private String username;

    private String city;

    private List<Car> cars = new ArrayList<>();


    public User() {
    }

    public User(Integer id, String username, String city, List<Car> cars) {
        this.id = id;
        this.username = username;
        this.city = city;
        this.cars = cars;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public List<Car> getCars() {
        return cars;
    }

    public void setCars(List<Car> cars) {
        this.cars = cars;
    }
}

           

服务接口

/**
 * 基于http协议可以使用xml或json传输数据
 * @author dell
 * @date 2020/11/14 16:44
 */
@Path("/userService")
@Produces("*/*")
public interface IUserService {

    @POST
    @Path("/user")  //路径:访问当前服务接口的方法路径
    //服务端支持的请求的数据格式
    @Consumes({"application/xml", "application/json"})
    public void saveUser(User user);

    @PUT
    @Path("/user")
    @Consumes({"application/xml", "application/json"})
    public void updateUser(User user);

    @GET
    @Path("/user")
    //服务端支持的响应数据格式
    @Produces({"application/xml", "application/json"})
    public List<User> findAllUsers();

    @GET
    @Path("/user/{id}")
    @Consumes("application/xml")
    @Produces({"application/xml", "application/json"})
    public User findUserById(@PathParam("id")Integer id);

    @DELETE
    @Path("/user/{id}")
    @Consumes({"application/xml", "application/json"})
    public void deleteUser(@PathParam("id") Integer id);
}

           

服务接口实现类

public class UserServiceImpl implements IUserService {
    @Override
    public void saveUser(User user) {
        System.out.println("save user:" + user);
    }

    @Override
    public void updateUser(User user) {
        System.out.println("update user:" + user);
    }

    @Override
    public List<User> findAllUsers() {
        List<User> userList = new ArrayList<>();

        List<Car> cars = new ArrayList<>();
        Car car1 = new Car(101,"保时捷",1000000d);
        Car car2 = new Car(102, "林肯", 4000000d);
        cars.add(car2);
        cars.add(car1);

        User user1 = new User(1, "小明", "广州", cars);
        User user2 = new User(2, "小丽", "深圳", cars);

        userList.add(user1);
        userList.add(user2);

        return userList;
    }

    @Override
    public User findUserById(Integer id) {
        if (id == 1) {
            return new User(1, "小明", "广州", null);
        }
        return null;
    }

    @Override
    public void deleteUser(Integer id) {
        System.out.println("delete user id:" + id);
    }
}
           

主类

public class App 
{
    public static void main( String[] args )
    {
        //创建服务工厂
        JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
        //设置服务地址
        jaxrsServerFactoryBean.setAddress("http://localhost:8001/rs");
        //实例化服务类
        jaxrsServerFactoryBean.setServiceBean(new UserServiceImpl());;
        //添加日志拦截器
        jaxrsServerFactoryBean.getOutFaultInterceptors().add(new LoggingOutInterceptor());;
        jaxrsServerFactoryBean.getInFaultInterceptors().add(new LoggingInInterceptor());

        //创建服务
        jaxrsServerFactoryBean.create();

        System.out.println("发布服务");

    }
}
           

客户端

pom文件中的依赖,比server端的多了一个WebClient依赖

<dependencies>
    <!--jaxrs 支持包-->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>3.0.1</version>
    </dependency>
    <!--内置的jetty服务器-->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http-jetty</artifactId>
      <version>3.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.12</version>
    </dependency>
    <!--客户端调用时候使用的包(WebClient工具类调用服务端)-->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-client</artifactId>
      <version>3.0.1</version>
    </dependency>

    <!--基于restful风格的webservice,客户端与服务端之间可以传递
    json,这个就是json支持相关包cxf‐rt‐rs‐extension‐providers-->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-extension-providers</artifactId>
      <version>3.0.1</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jettison</groupId>
      <artifactId>jettison</artifactId>
      <version>1.3.7</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <pluginManagement>
      <plugins>
        <!--         maven的jdk编译插件-->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven‐compiler‐plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF‐8</encoding>
            <showWarnings>true</showWarnings>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
           

实体类

Car类

/**
 * @XmlRootElement指定根元素,作用:客户端与服务端传递对象数据时候,序列化为xml
 * 或json的根元素的名称
 * 客户端与服务端传递XML:
 *
 * @author dell
 * @date 2020/11/14 16:41
 */
@XmlRootElement(name = "Car")
public class Car {

    private Integer id;

    private String carName;

    private Double price;

    public Car() {
    }

    public Car(Integer id, String carName, Double price) {
        this.id = id;
        this.carName = carName;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

           

User类

@XmlRootElement(name = "User")
public class User {

    private Integer id;

    private String username;

    private String city;

    private List<Car> cars = new ArrayList<>();


    public User() {
    }

    public User(Integer id, String username, String city, List<Car> cars) {
        this.id = id;
        this.username = username;
        this.city = city;
        this.cars = cars;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public List<Car> getCars() {
        return cars;
    }

    public void setCars(List<Car> cars) {
        this.cars = cars;
    }
}

           

测试

@Test
    public void shouldAnswerWithTrue()
    {
        //assertTrue( true );
        WebClient.create("http://localhost:8001/rs/userService/user")
                .type(MediaType.APPLICATION_JSON)
                .post(new User(100, "kobe", "gz", null));
    }


    @Test
    public void testUpdate() {
        WebClient.create("http://localhost:8001/rs/userService/user")
                .type(MediaType.APPLICATION_JSON)
                .put(new User(200, "sks", "sz", null));
    }


    @Test
    public void testDelete() {
        WebClient.create("http://localhost:8001/rs/userService/user/1")
                .type(MediaType.APPLICATION_XML)
                .delete();
    }
           

运行测试类后可以看到 服务端控制台 打印输出了以下内容:

cxf实现restful风格的webservice

参考

  • List item