Springboot集成webservice介紹

什麼是Web Services?

Web Services 是應用程序組件
Web Services 使用開放協議進行通信
Web Services 是獨立的(self-contained)並可自我描述
Web Services 可通過使用UDDI來發現
Web Services 可被其他應用程序使用
XML 是 Web Services 的基礎

它如何工作?

基礎的 Web Services 平臺是 XML + HTTP。

HTTP 協議是最常用的因特網協議。

XML 提供了一種可用於不同的平臺和編程語言之間的語言。

Web services 平臺的元素:
SOAP (簡易對象訪問協議)
UDDI (通用描述、發現及整合)
WSDL (Web services 描述語言)
1,添加依賴

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web-services</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-frontend-jaxws</artifactId>
			<version>3.2.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http</artifactId>
			<version>3.2.5</version>
		</dependency>

2,服務端代碼
(1)配置類

package com.example.webservice.demo.service.server;


import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;

/**
 * @author LiHaitao
 * @description CxfConfig:
 * @date 2019/6/17 17:07
 **/
@Configuration
public class CxfConfig {

    @Bean
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(),"/test/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean
    public DemoService demoService() {
        return new DemoServiceImpl();
    }

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), demoService());
        endpoint.publish("/api");
        return endpoint;
    }

}

(2)Service接口

package com.example.webservice.demo.service.server;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.JAXBException;

/**
 * @author LiHaitao
 * @description DemoService:
 * @date 2019/6/17 17:05
 **/
@WebService(name = "DemoService", // 暴露服務名稱
        targetNamespace = "http://server.mq.primeton.com"// 命名空間,一般是接口的包名倒序
)
public interface DemoService {

    @WebMethod(operationName = "test")//方法名test
    public @WebResult(name = "QueryReturn") String test(@WebParam(name = "test")String code);


    @WebMethod(operationName = "testXml")//方法名test
    public @WebResult(name = "QueryReturn") String testXml(@WebParam(name = "test")String code) throws JAXBException;

}

(3)實現類接口

package com.example.webservice.demo.service.server;

import cn.hutool.json.JSONUtil;

import javax.jws.WebService;
import javax.xml.bind.JAXBException;

/**
 * @author LiHaitao
 * @description DemoServiceImpl:
 * @date 2019/6/17 17:06
 **/

@WebService(serviceName = "DemoService", // 與接口中指定的name一致
        targetNamespace = "http://server.mq.primeton.com", // 與接口中的命名空間一致,一般是接口的包名倒
        endpointInterface = "com.example.webservice.demo.service.server.DemoService"// 接口地址
)
public class DemoServiceImpl implements DemoService {
    /**
     * 返回json
     * @param orgCode
     * @return
     */
    @Override
    public String test(String orgCode) {
        User lihaitao =new User("lihaitao","18");
        return JSONUtil.toJsonStr(lihaitao);
    }
    /**
     * 返回xml
     * @param orgCode
     * @return
     */
    @Override
    public String testXml(String orgCode) throws JAXBException {
        User lihaitao =new User("lihaitao","18");
        return JaxResultUtil.objToXmlString(lihaitao);
    }
}


(4)實體類User

package com.example.webservice.demo.service.server;


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * @author LiHaitao
 * @description User:
 * @date 2020/1/6 17:51
 **/

@XmlRootElement(name = "user")
@XmlType(propOrder = { "name", "age" }) // 定義xml節點的順序,屬性必須在這
public class User {

    public User(){
        
    }
    public User(String name, String age) {
        this.name = name;
        this.age = age;
    }
    private String name;
    private String age;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @XmlElement(name = "age")
    public String getAge() {
        return age;
    }

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

(5)工具類

package com.example.webservice.demo.service.server;

import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

/**
* @Description:
* @Author:         Lihaitao
* @Date:       2020/1/7 17:22
* @UpdateUser:
* @UpdateRemark:
*/
@Slf4j
public class JaxResultUtil {

    private static JAXBContext context = null;

    private static Marshaller marshaller = null;

    static {
        try {
            context = JAXBContext.newInstance(User.class);
            marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        } catch (JAXBException e) {
            log.error("JaxResultUtil init exception", e);
        }
    }

    public static <T> String objToXmlString(T obj) throws JAXBException {
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }


}

2,客戶端
(1)Json格式數據:

	@Test
	public void test() throws Exception {
		JaxWsDynamicClientFactory dcflient=JaxWsDynamicClientFactory.newInstance();
		Client client=dcflient.createClient("http://localhost:8081/test/api?wsdl");
		Object[] objects1=client.invoke("test","");
		System.err.println(objects1[0].toString());
	}

在這裏插入圖片描述
(2)xml格式

@Test
	public void testXml() throws Exception {
		JaxWsDynamicClientFactory dcflient=JaxWsDynamicClientFactory.newInstance();
		Client client=dcflient.createClient("http://localhost:8081/test/api?wsdl");
		Object[] objects1=client.invoke("testXml","");
		System.err.println(objects1[0].toString());
	}

在這裏插入圖片描述
代碼地址:https://github.com/lihaitao1418064017/webservice-demo.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章