1. 程式人生 > >spring 整合cxf 第二彈(經過測試)以xml格式進行資料互動

spring 整合cxf 第二彈(經過測試)以xml格式進行資料互動

為方便打大家學習以及應用,還是從配置檔案、jar、bean開始扯起。。。。。。奮鬥

1,web.xml 配置檔案基本配置

<web-app version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring MVC Application</display-name>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:spring-cxf.xml</param-value>
	</context-param>

    <servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!--spring 整合cxf web配置-->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
	</servlet>
	<!-- CXFServlet Mapping -->
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/cxf/*</url-pattern>
	</servlet-mapping>

</web-app>

這裡配置的cxf  servlet的對應關係,我的攔截路徑是/cxf/  下的所有url。

2,pom.xml 配置檔案,新增cxf開發需要的maven依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>WebCxf</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>WebCxf</name>

    <properties>
        <spring.version>4.1.1.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--CXF 依賴-->
        <!-- https://mvnrepository.com/artifact/org.apache.cxf/apache-cxf -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>apache-cxf</artifactId>
            <version>3.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>WebCxf</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3,簡單的spring配置檔案,這裡不多講了。
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--註解驅動-->
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.spring"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

4,針對cxf 實現的需要,增加spring-cxf.xml 配置檔案,這裡在web.xml 裡已經做了引入
<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-2.0.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd">
    <!-- Import Apache CXF Bean Definition -->
    <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"/>

    <!--模擬服務端① webservice-->
    <bean id="hello" class="com.spring.service.impl.HelloWordServiceImpl"/>
    <!--implementor="#hello" 指向bean id="hello"-->
    <jaxws:endpoint id="helloWorld" implementor="#hello" address="/helloWorld" />
    <!--模擬服務端②-->
    <bean id="user" class="com.spring.service.impl.UserServiceImpl"/>
    <jaxws:endpoint id="userPoint" implementor="#user" address="/user"/>
    <!--模擬客戶端①-->
    <jaxws:client id="client"
                  serviceClass="com.spring.service.IHelloWord"
                  address="http://localhost:8080/cxf/helloWorld" />
    <!--模擬客戶端②-->

</beans>

這裡demo應用的是<!--模擬服務端②-->的這個配置,其他與當前的demo沒有關係。

5,針對xml格式的資料 實現的工具封裝的實現。

package com.spring.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *生成xml格式的檔案
 * 解釋xml格式的字串
 */
