美文网首页
WebService入门

WebService入门

作者: 長得太帥忚四種檌 | 来源:发表于2018-07-17 19:07 被阅读11次

前言

Apache CXF官网:

http://cxf.apache.org/

简介

Apache CXF = Celtix + XFire,开始叫 Apache CeltiXfire,后来更名为 Apache CXF 了,以下简称为 CXF。
CXF 继承了 Celtix 和 XFire 两大开源项目的精华,提供了对 JAX-WS 全面的支持,并且提供了多种 Binding 、DataBinding、Transport 以及各种 Format 的支持,并且可以根据实际项目的需要,采用代码优先(Code First)或者 WSDL 优先(WSDL First)来轻松地实现 Web Services 的发布和使用。Apache CXF已经是一个正式的Apache顶级项目。

作用

用于多个服务器之间进行数据通信

JAX-WS

一.基本用法

1.创建Maven工程, 引入以下包的依赖

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.2.5</version>
        </dependency>

2. 准备好实体类

实体类

3.创建一个接口

package com.gongxm.ws.inter;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.gongxm.ws.domain.Car;
import com.gongxm.ws.domain.User;
@WebService
public interface IUserService {
    @WebMethod
    public String  sayHello(String name);
    @WebMethod
    public  List<Car> getCars(User user);
}

注意: 接口上需要加@WebService注解, 接口的方法需要加 @WebMethod注解

4.创建接口的实现类

package com.gongxm.ws.inter;
import java.util.List;
import javax.jws.WebService;
import com.gongxm.ws.domain.Car;
import com.gongxm.ws.domain.User;
@WebService(endpointInterface="com.gongxm.ws.inter.IUserService",name="IUserService")
public class IUserServiceImpl implements IUserService {
    public String sayHello(String name) {
        return "hello,"+name;
    }
    public List<Car> getCars(User user) {
        String name = user.getName();
        if("gongxm".equals(name)) {
            Car c1 = new Car("法拉利", "红色");
            Car c2 = new Car("保时捷","白色");
            List<Car> list = user.getList();
            list.add(c1);
            list.add(c2);
        }
        return user.getList();
    }
}

注意: 类上需要加@WebService注解, 并指定实现的接口包名, 以及服务的名称
@WebService(endpointInterface="com.gongxm.ws.inter.IUserService",name="IUserService")

5.部署服务

        //1.创建服务接口
        IUserService userService = new IUserServiceImpl();
        
        //2.指定访问地址
        String address = "http://localhost:8888/userService";
        
        //3.部署服务
        Endpoint.publish(address, userService);
        
        System.out.println("服务部署完成!");

6.如何使用部署好的服务

        //1.创建代理工厂Bean对象
        JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
        
        //2.指定服务的网络地址
        bean.setAddress("http://localhost:8888/userService");
        
        //3.使用指定的接口创建代理对象
        IUserService userService = bean.create(IUserService.class);
        
        //4.调用方法进行测试
        System.out.println(userService.sayHello("gongxm"));
        
        User user = new User();
        user.setName("gongxm");
        List<Car> cars = userService.getCars(user );
        System.out.println(cars);

二.整合到Spring中

-------------------------------------------服务端实现------------------------------------------------

1. 创建一个Maven web工程, 引入以下的包:

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.2.5</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>

        <!-- spring 框架 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

2.配置web.xml文件

    <!-- spring配置文件位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- spring核心监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- CXF服务配置 -->
    <servlet>
        <servlet-name>CXFService</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFService</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

注意:
这里是配置service的访问路径
配置成这样之后, 访问的路径就变成以下这样子了:
http://localhost:8088/项目名/services/userService

3.创建实体类和接口(跟上面的过程一样)

实体类和接口

4.配置applicationContext.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:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <jaxws:server id="userService" address="/userService"  <!-- 指定服务的地址 -->
        serviceClass="com.gongxm.ws.inter.IUserService">   <!-- 指定服务的接口 -->
        <jaxws:serviceBean>
            <bean class="com.gongxm.ws.inter.IUserServiceImpl" /><!-- 指定接口的实现类 -->
        </jaxws:serviceBean>
    </jaxws:server>
</beans>

5.部署web工程即可

