加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

WebService学习笔记:使用CXF+Spring搭建WebService服务端和客户

发布时间:2020-12-16 22:23:34 所属栏目:安全 来源:网络整理
导读:随着互联网技术的发展,WebService的使用也越来越广泛,WebService的常用框架有Apache Axis1,Apache Axis2,Codehaus XFile,Apache CXF等。今天主要是使用CXF框架结合Spring搭一个WebService服务端和客户端。 首先新建一个Web项目WebService_CXF_Server,w

随着互联网技术的发展,WebService的使用也越来越广泛,WebService的常用框架有Apache Axis1,Apache Axis2,Codehaus XFile,Apache CXF等。今天主要是使用CXF框架结合Spring搭一个WebService服务端和客户端。

首先新建一个Web项目WebService_CXF_Server,web.xml配置如下:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>WebService_CXF_Server</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:config/applicationContext-server.xml</param-value>
	</context-param>
	<!-- 监听的配置 -->
	<listener>
		<!-- spring监听的配置 -->
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!--  <listener>  
            <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
     </listener>  -->
	
	<!-- servlet的配置 -->
	<servlet>
		<!-- cxf的servlet名 -->
		<servlet-name>CXFServlet</servlet-name>
		<!-- cxf的servlet类 -->
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<!-- cxf的servlet名 -->
		<servlet-name>CXFServlet</servlet-name>
		<!-- 触发cxf的servlet的 -->
		<url-pattern>/ws/*</url-pattern>
	</servlet-mapping>

</web-app>
导入WebService需要的jar包:

在src下新建一个config文件夹,在config文件夹下新建一个applicationContext-server.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">

	<!-- 还需要引入以下3个关于CXF的资源文件,这三个文件在cxf.jar中 -->

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
	<!-- implementor参数:指明具体的实现类;address参数:指明这个webservice的相对地址 -->
	 <jaxws:endpoint id="helloService" implementor="com.cxf.test.HelloServiceImpl" address="/helloService" />

</beans>
新建一个package命名为com.cxf.test,在package下新建HelloService.java,HelloServiceImpl.java,ResponseData.java内容如下:

HelloService.java

package com.cxf.test;

import javax.jws.WebService;

/**
 * @description
 * @date:(2015-8-21 下午9:16:12)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
@WebService
public interface HelloService {
	
	String sayHello(String name);
	
	ResponseData getData();

}

HelloServiceImpl.java

package com.cxf.test;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * @description
 * @date:(2015-8-21 下午9:16:37)
 * @author 
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
@WebService(endpointInterface = "com.cxf.test.HelloService",serviceName = "HelloService")
public class HelloServiceImpl implements HelloService{

	@Override
	 @WebMethod
	public String sayHello(String name) {
		
		return "Webservice服务端:Hello World!===>"+name;
		
	}

	@Override
	public ResponseData getData() {
		ResponseData data=new ResponseData();
		data.setAge(25);
		data.setName("张三");
		data.setSex("男");
		
		return data;
	}
	
	
	
	

}

ResponseData.java
package com.cxf.test;

import java.io.Serializable;

/**
 * @description
 * @date:(2016-1-29 上午11:16:24)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class ResponseData implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	
	private int age;
	
	private String sex;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
}

因为我使用logback输出日志,在src下新建logback.xml,内容如下:

<configuration>   
   
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">   
    <!-- encoder 默认配置为PatternLayoutEncoder -->   
    <encoder>   
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>   
    </encoder>   
  </appender>   
   
  <root level="ALL">             
    <appender-ref ref="CONSOLE" />   
  </root>     
     
 </configuration> 
然后把项目加进Tomcat,启动服务,没有报错,说明就成功了。在浏览器地址栏输入:

http://localhost:8080/WebService_CXF_Server/ws,出现:


点击蓝色连接,出现:


接下来,新建一个Java Project项目,WebService_CXF_Client,他需要的jar包:


新建一个package命名com.cxf.test,在目录下新建HelloService.java,ResponseData.java,TestHelloService.java:

HelloService.java

package com.cxf.test;

import javax.jws.WebService;

/**
 * @description
 * @date:(2015-8-21 下午9:16:12)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
@WebService
public interface HelloService {
	
	String sayHello(String name);
	
	ResponseData getData();

}

ResponseData.java

package com.cxf.test;

import java.io.Serializable;

/**
 * @description
 * @date:(2016-1-29 上午11:16:24)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class ResponseData implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	
	private int age;
	
	private String sex;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

}

TestHelloService.java

package com.cxf.test;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @description
 * @date:(2016-1-28 上午11:17:16)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class TestHelloService {
	
	  private static Logger logger=LoggerFactory.getLogger(TestHelloService.class);
	
	  public static void main(String[] args) {
	   
		  //方法一
		  submitDepondsOnSpring();
		  
		  //方法二
//		  submit();
	           
	    }
	  
	  /**
	   * 使用Spring依赖注入的客户端
	   * */
	  public static void submitDepondsOnSpring(){
		  
		    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-client.xml");
	        HelloService helloService = (HelloService) context.getBean("client");
	        String response = helloService.sayHello("Tom");
	        ResponseData responseData=(ResponseData)helloService.getData();
	        logger.info("sayHello() method response:{}",response);
	        logger.info("getData() method response:name={},age={},sex={}",responseData.getName(),responseData.getAge(),responseData.getSex());
	  }
	  
	  /**
	   * 不使用Spring的webservice客户端
	   * */
	  public static void submit(){
		//创建WebService客户端代理工厂
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        //注册WebService接口
        factory.setServiceClass(HelloService.class);
        //设置WebService地址
        factory.setAddress("http://localhost:8080/WebService_CXF_Server/ws/helloService");
        HelloService hello = (HelloService)factory.create();
        //调用webservice接口方法
        String response2=hello.sayHello("Tom");//返回sucess
        System.out.println(response2);
	  }

}

在src目录下新建applicationContext-client.xml,logback.xml:

applicationContext-client.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-3.2.xsd
                       http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<!-- 还需要引入以下3个关于CXF的资源文件,这三个文件在cxf.jar中 -->

	 <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
    
    <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
        <property name="serviceClass" value="com.cxf.test.HelloService" />
        <property name="address" value="http://localhost:8080/WebService_CXF_Server/ws/helloService" />
    </bean>

    <bean id="client" class="com.cxf.test.HelloService" factory-bean="clientFactory" factory-method="create" />

</beans>

logback.xml

<configuration>   
   
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">   
    <!-- encoder 默认配置为PatternLayoutEncoder -->   
    <encoder>   
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>   
    </encoder>   
  </appender>   
   
  <root level="DEBUG">             
    <appender-ref ref="CONSOLE" />   
  </root>     
     
 </configuration> 
启动WebService服务端,运行TestHelloService.java

输出:

10:47:52.528 [main] INFO ?com.cxf.test.TestHelloService - sayHello() method response:Webservice服务端:Hello World!===>Tom
10:47:52.528 [main] INFO ?com.cxf.test.TestHelloService - getData() method response:name=张三,age=25,sex=男

这样环境就搭建好了,我使用的CXF版本是apache-cxf-2.7.18,Spring时用的是spring-framework-3.2.2。


jar包下载地址:http://download.csdn.net/detail/polo_longsan/9422886

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读