Spring編寫服務器

在本章中,我們將瞭解如何使用Spring WS創建Web應用程序服務器。請參考以下步驟:

第1步: 按照Spring WS入門程序章節的介紹,創建一個名稱爲:countryService 的項目,並在這個項目中創建一個名爲com.yiibai的包。

第2步: 按照以下步驟中的說明創建:countries.xsd,以及域類:CountryRepositoryCountryEndPoint

第3步: 更新/WEB-INF子文件夾下spring-ws-servlet.xml

第4步: 最後一步是爲所有源文件和配置文件創建內容,並按照下面的說明導出應用程序。

文件:countries.xsd -

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema" 
   xmlns:tns = "http://www.yiibai/schemas"
   targetNamespace = "http://www.yiibai/schemas" 
   elementFormDefault = "qualified">

   <xs:element name = "getCountryRequest">
      <xs:complexType>
         <xs:sequence>
            <xs:element name = "name" type = "xs:string"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>

   <xs:element name = "getCountryResponse">
      <xs:complexType>
         <xs:sequence>
            <xs:element name = "country" type = "tns:country"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>

   <xs:complexType name = "country">
      <xs:sequence>
         <xs:element name = "name" type = "xs:string"/>
         <xs:element name = "population" type = "xs:int"/>
         <xs:element name = "capital" type = "xs:string"/>
         <xs:element name = "currency" type = "tns:currency"/>
      </xs:sequence>
   </xs:complexType>

   <xs:simpleType name = "currency">
      <xs:restriction base = "xs:string">
         <xs:enumeration value = "RMB"/>
     <xs:enumeration value = "GBP"/>
         <xs:enumeration value = "USD"/>
         <xs:enumeration value = "INR"/>
      </xs:restriction>
   </xs:simpleType>
</xs:schema>

創建項目

打開Eclise創建一個Maven項目,項目名稱爲: countryService ,完整的項目目錄結構如下 -

Spring編寫服務器

更新文件:pom.xml 中的代碼 -

<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.yiibai</groupId>
    <artifactId>countryService</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>countryService Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>2.4.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
            <version>1.6.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>countryService</finalName>
        <defaultGoal>compile</defaultGoal>
    </build>
</project>

創建域類

將文件countries.xsd 複製到 D:\eclipse-workspace\countryService\countryService\src\main\resources , 打開命令控制檯,進入到 D:\eclipse-workspace\countryService\countryService\src\main\resources 目錄並執行以下xjc 命令,以使用countries.xsd生成域類。

xjc -p com.yiibai countries.xsd

Maven將開始處理,並將在 com.yiibai 包中創建域類。

D:\eclipse-workspace\countryService\countryService\src\main\resources>
xjc -p com.yiibai countries.xsd
正在解析模式...
正在編譯模式...
com\yiibai\Country.java
com\yiibai\Currency.java
com\yiibai\GetCountryRequest.java
com\yiibai\GetCountryResponse.java
com\yiibai\ObjectFactory.java
com\yiibai\package-info.java

D:\eclipse-workspace\countryService\countryService\src\main\resources>

D:\eclipse-workspace\countryService\countryService\src\main文件夾中創建一個文件夾:java。 複製上面生成的所有類到D:\eclipse-workspace\countryService\countryService\src\main\java目錄中。 並且再創建兩個類:CountryRepositoryCountryEndPoint分別代表國家數據庫和國家/地區服務器。

CountryRepository.java - 類代碼如下所示 -

package com.yiibai;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.propertyeditors.CurrencyEditor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class CountryRepository {
    private static final List<Country> countries = new ArrayList<Country>();

    public CountryRepository() {
        initData();
    }

    public void initData() {
        Country us = new Country();
        us.setName("United States");
        us.setCapital("Washington");
        us.setCurrency(Currency.USD);
        us.setPopulation(46704314);

        countries.add(us);

        Country china = new Country();
        china.setName("China");
        china.setCapital("Beijing");
        china.setCurrency(Currency.RMB);
        china.setPopulation(138186860);

        countries.add(china);

        Country uk = new Country();
        uk.setName("United Kingdom");
        uk.setCapital("London");
        uk.setCurrency(Currency.GBP);
        uk.setPopulation(63705000);

        countries.add(uk);
    }

    public Country findCountry(String name) {
        Assert.notNull(name);
        Country result = null;

        for (Country country : countries) {
            if (name.trim().equals(country.getName())) {
                result = country;
            }
        }
        return result;
    }
}

文件:CountryEndPoint.java 的代碼如下 -

package com.yiibai;

import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.yiibai.Country;
import com.yiibai.CountryRepository;
import com.yiibai.GetCountryRequest;
import com.yiibai.GetCountryResponse;

@Endpoint
public class CountryEndPoint {
   private static final String NAMESPACE_URI = "http://www.yiibai/schemas";
   private CountryRepository countryRepository;

   @Autowired
   public CountryEndPoint(CountryRepository countryRepository) throws JDOMException {
      this.countryRepository = countryRepository;
   }
   @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
   @ResponsePayload
   public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) 
      throws JDOMException {

      Country country = countryRepository.findCountry(request.getName());
      GetCountryResponse response = new GetCountryResponse();
      response.setCountry(country);
      return response;
   }
}

文件:/WEB-INF/spring-ws-servlet.xml 中的代碼如下所示 -

<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:sws = "http://www.springframework.org/schema/web-services"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/web-services
   http://www.springframework.org/schema/web-services/web-services-2.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.yiibai"/>
   <sws:annotation-driven/>

   <sws:dynamic-wsdl id="countries"
      portTypeName = "CountriesPort"
      locationUri = "/countryService/"
      targetNamespace = "http://www.yiibai.com/definitions">
      <sws:xsd location = "/WEB-INF/countries.xsd"/>
   </sws:dynamic-wsdl>
</beans>

文件:/WEB-INF/web.xml 中的代碼如下所示 -

<web-app 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"
   version = "2.4">

   <display-name>Yiibai Country Service</display-name>

   <servlet>
      <servlet-name>spring-ws</servlet-name>
      <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet
      </servlet-class>
      <init-param>
         <param-name>transformWsdlLocations</param-name>
         <param-value>true</param-value>
      </init-param>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring-ws</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app>

運行該項目

創建源文件和配置文件後,構建完成後,發佈到Tomcat的服務器中。啓動Tomcat服務器完成後,使用標準瀏覽器進行POST請求 - http://localhost:8080/countryService /,並通過使用任何SOAP客戶端發出以下請求。

<x:Envelope xmlns:x = "http://schemas.xmlsoap.org/soap/envelope/" 
   xmlns:tns = "http://www.yiibai/schemas">
   <x:Header/>
   <x:Body>
      <tns:getCountryRequest>
         <tns:name>United States</tns:name>
      </tns:getCountryRequest>
   </x:Body>
</x:Envelope>

應該會看到類似以下的結果 -

<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <ns2:getCountryResponse xmlns:ns2 = "http://www.yiibai/schemas">
         <ns2:country>
            <ns2:name>United States</ns2:name>
            <ns2:population>46704314</ns2:population>
            <ns2:capital>Washington</ns2:capital>
            <ns2:currency>USD</ns2:currency>
         </ns2:country>
      </ns2:getCountryResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>