杰瑞科技汇

Java XML WebService如何实现高效集成?

Of course! This is a classic and important topic in Java development. Here's a comprehensive guide to Java XML Web Services, covering the core concepts, the two main approaches, and modern alternatives.

Java XML WebService如何实现高效集成?-图1
(图片来源网络,侵删)

What is a Web Service?

At its heart, a web service is a method of communication between two electronic devices over a network. It's a software system designed to support interoperable machine-to-machine interaction over a network.

Key Characteristics:

  • Self-contained: It has its own functionality.
  • Self-describing: It uses XML (or another standard like JSON) to describe its capabilities and how to use it (via a WSDL file).
  • Discoverable: It can be located and accessed by other applications.

The most common standards for XML-based web services are SOAP (Simple Object Access Protocol) and REST (Representational State Transfer), though REST typically uses JSON today.


SOAP Web Services with Java

SOAP is a protocol standard for XML-based messaging. It's highly standardized, robust, and often used in enterprise environments where security, transactions, and reliability are critical.

Java XML WebService如何实现高效集成?-图2
(图片来源网络,侵删)

Key Concepts in SOAP

  • WSDL (Web Services Description Language): An XML file that describes your web service. It acts as a "contract" for clients. It defines:
    • The available operations (methods).
    • The messages (request and response formats).
    • The communication protocol (e.g., SOAP over HTTP).
    • The location (URL) of the service.
  • SOAP Message: The actual XML message sent over the network. It has a strict structure:
    • Envelope: The root element, identifying the XML as a SOAP message.
    • Header: Optional block for application-specific information (like security headers).
    • Body: Contains the actual message payload (the data for the request or response).
    • Fault: Optional element for reporting errors.

Java Technologies for SOAP (The Classic Way: JAX-WS)

For a long time, the standard way to create and consume SOAP web services in Java was using JAX-WS (Java API for XML Web Services).

JAX-WS is part of the Java EE standard and is included in the JDK.

A. Creating a SOAP Web Service (JAX-WS)

There are two primary ways to create a JAX-WS service:

  1. Bottom-Up (Contract-Last): You write your Java code first, and then a tool generates the WSDL for you.
  2. Top-Down (Contract-First): You write the WSDL/XSD first, and then a tool generates the Java code skeleton. This is generally the recommended approach for interoperability.

Let's look at a simple Bottom-Up example.

Step 1: Create a Java Interface (The Service Endpoint Interface - SEI)

This interface will define the methods that your web service will expose.

// src/main/java/com/example/HelloWorld.java
package com.example;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.WebParam;
// @WebService marks this class as a web service endpoint.
@WebService
public interface HelloWorld {
    // @WebMethod marks this method as a web service operation.
    // @WebParam specifies the name of the parameter in the SOAP message.
    @WebMethod
    String sayHello(@WebParam(name = "name") String name);
}

Step 2: Create a Java Implementation Class

This class implements the interface.

// src/main/java/com/example/HelloWorldImpl.java
package com.example;
import javax.jws.WebService;
// @WebService specifies the service name, target namespace, and SEI.
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
}

Step 3: Publish the Service

You need a main class to start a simple HTTP server and publish your service.

// src/main/java/com/example/HelloWorldPublisher.java
package com.example;
import javax.xml.ws.Endpoint;
public class HelloWorldPublisher {
    public static void main(String[] args) {
        // The URL where the service will be published.
        String url = "http://localhost:8888/ws/hello";
        // Publish the implementation.
        Endpoint.publish(url, new HelloWorldImpl());
        System.out.println("Service is published at: " + url);
        System.out.println("WSDL is available at: " + url + "?wsdl");
    }
}

Step 4: Generate and Use the WSDL

When you run HelloWorldPublisher, the JAX-WS runtime automatically generates the WSDL for you at http://localhost:8888/ws/hello?wsdl. Clients can use this WSDL to generate their own client-side stubs and invoke your service.

B. Consuming a SOAP Web Service (JAX-WS)

Consuming a service is also straightforward. You use the wsimport command-line tool (included with the JDK) to generate client-side Java classes from a WSDL file.

  1. Generate Client Stubs:

    wsimport -p com.example.client -keep http://localhost:8888/ws/hello?wsdl
    • -p com.example.client: The package for the generated classes.
    • -keep: Keep the generated source files.
  2. Use the Generated Client: The wsimport tool creates a service class (e.g., HelloWorldService) and a HelloWorld proxy. You can use them like this:

    // src/main/java/com/example/client/HelloWorldClient.java
    package com.example.client;
    public class HelloWorldClient {
        public static void main(String[] args) {
            // Create an instance of the generated service class.
            HelloWorldService service = new HelloWorldService();
            // Get the port (the proxy for the web service).
            HelloWorld helloPort = service.getHelloWorldPort();
            // Invoke the web service operation.
            String response = helloPort.sayHello("SOAP Client");
            System.out.println(response); // Output: Hello, SOAP Client!
        }
    }

RESTful Web Services with XML

While REST is an architectural style, not a protocol, it's the dominant paradigm for modern web services. Instead of a single, complex XML message like SOAP, REST uses standard HTTP methods (GET, POST, PUT, DELETE) to operate on resources identified by URIs.

Key Characteristics of REST:

  • Stateless: Each request from a client must contain all the information needed to understand and process it.
  • Resource-Oriented: Everything is a resource (e.g., /users, /products/123).
  • Use HTTP Methods:
    • GET: Retrieve a resource.
    • POST: Create a new resource.
    • PUT: Update an existing resource.
    • DELETE: Delete a resource.
  • Standard Data Formats: Typically uses JSON, but XML is also perfectly valid.

Java Technologies for REST (JAX-RS)

JAX-RS (Java API for RESTful Web Services) is the Java standard for creating RESTful web services. The reference implementation is Jersey, and another popular one is RESTEasy.

JAX-RS is also part of the Java EE standard.

A. Creating a RESTful Web Service (JAX-RS)

Step 1: Add Dependencies

If you're using a build tool like Maven, add the Jersey dependency.

<!-- pom.xml -->
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
    <version>2.39.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.39.1</version>
</dependency>

Step 2: Create a Resource Class

Annotate a POJO with JAX-RS annotations to make it a web resource.

// src/main/java/com/example/MyResource.java
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
// @Path defines the base URI for the resource.
@Path("myresource")
public class MyResource {
    // @GET handles HTTP GET requests.
    // @Produces specifies the MIME media types the method can produce (e.g., XML).
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Response getXml() {
        // Create a simple XML string.
        String xml = "<greeting><message>Hello from JAX-RS!</message></greeting>";
        // Return a 200 OK response with the XML entity.
        return Response.ok(xml).build();
    }
    @GET
    @Path("json")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getJson() {
        String json = "{\"message\": \"Hello from JAX-RS!\"}";
        return Response.ok(json).build();
    }
}

**Step 3: Create and Start the

分享:
扫描分享到社交APP
上一篇
下一篇