You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java(JEE)中读取Ajax传递的JSON数据?

Hey there! Let's sort out how to read that JSON data from your Ajax request in your Java backend. First off, I noticed a tiny typo in your frontend code: jQuery.ajex should be jQuery.ajax—that might save you some headaches later! 😊

Below are two common approaches to handle this, depending on whether you're using a framework like Spring MVC or plain vanilla Servlets:

1. Using Spring MVC (Most Common Modern Approach)

If you're building your backend with Spring MVC (or Spring Boot), this is the cleanest way to map the incoming JSON directly to a Java object.

Step 1: Create a Java Entity Class

First, make a simple class that mirrors the structure of your JSON data:

public class Book {
    private String title;
    private Double price;

    // Getters and Setters (required for Spring to map the JSON)
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Step 2: Build the Controller Endpoint

Use the @RequestBody annotation to automatically parse the JSON request body into your Book object:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/book_service/rest/books") // Matches your frontend URL path
public class BookController {

    @PostMapping("/")
    public String addBook(@RequestBody Book book) {
        // Now you can directly access the values from the Book object
        String incomingTitle = book.getTitle();
        Double incomingPrice = book.getPrice();

        // Add your business logic here (e.g., save to database)
        System.out.println("Received book: " + incomingTitle + " | Price: $" + incomingPrice);

        return "Added Successfully"; // This will be sent back to your frontend's success callback
    }
}

Note: If you're using Spring Boot, Jackson (the JSON parsing library) is included by default. For plain Spring MVC, make sure you have the Jackson dependencies in your pom.xml or build.gradle.

2. Using Plain Java Servlet (No Framework)

If you're not using a framework, you'll need to manually read the request body and parse the JSON yourself.

Step 1: Add a JSON Parsing Library

Use a library like org.json (simple and lightweight) or Jackson to parse the JSON string. For Maven, add this dependency to your pom.xml:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

Step 2: Write the Servlet Code

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/book_service/rest/books/") // Matches your frontend URL
public class BookServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Read the JSON string from the request body
        StringBuilder requestBody = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        String jsonData = requestBody.toString();

        // 2. Parse the JSON string into a JSONObject
        JSONObject jsonObject = new JSONObject(jsonData);
        String title = jsonObject.getString("title");
        double price = jsonObject.getDouble("price");

        // 3. Process the data (e.g., save to database)
        System.out.println("Received book title: " + title + " | Price: $" + price);

        // 4. Send a response back to the frontend
        response.setContentType("application/json");
        response.getWriter().write("{\"message\":\"Added Successfully\"}");
    }
}
Key Notes to Remember
  • Your frontend already sets contentType: "application/json"—don't remove this! This tells the backend that the request body is JSON, which is critical for proper parsing.
  • Make sure your backend endpoint URL exactly matches the url in your Ajax request (http://localhost:8080/book_service/rest/books/).
  • If you prefer using Jackson in the Servlet approach, you can replace the org.json parsing with:
    ObjectMapper objectMapper = new ObjectMapper();
    Book book = objectMapper.readValue(jsonData, Book.class);
    // Then use book.getTitle() and book.getPrice() as before
    

内容的提问来源于stack exchange,提问作者Suhail Moh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:36:53