注: 该篇主要介绍使用 CXF 创建WebService,若欲了解 AXIS 或 Jaxws,请移步 AXIS 创建WebService 或Jaxws 创建WebService
#1. 创建接口和实现
@WebService public interface IService { public String login(String name,String pwd); } @WebService(endpointInterface="ws.IService") public class ServiceImpl implements IService{ @Override public String login(String name, String pwd) { if(name.equals("123") && pwd.equals("456")){ return "登录成功"; }else{ return "用户名或密码错误"; } } }
可在实现类中注入WebServiceContext,然后获取messageContext对象,再获取其他信息
HttpServletRequest request = (HttpServletRequest) messageContext.get(AbstractHTTPDestination.HTTP_REQUEST);
#2. 发布服务
public class ServicePublish { public static void main(String[] args) { String url = "http://localhost:8080/ws/IService"; Endpoint.publish(url, new ServiceImpl()); System.out.println("发布成功,访问地址 http://localhost:8080/ws/IService?wsdl"); } }
#3. 调用(本地调用和远程调用)
a. 本地调用
public class LocalClient { public static void main(String[] args) { JaxWsProxyFactoryBean jaxws = new JaxWsProxyFactoryBean(); jaxws.setServiceClass(IService.class); jaxws.setAddress("http://localhost:8080/ws/IService"); IService service = (IService)jaxws.create(); System.out.println(service.login("123", "123")); System.out.println(service.login("123", "456")); } }
b. 远程调用
使用 cxf 的 wsdl2java 命令生成客户端,服务器端等文件.
用法: wsdl2java [options] <wsdl_url>
参数: -p生成代码包名,-d 指定生成代码目录 ,-client 生成客户端代码 ,-server 生成服务器代码,-impl 生成实现代码,-ant 生成build.xml文件,-all 生成所有相关文件
示例: wsdl2java -d java源文件目录\src -all -keep -verbose http://localhost:8080/ws/IService?wsdl
执行上述命令后调用服务
如欲了解相关Spring集成,请移步 CXF 创建 WebService (基于 Spring)public class RemoteClient { public static void main(String[] args) { ServiceImplService ser = new ServiceImplService(); IService service = ser.getPort(IService.class); System.out.println(service.login("123", "123")); System.out.println(service.login("123", "456")); } }