cxf创建WebService

本文介绍如何使用Apache CXF框架创建WebService,包括配置Spring上下文、实现WebService接口及调用服务的方法。通过示例展示了从服务端配置到客户端调用的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用java创建webService可以使用axis  也可以使用 cxf,axis需要打包成 arr cxf可以直接发布
首先引用相应的jar包  以及 spring相关的jar包

在spring 配置文件的命名空间中引入cxf相关的包路径

xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
 http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"
 

 编写相应的接口类

 @WebService
public interface GreetingService {
	public String greeting(String userName);    
}

实现类

import java.util.Calendar;
import javax.jws.WebService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.company.cxf.service.GreetingService;
import com.company.cxf.dao.*;

@WebService(endpointInterface = "com.company.cxf.service.GreetingService")
public class GreetingServiceImpl implements GreetingService {
	 public String greeting(String userName){
		 //servletConfig.getServletContext().getRealPath("/");
		 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		 UserMapper us=(UserMapper)context.getBean("UserMapper");
		 return "Hello " + us.getUserName(userName) + ", currentTime is " + Calendar.getInstance().getTime();    
	 }
}

在 spring 配置文件中添加:

<jaxws:endpoint id="greetingService"
		implementor="com.company.cxf.service.impl.GreetingServiceImpl" 
		address="/GreetingService" />

在web.xml中添加配置

<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
	

至此服务端配置完成

调用类

package com.company.cxf.client;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.company.cxf.service.GreetingService;

public class TestGreetingService {
	public static void main(String[] args) {
		// 创建WebService客户端代理工厂
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		// 注册WebService接口
		factory.setServiceClass(GreetingService.class);
		// 设置WebService地址
		factory.setAddress("http://localhost:8080/cxf_webservice/GreetingService");
		GreetingService greetingService = (GreetingService) factory.create();
		System.out.println("invoke webservice...");
		System.out.println("message context is:" + greetingService.greeting("SEX"));
	}   
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值