------------------------------------------------客户端实现------------------------------------------------

1.创建一个Maven web工程, 引入跟上面服务端相同的包

2.创建实体类与接口

实体类和接口

3.配置applicationContext.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:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <jaxws:client id="userServiceClient"
        serviceClass="com.gongxm.ws.inter.IUserService"  <!-- 指定服务的接口 -->
        address="http://localhost:8088/cxf_ws_spring/services/userService"><!-- 指定服务的地址 -->
 
        <!-- 日志控制 -->
        <jaxws:inInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
        </jaxws:inInterceptors>
        <jaxws:outInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
        </jaxws:outInterceptors>
    </jaxws:client>
</beans>

4.访问服务

    //注入接口的实现类对象
    @Autowired
    IUserService userService;

    @Test
    public void Test() {    
        System.out.println(userService.sayHello("gongxm")); //调用服务的方法
    
        User user = new User();
        user.setName("gongxm");
        List<Car> cars = userService.getCars(user);        //调用服务的方法
        System.out.println(cars);
    }

JAX-RS

独立部署方式

-------------------------服务端代码--------------------------------------

1.创建一个Maven工程, 引入以下jar包

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.2.5</version>
        </dependency>

2.创建实体类

package com.gongxm.rs.domain;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="User")
public class User {
    private String name;
    private List<Car> list = new ArrayList<Car>();
    public User() {
    }
    public User(String name) {
        super();
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Car> getList() {
        return list;
    }
    public void setList(List<Car> list) {
        this.list = list;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", list=" + list + "]";
    }
}
-----------------------
package com.gongxm.rs.domain;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Car")
public class Car {
    private String name;
    private String color;
    public Car() {
    }
    public Car(String name, String color) {
        super();
        this.name = name;
        this.color = color;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    @Override
    public String toString() {
        return "Car [name=" + name + ", color=" + color + "]";
    }
}

注意:实体类上需要增加注解: @XmlRootElement(name="Car") 用于指定传输数据时转换成xml时的根元素

3.创建接口和实现类

package com.gongxm.rs.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 javax.ws.rs.core.MediaType;
import com.gongxm.rs.domain.User;
@Path("/userService")
@Produces("*/*")
public interface IUserService {
    @POST
    @Path("/user")
    @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public void saveUser(User user);
    
