杰瑞科技汇

Java如何用JSON实现WebService交互?

Of course! This is a very common and important topic in modern Java development. Here’s a comprehensive guide covering the most popular ways to create a JSON Web Service in Java, from modern standards to classic approaches.

Java如何用JSON实现WebService交互?-图1
(图片来源网络,侵删)

We'll cover three main approaches:

  1. JAX-RS with a Framework (The Modern Standard)
    • Jakarta EE (formerly Java EE) / Jakarta RESTful Web Services (JAX-RS)
    • This is the standard, annotation-driven way to create RESTful web services in Java. We'll use the Jakarta EE namespace (for newer versions) and the Jersey implementation, which is the reference implementation.
  2. Spring Boot (The De Facto Standard for Microservices)

    Spring Boot makes creating web services incredibly simple and fast with minimal configuration. It's the most popular choice for new projects.

  3. Classic Servlets (The Manual Way)

    This approach shows how to handle JSON parsing and writing manually without a framework. It's great for understanding the underlying mechanics.


Prerequisites

  • JDK 8 or higher
  • Maven or Gradle for project and dependency management.

Approach 1: JAX-RS with Jersey (The Standard)

This is the "Java EE" way. We'll create a simple REST endpoint that returns a JSON object.

Java如何用JSON实现WebService交互?-图2
(图片来源网络,侵删)

Step 1: Set up a Maven Project

Create a new Maven project and add the following dependencies to your pom.xml. We'll use the jersey-server and jersey-container-grizzly2 to run the server without a full application server like Tomcat.

<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>jaxrs-json-example</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>
        <jersey.version>3.1.4</jersey.version>
    </properties>
    <dependencies>
        <!-- JAX-RS API (Jakarta EE) -->
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>9.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- Jersey Server Implementation -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <!-- For automatic JSON conversion -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
            <version>${jersey.version}</version>
        </dependency>
    </dependencies>
</project>

Step 2: Create a Model Class (POJO)

This class will be automatically converted to JSON.

// src/main/java/com/example/model/User.java
package com.example.model;
public class User {
    private long id;
    private String name;
    private String email;
    // Default constructor is needed for JAX-RS
    public User() {}
    public User(long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }
    // Getters and Setters
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }
    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; }
}

Step 3: Create the Resource (REST Endpoint)

This is the core of your web service. The @Path annotation defines the URL path, and @GET defines it as a GET request.

// src/main/java/com/example/resource/UserResource.java
package com.example.resource;
import com.example.model.User;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/users")
public class UserResource {
    @GET
    @Path("/{userId}") // Example: /users/1
    @Produces(MediaType.APPLICATION_JSON) // Tells Jersey to produce JSON
    public getUserById(@PathParam("userId") long userId) {
        // In a real app, you would fetch this from a database
        if (userId == 1) {
            return new User(1, "John Doe", "john.doe@example.com");
        }
        return null; // Or throw a 404 Not Found exception
    }
    @GET
    @Path("/all")
    @Produces(MediaType.APPLICATION_JSON)
    public getAllUsers() {
        // In a real app, you would fetch a list from a database
        return java.util.List.of(
            new User(1, "John Doe", "john.doe@example.com"),
            new User(2, "Jane Smith", "jane.smith@example.com")
        );
    }
}

Step 4: Create the Application and Server Runner

This class will configure and start the Grizzly server.

Java如何用JSON实现WebService交互?-图3
(图片来源网络,侵删)
// src/main/java/com/example/Main.java
package com.example;
import com.example.resource.UserResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.grizzly.http.server.HttpServer;
import java.io.IOException;
import java.net.URI;
public class Main {
    public static final String BASE_URI = "http://localhost:8080/myapi/";
    public static void main(String[] args) throws IOException {
        // 1. Create a resource config that scans for JAX-RS resources and providers
        final ResourceConfig rc = new ResourceConfig().packages("com.example.resource");
        // 2. Create and start the HTTP server
        final 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...");
        System.in.read();
        server.shutdownNow();
    }
}

Note: You'll need to add import org.glassfish.grizzly.http.server.GrizzlyHttpServerFactory;

Step 5: Run and Test

  1. Run the Main.java class.

  2. Open your browser or a tool like Postman/Insomnia.

  3. Access the following URLs:

    • http://localhost:8080/myapi/users/1 Response:

      {
        "id": 1,
        "name": "John Doe",
        "email": "john.doe@example.com"
      }
    • http://localhost:8080/myapi/users/all Response:

      [
        {
          "id": 1,
          "name": "John Doe",
          "email": "john.doe@example.com"
        },
        {
          "id": 2,
          "name": "Jane Smith",
          "email": "jane.smith@example.com"
        }
      ]

Approach 2: Spring Boot (The Modern Favorite)

Spring Boot abstracts away much of the configuration. We'll use the spring-boot-starter-web which includes Tomcat and Jackson (for JSON) by default.

Step 1: Set up a Spring Boot Project

The easiest way is to use the Spring Initializr (start.spring.io).

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.x.x (uses Jakarta EE internally)
  • Dependencies: Spring Web

This will generate a project with pom.xml like this:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Step 2: Create a Model Class (POJO)

Same as before, but in the com.example.model package.

// src/main/java/com/example/model/User.java
package com.example.model;
public class User {
    private long id;
    private String name;
    private String email;
    public User() {}
    public User(long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email =
分享:
扫描分享到社交APP
上一篇
下一篇