public class XMLHandler {
    /**
     * 建立xml
     * @return
     */
    public static String createXML(){
        String xmlStr="";
        //doc 的工廠
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try{
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            document.setXmlVersion("1.0");
            //
            Element root = document.createElement("root");
            document.appendChild(root);
            //
            Element user = document.createElement("user");
            //
            Element id = document.createElement("id");
            id.setTextContent("1");
            user.appendChild(id);
            //
            Element name = document.createElement("name");
            name.setTextContent("張三");
            user.appendChild(name);
            //
            Element sex = document.createElement("sex");
            sex.setTextContent("男");
            user.appendChild(sex);
            //
            root.appendChild(user);
            //
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transFormer = transFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);

            //export string
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            transFormer.transform(domSource, new StreamResult(bos));
            xmlStr = bos.toString();
            System.out.println("輸出結果"+xmlStr);
            //通過輸出流輸出
            File file = new File("D:/out/user.xml");
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            StreamResult xmlResult = new StreamResult(out);
            transFormer.transform(domSource, xmlResult);
        }catch(Exception e){
            e.printStackTrace();
        }
        return xmlStr;
    }

    /*public static void main(String[] args) {
        createXML();
    }*/
    /**
     * 轉化xml格式的字串
     * <?xml version="1.0" encoding="UTF-8" standalone="no"?>
     *     <root>
     *         <user>
     *             <id>1</id>
     *             <name>張三</name>
     *             <sex>男</sex>
     *         </user>
     *     </root>
     */
    public static List<Map<String,Object>> parseXML(String xmlStr){
        List<Map<String,Object>> list=null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try{
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(xmlStr);
            InputSource is = new InputSource(sr);
            Document doc = builder.parse(is);
            //
            Element rootElement = doc.getDocumentElement();
            //
            NodeList users = rootElement.getElementsByTagName("user");
            //
            list=new ArrayList<Map<String, Object>>();
            for(int i=0;i<users.getLength();i++){
                Node node = users.item(i);
                NodeList childs = node.getChildNodes();
                Map<String,Object> map=new HashMap<String, Object>();
                for(int j=0;j<childs.getLength();j++){
                    Node childNode = childs.item(j);
                    String nodeName=childNode.getNodeName();
                    String value=childNode.getTextContent();
                    map.put(nodeName,value);

                }
                list.add(map);
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /*public static void main(String[] args) {
        String xmlStr="<?xml version='1.0' encoding='UTF-8' standalone='no'?><root><user><id>1</id><name>張三</name><sex>男</sex></user></root>";
        List<Map<String, Object>> list = parseXML(xmlStr);
        System.out.println("======"+list.toString());
    }*/
}

6,定義一個介面實現類,注意該class的註解。
package com.spring.service;

import javax.jws.WebParam;
import javax.jws.WebService;

/**
 * 
 */
@WebService
public interface IUser {
    //獲取xml格式的資料
    /**
     * 根據傳遞的條件獲取相簿資訊
     * xml的格式規範
     * <?xml version="1.0" encoding="UTF-8" standalone="no"?>
     *     <root>
     *         <user>
     *             <id>1</id>
     *             <name>張三</name>
     *             <sex>男</sex>
     *         </user>
     *     </root>
     * 這裡的WebParam必須指定,否則呼叫的時候返回null
     * @return
     */
    String getUser(@WebParam(name = "xmlStr")String xmlStr);
}

7,實現該介面,注意註解的應用。
package com.spring.service.impl;

import com.spring.service.IUser;
import com.spring.utils.XMLHandler;

import javax.jws.WebService;
import java.util.List;
import java.util.Map;

/**
 * 
 */
@WebService
public class UserServiceImpl implements IUser {

    @Override
    public String getUser(String xmlStr) {
        List<Map<String, Object>> list = XMLHandler.parseXML(xmlStr);
        return list.toString();
    }
}

8,main方法測試。
package com.spring.test;


import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import javax.xml.namespace.QName;

/**
 *
 */
public class TestClientCxf {
    public static void main(String[] args) throws Exception {
        String xmlStr="<?xml version='1.0' encoding='UTF-8' standalone='no'?><root><user><id>1</id><name>張三</name><sex>男</sex></user></root>";
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        org.apache.cxf.endpoint.Client client = dcf.createClient("http://localhost:8080/cxf/user?wsdl");
        //url為呼叫webService的wsdl地址
        QName name=new QName("http://service.spring.com/","getUser");
        //paramvalue為引數值
        Object[] objects=client.invoke(name,xmlStr);
        //呼叫web Service//輸出呼叫結果
        System.out.println("輸出結果:"+objects[0].toString());
        /*User user = new User(xmlStr);
        Object obj = user.getUser();
        System.out.println("========="+obj.toString());*/
    }
}
這裡注意:url 呼叫的webService的wsdl的地址 為瀏覽器訪問
http://localhost:8080/cxf/user?wsdl
路徑產生的,cxf的服務端搭建是否成功,需要再瀏覽器訪問一下你的配置路徑,/user 定義在spring-cxf.xml 的配置檔案
  <jaxws:endpoint id="userPoint" implementor="#user" address="/user"/>
效果圖:


//url為呼叫webService的wsdl地址
        QName name=new QName("http://service.spring.com/","getUser");

圖中標註的就是名稱空間,getUser  指的是介面的中定義的方法名稱。

到這裡基本就算結束了,總結的不夠精細,還望擔待。偷笑偷笑