    @PUT
    @Path("/user")
    @Consumes(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public void updateUser(User user);
    
    @DELETE
    @Path("/user/{name}")
    @Consumes(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public void deleteUser(@PathParam("name")String name);
    @GET
    @Path("/user/{name}")
    @Consumes(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    @Produces(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public User findUserByName(@PathParam("name")String name);
    
    @GET
    @Path("/user")
    @Consumes(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    @Produces(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
    public List<User> findAllUser();

}

注意:
接口上需要使用注解:
@Path("/userService") //指定访问这个类的路径
@Produces("*/*") //指定返回数据类型
方法中使用注解:
@GET/POST/PUT/DELETE //指定访问方式
@Path("/user") //指定访问这个方法的路径
@Consumes(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) //指定接收的数据类型
@Produces(value= {MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) //指定返回的数据类型

方法中参数可以使用以下注解:
@PathParam("XXX") 指定使用路径中的内容作为参数
示例:

 @Path("/user/{name}")
 public User findUserByName(@PathParam("name")String name); //表示name参数接收的是路径中的{name}位置的内容

实现类:

package com.gongxm.rs.service;
import java.util.ArrayList;
import java.util.List;
import com.gongxm.rs.domain.Car;
import com.gongxm.rs.domain.User;
public class IUserServiceImpl implements IUserService {
    public void saveUser(User user) {
        System.out.println("保存用户信息:" + user);
    }
    public void updateUser(User user) {
        System.out.println("更新用户信息:" + user);
    }
    public void deleteUser(String name) {
        System.out.println("删除用户信息:" + name);
    }
    public User findUserByName(String name) {
        System.out.println("查找用户:" + name);
        User user = new User(name);
        Car c1 = new Car("法拉利", "红色");
        Car c2 = new Car("保时捷", "白色");
        List<Car> list = user.getList();
        list.add(c1);
        list.add(c2);
        return user;
    }
    public List<User> findAllUser() {
        User u1 = new User("小明");
        User u2 = new User("小红");

        List<User> list = new ArrayList<User>();
        list.add(u1);
        list.add(u2);
        return list;
    }
}

4.启动服务

        //1.创建服务器工厂
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
        //2.设置服务器地址
        factory.setAddress("http://localhost:8099/");
        //3.设置domain的实体类
        factory.setResourceClasses(User.class,Car.class);
        //4.设置接口
        factory.setServiceClass(IUserServiceImpl.class);
        //5.创建服务对象
        factory.create();
        System.out.println("服务启动了...");

--------------------------------------客户端代码--------------------------------------

1.必须导入以下jar包

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-client</artifactId>
            <version>3.2.5</version>
        </dependency>

2.访问服务端的代码实现

// 查找所有用户
Collection<? extends User> collection = WebClient.create("http://localhost:8099/userService/user")
.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_XML).getCollection(User.class);
System.out.println(collection);

//查找指定用户名的用户
User user2 = WebClient.create("http://localhost:8099/").path("userService/user/gongxm")
.type(MediaType.APPLICATION_JSON).get(User.class);
System.out.println(user2);

//更新用户信息
WebClient.create(baseAddress).path("userService/user").type(MediaType.APPLICATION_XML).put(user);

//删除用户
WebClient.create(baseAddress).path("userService/user/gongxm").type(MediaType.APPLICATION_JSON).delete();

解释:
create(baseAddress):创建访问指定地址的客户端对象
path(path): 拼接path路径到baseAddress中组成完整路径
type(xxx):指定Content-Type为指定的类型 (设置请求参数的类型)
accept(xxx):指定可以接收的参数的类型 (设置返回的参数的类型)
getCollection(Xxx.class): 获取指定类型的集合.(请求的结果为Xxx类型的一个集合)
get/post/put/delete 使用指定的请求方式进行访问

3.如果需要使用json格式数据, 需要导入以下两个包:

        <!--CXF扩展的提供者接口-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-extension-providers</artifactId>
            <version>3.2.5</version>
        </dependency>
        <!--提供者的实现类-->
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.7</version>
        </dependency>

整合到Spring中的方式

1.创建一个Maven Web项目, 导入以下依赖:

    <!--RS开发必须的jar包-->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxrs</artifactId>
        <version>3.2.5</version>
    </dependency>
    <!--日志工具-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
    </dependency>
    <!--spring web整合jar包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.0.0.RELEASE</version>
        <type>pom.lastUpdated</type>
    </dependency>
    <!--spring 核心包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.0.RELEASE</version>
        <type>pom.lastUpdated</type>
    </dependency>
    <!--RS客户端-->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-client</artifactId>
        <version>3.2.5</version>
    </dependency>

    <!--扩展提供者接口-->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
        <version>3.2.5</version>
    </dependency>
    <!--扩展提供者接口的默认实现类-->
    <dependency>
        <groupId>org.codehaus.jettison</groupId>
        <artifactId>jettison</artifactId>
        <version>1.3.7</version>
    </dependency>

2.配置web.xml

    <!-- spring配置文件位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- spring核心监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- CXF服务配置 -->
    <servlet>
        <servlet-name>CXFService</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFService</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

3.创建实体类和接口, 跟上面一样的:

实体类和接口

4.配置applicationContext.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">

    <jaxrs:server id="userService" address="/userService" >
        <jaxrs:serviceBeans>
            <bean class="com.gongxm.rs.service.IUserServiceImpl" />
        </jaxrs:serviceBeans>
        <!-- 日志工具配置 -->
        <jaxrs:inInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
        </jaxrs:inInterceptors>
        <jaxrs:outInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
        </jaxrs:outInterceptors>
    </jaxrs:server>
    
</beans>

注意:
这里的address配置的路径与接口上的路径重复了, 可以把接口上的注解删除:

去掉这个注解

5.启动服务即可

注意

最终的访问路径:
服务器地址 + 端口号 + 项目名称 + web.xml中配置的url-pattern + applicationContext.xml中配置的address + 接口上的@Path + 方法上的@Path

相关文章

网友评论

      本文标题:WebService入门

      本文链接:https://www.haomeiwen.com/subject/zkcwpftx.html