杰瑞科技汇

Ajax如何调用Java WebService?

Of course! Let's break down how to create a web service in Java that can be consumed by AJAX (Asynchronous JavaScript and XML) calls. This is a fundamental pattern for building modern web applications.

Ajax如何调用Java WebService?-图1
(图片来源网络,侵删)

We'll cover two popular approaches for creating the Java web service:

  1. JAX-RS (Java API for RESTful Web Services): This is the modern, standard way to create RESTful APIs in Java. It's annotation-based and very easy to use. We'll use the Jersey implementation, which is the reference implementation for JAX-RS.
  2. Spring Boot with @RestController: This is the dominant framework in the Java world. It simplifies creating web services dramatically. We'll show how to do it with Spring Boot, as it's the most common scenario today.

Core Concept: The Flow

Here's a simple diagram of how AJAX and a Java web service interact:

+----------------+      1. HTTP Request (JSON/XML)      +---------------------+
|                | -----------------------------------> |                     |
|   Browser      |                                    |   Java Web Service  |
| (JavaScript)   | <----------------------------------- |    (e.g., JAX-RS,    |
|                |      2. HTTP Response (JSON/XML)     |     Spring Boot)    |
+----------------+                                    +---------------------+
      ^                                                      |
      |                                                      |
      +------------------------------------------------------+
               3. Browser updates the page (DOM)

Key Points:

  • AJAX (Client-Side): The JavaScript code in your browser sends an HTTP request (e.g., GET, POST) to a specific URL on your server. It doesn't reload the whole page.
  • Java Web Service (Server-Side): A Java application running on a server (like Tomcat) listens for requests at that URL. It processes the request (e.g., queries a database, performs logic) and sends back a response, usually in JSON format.
  • JSON (Data Format): While the "X" in AJAX stands for XML, JSON is overwhelmingly the most popular format today due to its simplicity and how well it maps to JavaScript objects. Our Java services will produce and consume JSON.

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

This approach is great if you're working in a standard Java EE environment or want to learn the JAX-RS standard.

Ajax如何调用Java WebService?-图2
(图片来源网络,侵删)

Step 1: Set up a Maven Project

You'll need the Jersey server dependency in your pom.xml.

<dependencies>
    <!-- Jersey Server -->
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>3.1.3</version> <!-- Use a recent version -->
    </dependency>
    <!-- For JSON support -->
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>3.1.3</version>
    </dependency>
</dependencies>

Step 2: Create the Resource (Web Service Endpoint)

This is a simple Java class with annotations that defines your API.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.List;
// The @Path annotation defines the base URL for this resource.
@Path("/api/users")
public class UserResource {
    // A simple in-memory "database"
    private static final List<User> users = new ArrayList<>();
    static {
        users.add(new User(1, "Alice"));
        users.add(new User(2, "Bob"));
    }
    // The @GET annotation handles HTTP GET requests.
    // @Path can be used to add more segments to the URL.
    // @Produces specifies the media type the method will return.
    @GET
    @Path("/{userId}")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUserById(@PathParam("userId") int id) {
        System.out.println("Received request for user with ID: " + id);
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        // Return null or throw a WebApplicationException for 404 Not Found
        return null;
    }
    // An endpoint to get all users
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getAllUsers() {
        return users;
    }
}
// A simple POJO (Plain Old Java Object) to represent a User.
// Jackson (the JSON library) will automatically convert this to/from JSON.
class User {
    private int id;
    private String name;
    public User() {} // Default constructor for Jackson
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
    // Getters and Setters are required for Jackson
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

Step 3: Configure and Run the Application

You need to tell your servlet container (like Tomcat or embedded Jetty) where to find your JAX-RS resources. You can do this with a web.xml file or programmatically.

Using web.xml (for a traditional WAR deployment):

Ajax如何调用Java WebService?-图3
(图片来源网络,侵删)
<!-- web.xml -->
<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">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.yourpackage.resources</param-value> <!-- Package containing your resources -->
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/api/*</url-pattern> <!-- Map all /api/* requests to Jersey -->
    </servlet-mapping>
</web-app>

Step 4: Create the AJAX Client (HTML/JavaScript)

Create an index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">AJAX and Java Web Service</title>
</head>
<body>
    <h1>Users from Java Web Service</h1>
    <button id="getUsersBtn">Get All Users</button>
    <button id="getUser1Btn">Get User with ID 1</button>
    <div id="output"></div>
    <script>
        document.getElementById('getUsersBtn').addEventListener('click', getAllUsers);
        document.getElementById('getUser1Btn').addEventListener('click', getUserById);
        function getAllUsers() {
            fetch('/api/users') // Assuming your app is running at the root context
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json(); // Parse the JSON from the response
                })
                .then(data => {
                    console.log('All Users:', data);
                    displayOutput(data);
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                    displayOutput('Error: ' + error.message);
                });
        }
        function getUserById() {
            fetch('/api/users/1') // Fetch user with ID 1
                .then(response => response.json())
                .then(data => {
                    console.log('User 1:', data);
                    displayOutput([data]); // Display in the same format as getAllUsers
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                    displayOutput('Error: ' + error.message);
                });
        }
        function displayOutput(data) {
            const outputDiv = document.getElementById('output');
            outputDiv.innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
        }
    </script>
</body>
</html>

Approach 2: Spring Boot (The Modern, Popular Way)

Spring Boot drastically simplifies setup with auto-configuration and an embedded server.

Step 1: Create a Spring Boot Project

Use the Spring Initializr (start.spring.io) with the following dependencies:

  • Spring Web: For building web applications, including RESTful services.
  • Spring Boot DevTools: For automatic restarts during development.

Step 2: Create the Controller

In Spring, you use a @RestController to create a RESTful web service.

import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
分享:
扫描分享到社交APP
上一篇
下一篇