杰瑞科技汇

webservice java cxf

Of course! Let's dive deep into creating a web service in Java using Apache CXF. This is a comprehensive guide covering the core concepts, a step-by-step example, and best practices.

webservice java cxf-图1
(图片来源网络,侵删)

What is Apache CXF?

Apache CXF™ is an open-source services framework. It's essentially a set of libraries that makes it incredibly easy to build and develop web services using standard protocols like SOAP and RESTful HTTP/JSON.

Think of it as a powerful toolkit that handles all the complex plumbing (like XML parsing, message formatting, and network communication) so you can focus on writing your business logic.

Key Features:

  • Dual Protocol Support: Supports both SOAP (with WS-* standards) and RESTful services.
  • Multiple Front-ends: You can develop services using a variety of programming models, including:
    • JAX-WS (Java API for XML Web Services): The standard and most common way to create SOAP services.
    • JAX-RS (Java API for RESTful Web Services): The standard for creating RESTful services.
  • Transport Independence: Works over HTTP, JMS, and more.
  • Data Binding: Flexible ways to map between Java objects and XML/JSON (e.g., JAXB, Aegis, JSON).
  • Framework Integration: Easily integrates with popular frameworks like Spring and Spring Boot.

Scenario: We'll Build a Simple JAX-WS SOAP Web Service

This is the classic "Hello World" example, which is perfect for understanding the fundamentals. We will create a web service that takes a name as input and returns a personalized greeting.

Technology Stack:

webservice java cxf-图2
(图片来源网络,侵删)
  • Java: Java 8 or higher.
  • Build Tool: Maven (recommended).
  • Server: Apache Tomcat (or any servlet container).
  • Framework: Apache CXF.

Step-by-Step Guide: Creating a JAX-WS Web Service with CXF

Step 1: Set Up Your Maven Project

First, create a new Maven project. The most important part is the pom.xml file, where we define the CXF dependencies.

<!-- 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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>cxf-hello-world</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <cxf.version>3.5.5</cxf.version>
    </properties>
    <dependencies>
        <!-- Apache CXF Core -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <!-- CXF Servlet for deployment to a web container -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <!-- For Jetty if you want to run it standalone -->
        <!--
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>${cxf.version}</version>
            <scope>test</scope>
        </dependency>
        -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>
        </plugins>
    </build>
</project>

Step 2: Create the Service Endpoint Interface (SEI)

This is a Java interface that defines the methods your web service will expose. Each method in this interface becomes a "web operation". We use JAX-WS annotations to configure it.

src/main/java/com/example/HelloWorld.java

package com.example;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
// @WebService marks this interface as a web service interface.
@WebService
// @SOAPBinding specifies the style (DOCUMENT) and use (LITERAL).
// DOCUMENT/LITERAL is the modern, most interoperable standard.
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL)
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 3: Create the Service Implementation Bean (SIB)

This is the concrete Java class that implements the HelloWorld interface. This is where you write your actual business logic.

webservice java cxf-图3
(图片来源网络,侵删)

src/main/java/com/example/HelloWorldImpl.java

package com.example;
import javax.jws.WebService;
// @WebService with an endpointInterface links this implementation
// to the SEI. This is crucial.
@WebService(endpointInterface = "com.example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        if (name == null || name.trim().isEmpty()) {
            return "Hello, Stranger!";
        }
        return "Hello, " + name + "!";
    }
}

Step 4: Deploy the Service (Web.xml Configuration)

Now, we need to tell the web server (like Tomcat) how to handle requests for our web service. We do this by configuring a web.xml file and a CXF servlet.

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- CXF Servlet -->
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Map all requests with /services/* to the CXF Servlet -->
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

Step 5: Publish the Service (Optional but Recommended)

You can publish your service programmatically. This is useful for testing or if you're not deploying to a traditional web container. You can do this in a main method.

src/main/java/com/example/Server.java

package com.example;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class Server {
    public static void main(String[] args) {
        // Create a factory for the JAX-WS server
        JaxWsServerFactoryBean serverFactory = new JaxWsServerFactoryBean();
        // Set the service implementation bean
        serverFactory.setServiceBean(new HelloWorldImpl());
        // Set the address to publish the service on
        serverFactory.setAddress("http://localhost:8080/services/hello");
        // Create and start the server
        serverFactory.create();
        System.out.println("Server started at http://localhost:8080/services/hello");
        System.out.println("WSDL is available at: http://localhost:8080/services/hello?wsdl");
    }
}

To run this, you'd need the Jetty dependency from the pom.xml commented out earlier. You can then run mvn compile exec:java -Dexec.mainClass="com.example.Server".

Step 6: Build and Deploy

  1. Build the project: mvn clean package
  2. Deploy: Copy the generated target/cxf-hello-world-1.0-SNAPSHOT.war file to your Tomcat's webapps directory.
  3. Start Tomcat.

Step 7: Test the Web Service

Your service is now live! You can test it in two ways.

Method 1: WSDL (Web Services Description Language)

The WSDL is a machine-readable XML file that describes your service's interface. CXF automatically generates it.

Open your web browser and go to: `http://localhost:8080/cxf

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