zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【webservice】JAX-WS独立服务使用

服务 webservice 独立 WS 使用 JAX
2023-09-14 09:01:59 时间

【webservice】JAX-WS独立服务使用

建立maven Java项目,在项目中导入CXF jar包的支持,要提供jaxws服务,就引入jaxws的jar包,要提供jaxrs服务,就要引入jaxrs的jar包。

使用maven坐标

<!--要进行jaxws服务开发-->
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.0.1</version>
<dependency>
<!--内置jetty web服务器-->
<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>

要使用日志,同时需要导入log4j.properties配置文件.

编写服务端程序。编写实体类

public class User{
    private Integer id;
    private String username;
    private Sting city;
    private List<Car> cars = new ArrayList<Car>();
}
public class Car{
    private Integer id;
    private String carName;
    private Double price;
}

编写服务

@WebService
public interface IUserService {
    @WebMethod
    public String sayHello(String name);
    @WebMethod
    public List<Car> findCarsByUser(User user);
}

@WebService使用在类上面,标记类是WebService服务提供对象;

@WebMethod使用在方法上面,标记方法是WebService服务的提供方法。

服务实现

@WebService(endpointInterface = "cn.nwtxxb.cxf.services.IUserService",serviceName="userService")
public class UserServiceImpl implements IUserService {
    //简单参数传递
    public String sayHello(String name){
        return "hello,"+name;
    }
    //复杂参数传递
    public List<Car> findCarsByUser(User user){
        if("xiaoming").equals(user.getUsername()){
            List<Car> cars = new ArrayList<Car>();
            Car car1 = new Car();
            car1.setId(1);
            car1.setName("凯迪拉克");
            car1.setPrice(200000d);
            cars.add(car1);
        }
    }
}

@WebService注解设置endPointInterface接口服务完整类名,servicename是服务名称。

想将UserService的服务方法发布到网络上,供其他系统调用。

public static void main(String[] args){
    //使用CXF将UserService服务注册到网络上
    //1.服务的实现对象
    IUserService userService = new UserServiceImpl();
    //2.发布服务的地址
    String address = "http://localhost:9999/userService";
    //3.发布服务的地址
    Endpoint.publish(address,userService);
    System.out.println("服务已经启动...");
}

访问网址:http://localhost:9999/userService?wsdl

编写客户端操作

public static void main(String[] args){
    //编写客户端 调用发布WebService服务
    JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxProxyFactoryBean();
    jaxWsProxyFactoryBean.setServiceClass(IUserService.class);
    jaxWsproxyFactoryBean.setAddress("http://localhost:9999/userService");
    //创建调用远程服务代理对象
    IUserService proxy = (IUserService)jaxWsProxyFactoryBean.create();
    //调用代理对象的任何一个方法,都将通过网络调用web服务
    System.out.println(proxy.sayHello("你我他学习吧"));