杰瑞科技汇

cxf wsdl2java命令如何正确生成Java代码?

Of course! Here is a comprehensive guide on how to use the cxf wsdl2java tool to generate Java client code from a WSDL (Web Services Description Language) file.

cxf wsdl2java命令如何正确生成Java代码?-图1
(图片来源网络,侵删)

What is wsdl2java?

wsdl2java is a command-line tool provided by Apache CXF, a powerful open-source framework for developing web services. Its primary function is to read a WSDL file and automatically generate a complete set of Java source files (client stubs, service interfaces, data objects, etc.) that you can use to easily interact with the web service.

This process is called stub-based web service development. Instead of manually constructing SOAP messages, you work with familiar Java objects and method calls, and the CXF framework handles the underlying communication.


Step-by-Step Guide

Here’s a complete walkthrough, from setting up your environment to using the generated code.

Step 1: Prerequisites

  1. Java Development Kit (JDK): You need JDK 8 or newer installed.
  2. Apache CXF: You need to have CXF installed. The easiest way is to download the binary distribution from the Apache CXF website.

Step 2: Set Up Your Environment

After downloading and extracting the CXF distribution, you need to add the bin directory to your system's PATH environment variable. This allows you to run the wsdl2java command from anywhere in your terminal.

cxf wsdl2java命令如何正确生成Java代码?-图2
(图片来源网络,侵删)

Example for Linux/macOS:

# Add this line to your ~/.bashrc or ~/.zshrc file
export PATH=/path/to/your/apache-cxf-<version>/bin:$PATH
# Then, apply the changes to your current terminal session
source ~/.bashrc

Example for Windows:

# In Command Prompt
setx PATH "%PATH%;C:\path\to\your\apache-cxf-<version>\bin"
# In PowerShell
$oldPath = [Environment]::GetEnvironmentVariable("PATH", "User")
$newPath = "$oldPath;C:\path\to\your\apache-cxf-<version>\bin"
[Environment]::SetEnvironmentVariable("PATH", $newPath, "User")

To verify the installation, open a new terminal and run:

wsdl2java -version

You should see the CXF version number.

cxf wsdl2java命令如何正确生成Java代码?-图3
(图片来源网络,侵删)

Step 3: Get a WSDL File

You need a WSDL file to start with. You can either:

  • Use a public WSDL for testing (e.g., from a weather service).
  • Get the WSDL URL from the service provider.
  • Use a local WSDL file on your machine.

For this example, let's use a public WSDL from W3Schools for testing: http://www.dneonline.com/calculator.asmx?wsdl

Step 4: Generate the Java Code

Now, navigate to your project directory (or a directory where you want to store the generated code) and run the wsdl2java command.

Basic Command:

wsdl2java http://www.dneonline.com/calculator.asmx?wsdl

This will download the WSDL and generate a package structure like com.dneonline.www.calculator in the current directory.

Important Common Options:

  • -p <package.name>: (Highly Recommended) Specifies the Java package name for the generated code. Without this, you might get a long, default package name.
    wsdl2java -p com.example.calculator http://www.dneonline.com/calculator.asmx?wsdl
  • -client: Generates a standalone Java client class. This is very useful for testing.
    wsdl2java -client -p com.example.calculator http://www.dneonline.com/calculator.asmx?wsdl
  • -server: Generates a server-side skeleton (JAX-WS endpoints). Useful if you are implementing the service.
  • -d <output-directory>: Specifies the directory where the generated files should be placed. For example, src/main/java.
    wsdl2java -d src/main/java -p com.example.calculator http://www.dneonline.com/calculator.asmx?wsdl
  • -autoNameResolution: Automatically resolves name conflicts that can occur with complex WSDLs.
  • -exsh true: Generates sample code for exception classes.

Recommended Command for a Project:

# Create a src directory if it doesn't exist
mkdir -p src/main/java
# Run wsdl2java with recommended options
wsdl2java -d src/main/java -p com.example.calculator -client http://www.dneonline.com/calculator.asmx?wsdl

Step 5: Understand the Generated Files

After running the command, you will find several Java files in the specified directory. The key files for a client are:

  1. Calculator.java: This is the Service Interface. It defines the methods you can call on the web service (e.g., add(), subtract()).
  2. CalculatorService.java: This is the Service Class. It acts as a factory for creating instances of the service interface.
  3. Add.java, AddResponse.java, etc.: These are JAXB Data Objects. They represent the request and response messages defined in the WSDL. For example, Add holds the input parameters for the add operation, and AddResponse holds the result.
  4. CalculatorServiceClient.java: This is the Standalone Client (if you used the -client flag). It's a runnable class that demonstrates how to use the generated code to make a web service call.

Step 6: Use the Generated Code in Your Application

Here’s how you can use the generated code in your own Java application.

  1. Create a new Java project in your favorite IDE (IntelliJ, Eclipse, VS Code).

  2. Add the CXF dependencies to your project. You need the core CXF libraries and JAXB. If you're using Maven, add this to your pom.xml:

    <dependencies>
        <!-- CXF Core -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-core</artifactId>
            <version>3.5.5</version> <!-- Use the latest version -->
        </dependency>
        <!-- CXF JAX-WS API and Implementation -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!-- JAXB is needed for data binding -->
        <dependency>
            <groupId>jakarta.xml.bind</groupId>
            <artifactId>jakarta.xml.bind-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>3.0.2</version>
        </dependency>
    </dependencies>
  3. Copy the generated Java files (from src/main/java) into your project's source folder.

  4. Write your client code:

    package com.example.calculator.client;
    import com.example.calculator.Calculator;
    import com.example.calculator.CalculatorService;
    import com.example.calculator.Add;
    import com.example.calculator.AddResponse;
    public class MyCalculatorClient {
        public static void main(String[] args) {
            // 1. Create an instance of the Service class
            CalculatorService service = new CalculatorService();
            // 2. Get the port (the interface) from the service
            Calculator calculator = service.getCalculatorSoap12(); // or getCalculatorSoap()
            // 3. Create the request data object
            Add addRequest = new Add();
            addRequest.setIntA(10);
            addRequest.setIntB(5);
            // 4. Invoke the web service method
            AddResponse addResponse = calculator.add(addRequest);
            // 5. Process the response
            int result = addResponse.getAddResult();
            System.out.println("10 + 5 = " + result);
            // Example of another operation
            com.example.calculator.Subtract subRequest = new com.example.calculator.Subtract();
            subRequest.setIntA(20);
            subRequest.setIntB(8);
            com.example.calculator.SubtractResponse subResponse = calculator.subtract(subRequest);
            System.out.println("20 - 8 = " + subResponse.getSubtractResult());
        }
    }

Troubleshooting

  • ClassNotFoundException: This usually means you haven't included the CXF (and JAXB) dependencies in your project's classpath.
  • javax.xml.ws.WebServiceException: Could not find metadata: This can happen if the WSDL is complex. Try adding the -autoNameResolution flag to your wsdl2java command.
  • HTTPS Issues (SSLHandshakeException): If the WSDL is at an https URL and the server uses a self-signed certificate, you may run into SSL errors. You can configure a trust manager to ignore these errors, but be aware of the security implications. A simple workaround for development is often to use http if the service provider allows it.
分享:
扫描分享到社交APP
上一篇
下一篇