小工具知识网

当前位置: 首页 > 行业知识 > WebService使用

行业知识

WebService使用

2026-11-15 14:16:57 来源:互联网转载

java发布WebService

普通maven项目,使用原生jdk发布webservice

1.pom

           junit      junit      3.8.1      test            com.alibaba    fastjson    1.2.76  

2.接口

import javax.jws.WebService;import javax.jws.WebParam;/** * 对外发布服务的接口 * */@WebService//(targetNamespace = "http://wsImpl.com/")public interface HelloWs {public String sayHello(@WebParam(name="arg0")String name);}

3.实现类

import java.util.HashMap;import com.alibaba.fastjson.JSONObject;import com.ws.HelloWs;public class HelloWsImpl implements HelloWs{public String sayHello(String name) {    String jsonStr = json();System.out.print(name);return jsonStr;}//将map变成json并通过报文返回public String mapJson(){HashMap zhangsan = new HashMap();        zhangsan.put("name", "张三");        zhangsan.put("age", 18.4);        zhangsan.put("birthday", "1900-20-03");        zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});        zhangsan.put("null", null);        zhangsan.put("house", false);        //System.out.println(new JSONObject(zhangsan).toString());        String jsonStr = new JSONObject(zhangsan).toString();// TODO Auto-generated method stub        return jsonStr;}//原生json并通过报文返回public String json(){JSONObject zhangsan = new JSONObject();zhangsan.put("name", "张三");    zhangsan.put("age", 18.4);    zhangsan.put("birthday", "1900-20-03");    zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});    zhangsan.put("null", null);    zhangsan.put("house", false);    return zhangsan.toString();   }}

4.发布类

主方法运行后,直接在浏览器访问http://ip:8080/ws/hello?wsdl

import javax.xml.ws.Endpoint;import com.wsImpl.HelloWsImpl;public class Service {public static void main(String[] args) {//设置服务地址,换成你的ipEndpoint.publish("http://10.10.150.20:8080/ws/hello",new HelloWsImpl());System.out.println("发布WS服务成功");}}

5.调用方法

import java.io.IOException;import java.net.URL;import javax.xml.namespace.QName;import javax.xml.ws.Service;import com.ws.HelloWs;public class ProtoCall {    public static void main(String[] args) throws IOException {        //创建WSDL地址,不是服务地址        URL url = new URL("http://10.10.150.20:8080/ws/hello?wsdl");        /**         * QName是XML元素的限定名称,是组成XML的最基本的要素         * */        //创建服务名称        //1.namespaceURI - 命名空间地址        //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name        QName qname = new QName("http://wsImpl.com/", "HelloWsImplService");        //Service创建视图        //参数:        //1.wsdlDocumentLocation - 使用说明书地址        //2.serviceName - 服务名称        Service service = Service.create(url, qname);        //获取实现类        HelloWs mobileCodeWSSoap = service.getPort(HelloWs.class);        //调用查询方法        String result = mobileCodeWSSoap.sayHello("188888888");        System.out.println(result);    }}

CXF发布WebService

普通maven项目,使用apache.cxf发布webservice

1.pom

           junit      junit      3.8.1      test                  org.apache.cxf    cxf-rt-frontend-jaxws    3.4.3            org.apache.cxf    cxf-rt-transports-http-jetty    3.4.3    test        com.alibaba    fastjson    1.2.76  

2.接口

import javax.jws.WebService;import javax.jws.WebParam;/** * 对外发布服务的接口 * */@WebService//(targetNamespace = "http://wsImpl.com/")public interface HelloWs {public String sayHello(@WebParam(name="arg0")String name);}

3.实现类

import java.util.HashMap;import com.alibaba.fastjson.JSONObject;import com.ws.HelloWs;public class HelloWsImpl implements HelloWs{public String sayHello(String name) {    String jsonStr = json();System.out.print(name);return jsonStr;}//将map变成json并通过电文返回public String mapJson(){HashMap zhangsan = new HashMap();        zhangsan.put("name", "张三");        zhangsan.put("age", 18.4);        zhangsan.put("birthday", "1900-20-03");        zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});        zhangsan.put("null", null);        zhangsan.put("house", false);        //System.out.println(new JSONObject(zhangsan).toString());        String jsonStr = new JSONObject(zhangsan).toString();// TODO Auto-generated method stub        return jsonStr;}//原生json并通过电文返回public String json(){JSONObject zhangsan = new JSONObject();zhangsan.put("name", "张三");    zhangsan.put("age", 18.4);    zhangsan.put("birthday", "1900-20-03");    zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});    zhangsan.put("null", null);    zhangsan.put("house", false);    return zhangsan.toString();   }}

4.发布类

主方法运行后,直接在浏览器访问http://ip:8080/ws/hello?wsdl

import org.apache.cxf.interceptor.LoggingInInterceptor;import org.apache.cxf.interceptor.LoggingOutInterceptor;import org.apache.cxf.jaxws.JaxWsServerFactoryBean;import com.wsImpl.HelloWsImpl;public class Service {public static void main(String[] args) {                 /**        EndpointImpl发布方式        *///EndpointImpl publish = (EndpointImpl) Endpoint.publish("http://10.10.150.20:8080/ws/hello",new HelloWsImpl());//publish.getOutInterceptors().add(new LoggingOutInterceptor());//publish.getInInterceptors().add(new LoggingInInterceptor());        /**        工厂发布方式        */        //发布服务的工厂JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();//设置服务地址,换成你的ipfactory.setAddress("http://10.10.150.20:8080/ws/hello");//设置服务类factory.setServiceBean(new HelloWsImpl());//添加日志输入输出拦截器factory.getInInterceptors().add(new LoggingInInterceptor());          factory.getOutInterceptors().add(new LoggingOutInterceptor());//发布服务factory.create();System.out.println("发布WS服务成功");}}

5.调用方法

import java.io.IOException;import java.net.URL;import javax.xml.namespace.QName;import javax.xml.ws.Service;import com.ws.HelloWs;public class ProtoCall {    public static void main(String[] args) throws IOException {        //创建WSDL地址,不是服务地址        URL url = new URL("http://10.10.150.20:8080/ws/hello?wsdl");        /**         * QName是XML元素的限定名称,是组成XML的最基本的要素         * */        //创建服务名称        //1.namespaceURI - 命名空间地址        //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name        QName qname = new QName("http://wsImpl.com/", "HelloWsImplService");        //Service创建视图        //参数:        //1.wsdlDocumentLocation - 使用说明书地址        //2.serviceName - 服务名称        Service service = Service.create(url, qname);        //获取实现类        HelloWs mobileCodeWSSoap = service.getPort(HelloWs.class);        //调用查询方法        String result = mobileCodeWSSoap.sayHello("188888888");        System.out.println(result);    }}

整合SpringBoot发布及调用

1.pom依赖

                            org.springframework.boot            spring-boot-starter                                    org.springframework.boot            spring-boot-starter-web                                    org.springframework.boot            spring-boot-starter-web-services                                    org.apache.cxf            cxf-spring-boot-starter-jaxws            3.2.1                            org.apache.cxf            cxf-rt-transports-http            3.2.1                            org.apache.cxf            cxf-rt-ws-security            3.2.1                                            wsdl4j            wsdl4j            1.6.3                                    org.apache.cxf            cxf-spring-boot-starter-jaxrs            3.1.12                            org.wso2.apache.httpcomponents            httpclient            4.3.1.wso2v1                                    org.apache.axis            axis            1.4                                    commons-httpclient            commons-httpclient            3.1                                    javax.xml            jaxrpc            1.1                            commons-logging            commons-logging            1.0.4                                    commons-discovery            commons-discovery            0.5                                    com.alibaba            fastjson            1.2.47                            org.hibernate            hibernate-validator            6.0.18.Final                            junit            junit            test            

2.创建接口及实现类

接口

@WebService: 标记此接口为WebService接口;name为接口名称,targetNamespace为名称空间,可以自定义;

@WebMethod: 标记方法为WebService接口中的方法

@WebParam: 标记参数为WebService接口中方法参数,可限定名称(name = “abdc”),不限定默认为方法参数变量名

import javax.jws.WebMethod;import javax.jws.WebParam;import javax.jws.WebService;import javax.xml.ws.BindingType;import javax.xml.ws.soap.SOAPBinding;@WebService(name = "ServerServiceDemo", targetNamespace = "http://server.webservice.example.com")//@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)//将SOAP协议定义为1.2 Eclipse自带的WebService Brower只能解析soap1.1的协议,服务器端最好使用高版本的协议public interface ServerServiceDemo {    @WebMethod    String emrService(@WebParam String data);}

实现类

@WebService: 标记此接口为WebService接口;name为接口名称,targetNamespace为名称空间,可以自定义;endpointInterface为此类实现接口的全路径

@WebParam: 标记参数为WebService接口中方法参数,可限定名称(name = “abdc”),不限定默认为方法参数变量名

import com.alibaba.fastjson.JSONObject;import com.demo.axisDemo.service.ServerServiceDemo;import org.springframework.stereotype.Component;import javax.jws.WebParam;import javax.jws.WebService;@Component@WebService(name = "ServerServiceDemo", targetNamespace = "http://server.webservice.example.com",        endpointInterface = "com.demo.axisDemo.service.ServerServiceDemo")public class ServerServiceDemoImpl implements ServerServiceDemo {    @Override    public String emrService(@WebParam String data) {        if (null == data || "".equals(data.trim())) {            return "传入的参数为空";        }        System.out.println(data + "     -------------------------");        return "服务端返回 调用成功:" + data;    }}

3.编写配置类

@Configurationpublic class WebServiceConfig {/**  引入接口类*/    @Autowired    private ServerServiceDemo serverServiceDemo;    /**     * Apache CXF 核心架构是以BUS为核心,整合其他组件。     * Bus是CXF的主干, 为共享资源提供一个可配置的场所,作用类似于Spring的ApplicationContext,这些共享资源包括     * WSDl管理器、绑定工厂等。通过对BUS进行扩展,可以方便地容纳自己的资源,或者替换现有的资源。默认Bus实现基于Spring架构,     * 通过依赖注入,在运行时将组件串联起来。BusFactory负责Bus的创建。默认的BusFactory是SpringBusFactory,对应于默认     * 的Bus实现。在构造过程中,SpringBusFactory会搜索META-INF/cxf(包含在 CXF 的jar中)下的所有bean配置文件。     * 根据这些配置文件构建一个ApplicationContext。开发者也可以提供自己的配置文件来定制Bus。     */    @Bean(name = Bus.DEFAULT_BUS_ID)    public SpringBus springBus() {        return new SpringBus();    }            /*      * 此方法作用是改变项目中服务名的前缀名     * 此方法被注释后, 即不改变前缀名(默认是services), wsdl访问地址为 http://127.0.0.1:8080/services/ws/api?wsdl     * 去掉注释后wsdl访问地址为:http://127.0.0.1:8080/soap/ws/api?wsdl    //@Bean     //public ServletRegistrationBean dispatcherServlet() {    //    return new ServletRegistrationBean(new CXFServlet(), "/soap/*");    //}                /**     * 此处的EndpointImpl构造方法源码调用了JaxWsServiceFactoryBean及WebServiceFeature,     * 即在bus中开启webservice功能,并通过JaxWsServiceFactoryBean获取一个具体服务     *     * EndpointImpl端点对象,可以将其作用理解为连接bus与java WS服务     * WebServiceFeature 用于表示可以为 Web 服务启用或禁用的功能。     * */    @Bean    public Endpoint endpoint() {        EndpointImpl endpoint = new EndpointImpl(springBus(), serverServiceDemo);//363        endpoint.publish("/ws/api");        return endpoint;        }        }

4.客户端调用

Axis调用

import org.apache.axis.client.Call;import org.apache.axis.client.Service;import org.apache.axis.encoding.XMLType;import org.apache.axis.message.SOAPHeaderElement;import org.apache.cxf.configuration.security.AuthorizationPolicy;import org.apache.cxf.helpers.DOMUtils;import javax.xml.namespace.QName;import javax.xml.rpc.ParameterMode;import java.net.URL;public class CallUtiles {//接口地址    private static String publishUrl = "http://localhost:8080/services/ws/api?wsdl";    //wsdl中的targetNamespace    private static String nameSpaceURI = "http://server.webservice.example.com";        public static String get(String userStr) throws Exception {        Service service = new Service();        Call call = (Call) service.createCall();        call.setTargetEndpointAddress(new URL(publishUrl));                //指定接口路径,要调用的方法名        call.setOperationName(new QName(nameSpaceURI, "emrService"));                //如果没用@WebParam(name="name")来表明参数名,则方法的入参是啥,这边就必须传一样的参数名才行。不然报错。        call.addParameter("arg0", XMLType.XSD_STRING, ParameterMode.IN);                call.setReturnType(XMLType.XSD_STRING);        Object[] obj = new Object[]{userStr};        String result = (String) call.invoke(obj);        return result;    }}

java原生调用

import com.demo.axisDemo.service.ServerServiceDemo;import java.io.IOException;import java.net.URL;import javax.xml.namespace.QName;import javax.xml.ws.Service;public class ProtoCall {    public static void main(String[] args) throws IOException {        //创建WSDL地址,不是服务地址        URL url = new URL("http://127.0.0.1:9088/api/Domain/Xinda-ESB/esb-ec2erp?wsdl");        /**         * QName是XML元素的限定名称,是组成XML的最基本的要素         * */        //创建服务名称        //1.namespaceURI - 命名空间地址        //2.localPart - 服务名称,wsdl中的name,不是@WebService注解中的name        QName qname = new QName("http://service.erp.esb.xinda.com/IDTIWSReceEC", "IDTIWSReceEC");        //Service创建视图        //参数:        //1.wsdlDocumentLocation - 使用说明书地址        //2.serviceName - 服务名称        Service service = Service.create(url, qname);        //获取实现类        ServerServiceDemo mobileCodeWSSoap = service.getPort(ServerServiceDemo.class);        //调用查询方法        String result = mobileCodeWSSoap.emrService("188888888");        System.out.println(result);    }}

命令工具调用

cmd输入命令:wsdl2java -p com -d ../src -client -encoding utf-8  http://localhost:8080/admin/cxfService?wsdl注意:wsdl地址必须与发布publish中的相同,执行后会在../src生成代码,直接使用实现类get方法调用

上一篇:揭秘网络播放器源码的秘密,解析与实现之道

下一篇:MySQL常见的存储引擎介绍