webservice开发spring整合cxf入门案例

一、创建服务端发布服务

  1. 添加依赖

 <dependencies>
        <!-- cxf 进行rs开发 必须导入  -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- 日志引入  -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <!-- 客户端 -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- 扩展json提供者 -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-extension-providers</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- 转换json工具包,被extension providers 依赖 -->
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.7</version>
        </dependency>

        <!-- spring 核心 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- spring web集成 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- spring 整合junit  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- junit 开发包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

 

  2. 创建服务接口

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 cn.itcast.domain.User;

//@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 finUserById(@PathParam("id") Integer id);

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

 

  3. 创建服务接口实现

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements IUserService {

    public void saveUser(User user) {
        System.out.println("save user:" + user);
    }

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

    public List<User> findAllUsers() {
        List<User> users = new ArrayList<User>();
        User user1 = new User();
        user1.setId(1);
        user1.setUsername("小明");
        user1.setCity("北京");

        List<Car> carList1 = new ArrayList<Car>();
        Car car1 = new Car();
        car1.setId(101);
        car1.setCarName("保时捷");
        car1.setPrice(1000000d);
        carList1.add(car1);
        Car car2 = new Car();
        car2.setId(102);
        car2.setCarName("宝马");
        car2.setPrice(400000d);
        carList1.add(car2);
        user1.setCars(carList1);

        users.add(user1);

        User user2 = new User();
        user2.setId(2);
        user2.setUsername("小丽");
        user2.setCity("上海");
        users.add(user2);

        return users;
    }

    public User finUserById(Integer id) {
        if (id == 1) {
            User user1 = new User();
            user1.setId(1);
            user1.setUsername("小明");
            user1.setCity("北京");
            return user1;
        }
        return null;
    }

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

}

 

  4. 配置web.xml

 <!-- 1. 加载spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-cxf.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 2.CXF的核心控制器 -->
    <servlet>
        <servlet-name>cxfServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxfServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

 

  5. 配置applicationContext-cxf.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">

    <!-- 1. 通过容器发布服务
    2. 服务访问地址 http://localhost:12345/web.xml配置/spring中的address地址/service接口地址
    3. 如: http://localhost:12345/ws/userService -->

    <jaxrs:server address="/userService" serviceClass="cn.itcast.service.UserServiceImpl"/>

</beans>

 

  6. 启动项目发布服务

 

二、创建客户端调用服务

import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import java.util.Collection;

public class WebServiceClient {
    /**
     * webservice客户端调用服务
     */

    // 请求默认xml格式
    @Test
    public void save() {

        User user = new User();
        user.setId(10);
        user.setUsername("刘备");

        //WebClient就是webservice客户端调用对象
        WebClient.create("http://localhost:12345/userService/user")
                .post(user);
    }

    // 指定请求数据为json格式
    @Test
    public void update() {
        User user = new User();
        user.setUsername("关羽");
        user.setId(12);
        user.setCity("荆州");
        WebClient.create("http://localhost:12345/userService/user")
                .type(MediaType.APPLICATION_JSON)
                .put(user);
    }

    @Test
    public void findById() {
        User user = WebClient.create("http://localhost:12345/userService/user/1")
                .type(MediaType.APPLICATION_JSON) //指定请求数据格式
                .accept(MediaType.APPLICATION_JSON)//响应数据格式
                .get(User.class);
        System.out.println(user);
    }

    @Test
    public void findAll() {
        Collection<? extends User> users = WebClient.create("http://localhost:12345/userService/user")
                .getCollection(User.class);
        System.out.println(users);
    }

    @Test
    public void delete() {
        WebClient.create("http://localhost:12345/userService/user/1")
                .delete();
    }

}

 

posted @ 2019-08-30 12:21  闲云陌路  阅读(1062)  评论(0编辑  收藏  举报