WebService笔记


webservice

Web Service是一个平台独立的,低耦合的,自包含的、基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的交互操作的应用程序。 [1]
Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的、专门的第三方软件或硬件, 就可相互交换数据或集成。依据Web Service规范实施的应用之间, 无论它们所使用的语言、 平台或内部协议是什么, 都可以相互交换数据。Web Service是自描述、 自包含的可用网络模块, 可以执行具体的业务功能。Web Service也很容易部署, 因为它们基于一些常规的产业标准以及已有的一些技术,诸如标准通用标记语言下的子集XML、HTTP。Web Service减少了应用接口的花费。Web Service为整个企业甚至多个组织之间的业务流程的集成提供了一个通用机制。

1.服务端

service:
@WebService
public interface HelloService {
    public String sayHello(String name);

}
impl:
public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "hello,"+name+",welcome ";
    }
}
发布:
public class Fabu {
    public static void main(String[] args) {
        JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
        // 设置发布地址
        String fbdz = "http://localhost:8000/ws/hello";
        factoryBean.setAddress(fbdz);
        //设置service类
        factoryBean.setServiceBean(new HelloServiceImpl());
        //添加日志输入输出拦截器
        factoryBean.getInInterceptors().add(new LoggingInInterceptor());
        factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
        //发布
        factoryBean.create();
        System.out.println("服务发布成功,端口8000");

pom.xml

properties>
    <cxf.version>3.0.1</cxf.version>
  </properties>
<dependencies>
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>${cxf.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>${cxf.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http-jetty</artifactId>
    <version>${cxf.version}</version>
  </dependency>

  <!--<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
  </dependency>-->
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.12</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>

</dependencies>

2.客户端

service:同上

pom.xml:同上

调用:

public class ClientTest {

    public static void main(String[] args) {
        JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
        //设置服务地址
        //http://localhost:8000/ws/hello
        String url = "http://localhost:8000/ws/hello";
        factoryBean.setAddress(url);
        //设置接口类型
        factoryBean.setServiceClass(HelloService.class);
        //创建链接
        HelloService helloService = factoryBean.create(HelloService.class);
        String s = helloService.sayHello("Mr.Zheng");
        System.out.println(s);
    }
}

3.spring整合cxf

发布:

pom.xml
<dependencies>
  <!-- CXF WS开发  -->
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.0.1</version>
  </dependency>

  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.2.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.2.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>3.0.1</version>
    <scope>compile</scope>
  </dependency>
</dependencies>
<build>
  <plugins>
    <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>
    <!-- 运行tomcat7方法:tomcat7:run -->
    <plugin>
      <groupId>org.apache.tomcat.maven</groupId>
      <artifactId>tomcat7-maven-plugin</artifactId>
      <version>2.2</version>
      <configuration>
        <!-- 指定端口 -->
        <port>8080</port>
        <!-- 请求路径 -->
        <path>/</path>
      </configuration>
    </plugin>
  </plugins>
</build>
web.xml配置
<!--配置cxfSerclet-->
  <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>/ws/*</url-pattern>
  </servlet-mapping>
    <!--spring容器配置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">
<!--spring整合cxf-->
    <!--访问地址:http://localhost:8080/ws/hello-->
<jaxws:server address="/hello">
    <jaxws:serviceBean>
        <bean class="vip.zhguo.serviceimpl.HelloServiceImpl"></bean>
    </jaxws:serviceBean>
</jaxws:server>

</beans>

远程调用:

pom.xml:同上

service:同上

impl:不需要

application.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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">
<!--spring整合cxf客户端-->
    <!--访问地址:http://localhost:8080/ws/hello-->
<jaxws:client address="http://localhost:8080/ws/hello"
              id="jaxwsClient"
              serviceClass="vip.zhguo.service.HelloService">
</jaxws:client>

</beans>

测试类

package vip.zhguo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import vip.zhguo.service.HelloService;
import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ClientTest {
    @Resource
    private HelloService helloService;
    @Test
    public void show(){
        String s = helloService.sayHello("Mr.Zheng");
        System.out.println(s);
    }
}

restful风格

1.服务端

1.1service:IUserService
package service;

import vip.zhguo.entity.User;

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;



@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);
}
1.2impl:UserServiceImpl
package service;

import vip.zhguo.entity.Car;
import vip.zhguo.entity.User;

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);
   }

}
1.3entity:

Car:

package vip.zhguo.entity;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Car")
public class Car {
   private Integer id;
   private String carName;
   private Double 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;
   }

   @Override
   public String toString() {
      return "Car [id=" + id + ", carName=" + carName + ", price=" + price + "]";
   }

}

User:

package vip.zhguo.entity;

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

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "User")
public class User {
   private Integer id;
   private String username;
   private String city;

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

   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;
   }

   @Override
   public String toString() {
      return "User [id=" + id + ", username=" + username + ", city=" + city + ", cars=" + cars + "]";
   }

}
1.4发布服务
package vip.zhguo;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.junit.Test;
import service.IUserService;
import service.UserServiceImpl;

public class Server {
    public static void main(String[] args) {
        JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
        String url = "http://localhost:8001/ws";
        factoryBean.setAddress(url);
        factoryBean.setServiceBean(new UserServiceImpl());
        factoryBean.getInInterceptors().add(new LoggingInInterceptor());
        factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
        factoryBean.create();
        System.out.println("服务发布成功,端口8001");
    }
}

2.客户端:

entity:同上
远程调用:
package vip.zhguo;

import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;
import vip.zhguo.entity.User;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

public class Client {
    @Test
    public void getOne(){
        String url = "http://localhost:8001/ws/userService/user/1";
        User user = WebClient
                .create(url)
                .accept(MediaType.APPLICATION_JSON)
                .get(User.class);
        System.out.println(user);
    }
    @Test
    public void getAll(){
        String url = "http://localhost:8001/ws/userService/user";
        List<User> users = (List) WebClient
                .create(url)
                .accept(MediaType.APPLICATION_JSON)
                .getCollection(User.class);
        for (User user : users){
            System.out.println(user);
        }
    }   @Test
    public void deleteById(){
        String url = "http://localhost:8001/ws/userService/user/10086";
        Response response =  WebClient
                .create(url)
                .delete();
    }
}

3.pom.xml

<dependencies>
  <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.0.1</version>
  </dependency>

  <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-simple</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>

  <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>

4.spring整合cxf

服务端

service:同上

entity:同上

web.xml:同webservice下的spring整合cxf

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:cxf="http://cxf.apache.org/core"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       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/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd">
<!--spring整合cxf-->
    <!--访问地址:http://localhost:8080/ws/hello-->
<jaxrs:server address="/userService">
    <jaxrs:serviceBeans>
        <bean class="vip.zhguo.service.UserServiceImpl"></bean>
    </jaxrs:serviceBeans>
</jaxrs:server>

</beans>
客户端

entity:同上

测试:

package vip.zhguo;

import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;
import vip.zhguo.entity.User;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

public class Client {
    @Test
    public void getOne(){
        String url = "http://localhost:8080/ws/userService/userService/user/1";
        User user = WebClient
                .create(url)
                .accept(MediaType.APPLICATION_JSON)
                .get(User.class);
        System.out.println(user);
    }
    @Test
    public void getAll(){
        String url = "http://localhost:8080/ws/userService/userService/user";
        List<User> users = (List) WebClient
                .create(url)
                .accept(MediaType.APPLICATION_JSON)
                .getCollection(User.class);
        for (User user : users){
            System.out.println(user);
        }
    }   @Test
    public void deleteById(){
        String url = "http://localhost:8080/ws/userService/userService/user/10086";
        Response response =  WebClient
                .create(url)
                .delete();
    }
}

声明:乐芙僧|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - WebService笔记


Do what I want to do