杰瑞科技汇

Java webservice post如何正确调用与传参?

Of course! Creating a Java Web Service that handles a POST request is a fundamental task in web development. The most modern and standard way to do this in Java is using JAX-RS (Java API for RESTful Web Services), with the reference implementation being Jersey.

I'll guide you through this process in two parts:

  1. The Modern Standard (Recommended): Using JAX-RS with Jersey and a Maven project.
  2. The Classic (Legacy) Way: Using JAX-WS (Java API for XML Web Services), which is older and more complex for simple REST operations.

Part 1: Modern JAX-RS (Jersey) for a RESTful POST

This is the standard approach for building RESTful web services in Java. It's clean, simple, and widely used.

Step 1: Set up a Maven Project

First, you need a Maven project. If you're using an IDE like IntelliJ IDEA or Eclipse, you can create one easily. Make sure you have the pom.xml file with the necessary dependencies for Jersey and a server (like Jetty, which is great for testing).

Java webservice post如何正确调用与传参?-图1

Here's a minimal pom.xml:

<?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-post-webservice</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <jersey.version>2.39</jersey.version>
    </properties>
    <dependencies>
        <!-- Jersey Server -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <!-- JSON support (e.g., for marshalling/unmarshalling POJOs) -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <!-- For easy JSON <-> POJO mapping (Jackson is the default) -->
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey.version}</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>
        </plugins>
    </build>
</project>

Step 2: Create a Data Model (POJO)

This class will represent the data you expect to receive in the POST request, typically in JSON format.

User.java

package com.example.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement // Needed for JAX-B, which Jersey uses for XML/JSON conversion
public class User {
    private String name;
    private String email;
    private int age;
    // No-arg constructor is required for Jersey to instantiate the object
    public User() {
    }
    public User(String name, String email, int age) {
        this.name = name;
        this.email = email;
        this.age = age;
    }
    // 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; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

Step 3: Create the Resource Class (The Web Service Endpoint)

This is the core of your service. It defines the URL path (/api/users) and the POST method.

Java webservice post如何正确调用与传参?-图2

UserResource.java

package com.example.resource;
import com.example.model.User;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@Path("/api/users") // The base path for this resource
public class UserResource {
    // Use a thread-safe list to store users for this example
    private static List<User> users = new CopyOnWriteArrayList<>();
    @Context
    UriInfo uriInfo;
    /**
     * Handles POST requests to create a new user.
     * @param user The User object, automatically deserialized from the JSON request body.
     * @return A Response object with the status and location of the new resource.
     */
    @POST
    @Consumes(MediaType.APPLICATION_JSON) // Specifies that this method consumes JSON
    public Response createUser(User user) {
        if (user == null || user.getName() == null || user.getEmail() == null) {
            return Response.status(Response.Status.BAD_REQUEST)
                           .entity("Invalid user data: name and email are required.")
                           .build();
        }
        // In a real application, you would save this to a database
        users.add(user);
        // Build a response with a 201 Created status
        // The 'Location' header points to the URL of the newly created resource
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        builder.path(Integer.toString(users.size())); // A simple way to create a unique ID for the example
        return Response.created(builder.build())
                       .entity(user) // Return the created user in the response body
                       .build();
    }
    /**
     * A helper GET method to see the users we've created.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getUsers() {
        return users;
    }
}

Step 4: Create the Application Class and Runner

This class tells Jersey how to configure and run your web service.

Main.java

package com.example;
import com.example.resource.UserResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import java.net.URI;
public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/myapp/";
    public static void main(String[] args) {
        // Create a resource config that scans for JAX-RS resources and providers
        ResourceConfig config = new ResourceConfig(UserResource.class);
        // Create and start a new instance of grizzly http server
        System.out.println("Starting server... " + BASE_URI);
        GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), config);
    }
}

Step 5: Run and Test

  1. Run the Application: Execute the main method in Main.java.
  2. Test with curl: Open a new terminal and use curl to send a POST request.
# Send a POST request with a JSON payload
curl -X POST \
  http://localhost:8080/myapp/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30
  }'

Expected Output: You should see a 201 Created response, and the body will contain the JSON representation of the user you just created.

Java webservice post如何正确调用与传参?-图3

{"name":"Alice","email":"alice@example.com","age":30}

To verify, you can also make a GET request:

curl http://localhost:8080/myapp/api/users

This will return a JSON array with all the users you've created.


Part 2: Classic JAX-WS (SOAP) POST

JAX-WS is used for building SOAP-based web services, which are more complex and rigid than REST services. It's less common for new projects but still exists in many enterprise systems.

Step 1: Create the Service Endpoint Interface (SEI)

This interface defines the contract for your web service, including the POST-like operation.

UserService.java

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
// This annotation specifies the SOAP style (Document/Literal is standard

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