杰瑞科技汇

如何用Java实现WebService入门Demo?

Of course! Here is a comprehensive, step-by-step guide to creating a simple Java Web Service demo. We'll use JAX-RS (Java API for RESTful Web Services) with the reference implementation Jersey, which is the standard and easiest way to create RESTful services in Java.

This demo will be a "Hello World" style service that can be run directly from your IDE without needing a separate application server like Tomcat or JBoss (though we'll show how to do that too).

What We'll Build

A simple web service with two endpoints:

  1. GET /hello/{name}: Returns a personalized greeting.
  2. GET /hello: Returns a generic greeting.

Step 1: Set Up Your Project (Using Maven)

Maven is the standard build tool for Java projects and makes managing dependencies incredibly easy.

  1. Create a new Maven project in your favorite IDE (IntelliJ, Eclipse, VS Code).
  2. Use the following pom.xml file. It defines the necessary dependencies for Jersey and an embedded server (Grizzly) so we can run the service easily.

pom.xml

如何用Java实现WebService入门Demo?-图1

<?xml version="1.0" encoding="UTF-8"?>
<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>java-webservice-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- JAX-RS API (Jersey Implementation) -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>3.1.2</version>
        </dependency>
        <!-- For JSON support (optional, but good practice) -->
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
            <version>3.1.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
            <!-- Plugin to run the web service directly from Maven -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <mainClass>com.example.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 2: Create the Web Service Resource Class

This is the core of our application. It's a simple Java class with methods annotated to become web service endpoints.

Create a new package com.example and add the following class:

如何用Java实现WebService入门Demo?-图2

HelloResource.java

package com.example;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
 * This class defines our RESTful web service endpoints.
 * The @Path annotation specifies the base URI for all resource methods in this class.
 */
@Path("/hello")
public class HelloResource {
    /**
     * This method handles GET requests at the base path /hello.
     * It returns a simple plain text greeting.
     *
     * @return A greeting string.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getGenericGreeting() {
        return "Hello, World!";
    }
    /**
     * This method handles GET requests at the path /hello/{name}.
     * The {name} part is a path parameter.
     *
     * @param name The name to greet, extracted from the URL path.
     * @return A personalized greeting string.
     */
    @GET
    @Path("{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public String getPersonalizedGreeting(@PathParam("name") String name) {
        return "Hello, " + name + "!";
    }
    /**
     * This is an example of a POST request that accepts JSON.
     * It returns a JSON response.
     *
     * @param user A User object that will be automatically created from the JSON request body.
     * @return A JSON response confirming the user was received.
     */
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createUser(User user) {
        // In a real application, you would save this user to a database.
        System.out.println("Received user: " + user.getName() + ", Email: " + user.getEmail());
        // Return a 201 Created response with the user object in the body
        return Response.status(Response.Status.CREATED)
                       .entity(user)
                       .build();
    }
}
/**
 * A simple POJO (Plain Old Java Object) to represent a User.
 * Jersey will automatically map JSON to this object.
 */
class User {
    private String name;
    private String email;
    // No-arg constructor is required for Jersey
    public User() {}
    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

Annotations Explained:

如何用Java实现WebService入门Demo?-图3

  • @Path("/hello"): Defines the base URI path for this resource.
  • @GET: Indicates that this method responds to HTTP GET requests.
  • @POST: Indicates that this method responds to HTTP POST requests.
  • @Produces(MediaType.TEXT_PLAIN): Specifies the media type(s) that the method can produce and send back to the client. Here, it's plain text.
  • @Consumes(MediaType.APPLICATION_JSON): Specifies the media type(s) that the method can consume from the client. Here, it's JSON.
  • @Path("{name}"): Defines a sub-path with a variable part ({name}).
  • @PathParam("name"): Injects the value of the URI path parameter into the method argument.

Step 3: Create the Main Application Class

This class is the entry point for our web service. It will configure and start the embedded Grizzly server.

Main.java

package com.example;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.net.URI;
/**
 * Main class to start the Grizzly HTTP server and deploy the web service.
 */
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/myapp/";
    /**
     * Starts Grizzly HTTP server exposing the web service defined in the HelloResource class.
     */
    public static void main(String[] args) {
        // Create a resource config that scans for JAX-RS resources and providers
        // in the com.example package.
        final ResourceConfig rc = new ResourceConfig().packages("com.example");
        // Create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
        System.out.println("Jersey app started with WADL available at "
                + BASE_URI + "application.wadl\nHit enter to stop it...");
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            server.shutdownNow();
        }
    }
}

Step 4: Run and Test the Web Service

You now have a complete, runnable web service!

How to Run:

  1. Open a terminal or command prompt.
  2. Navigate to the root directory of your project (where pom.xml is located).
  3. Run the Maven command:
    mvn compile exec:java
  4. You should see the following output, indicating the server is running:
    Jersey app started with WADL available at http://localhost:8080/myapp/application.wadl
    Hit enter to stop it...

How to Test:

You

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