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

如何在Servlet中从JSON获取数据?附前端AJAX提交示例代码

How to Retrieve Data from JSON/Form Requests in a Servlet

Hey there! Let's walk through how to grab the data your AJAX request is sending to AddServlet. There are two common scenarios depending on how your frontend formats the request—let's cover both:

1. If you're sending form-encoded data (your current setup)

Right now, your jQuery AJAX request uses the default behavior: when you pass a plain object to the data parameter, jQuery automatically formats it as application/x-www-form-urlencoded (standard form data), not raw JSON.

To get these values in your Servlet, use the HttpServletRequest.getParameter() method directly. Just match the parameter names to the keys you send from the frontend:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Fetch each field by its name (match the keys in your AJAX data object)
    String systemName = request.getParameter("SystemName");
    String ip = request.getParameter("IP");
    String systemLevel = request.getParameter("SystemLevel");
    String ownera = request.getParameter("Ownera");
    String ownerb = request.getParameter("Ownerb");
    String systemDesc = request.getParameter("SystemDesc");
    String systemDate = request.getParameter("SystemDate");
    String recorder = request.getParameter("Recorder");

    // Now you can process these values as needed!
}

Note: Make sure your AJAX data object uses correct key names (e.g., SystemName: str instead of str: str) so the parameter names match. Your current code snippet cuts off, but that's the key fix if you haven't sorted it yet.

2. If you want to send raw JSON data

If you prefer sending data as a JSON string (better for complex data structures), adjust your frontend code first, then parse the JSON in the Servlet.

Step 1: Update the frontend AJAX request

Modify your JavaScript to stringify the form data and set the correct content type:

function getvalue1(){
    // Collect all form values into a single object
    const formData = {
        SystemName: document.getElementById("SystemName").value,
        IP: document.getElementById("IP").value,
        SystemLevel: document.getElementById("SystemLevel").value,
        Ownera: document.getElementById("Ownera").value,
        Ownerb: document.getElementById("Ownerb").value,
        SystemDesc: document.getElementById("SystemDesc").value,
        SystemDate: document.getElementById("SystemDate").value,
        Recorder: document.getElementById("Recorder").value
    };

    $.ajax({
        type: "post",
        url: "../AddServlet",
        contentType: "application/json", // Tell the server we're sending JSON
        data: JSON.stringify(formData), // Convert object to JSON string
        success: function(response) {
            // Handle successful response here
        }
    });
}

Step 2: Parse JSON in the Servlet

Java doesn't have built-in JSON parsing, so we'll use the popular Jackson library (Gson works too if you prefer).

First, add Jackson dependencies to your project (if using Maven):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

Next, create a POJO (Plain Old Java Object) to map the JSON data to:

public class SystemForm {
    // Fields match the keys in your JSON object
    private String SystemName;
    private String IP;
    private String SystemLevel;
    private String Ownera;
    private String Ownerb;
    private String SystemDesc;
    private String SystemDate;
    private String Recorder;

    // Generate getter and setter methods for all fields
    public String getSystemName() { return SystemName; }
    public void setSystemName(String systemName) { SystemName = systemName; }

    public String getIP() { return IP; }
    public void setIP(String IP) { this.IP = IP; }

    // Repeat getters/setters for the remaining fields...
}

Finally, use Jackson to parse the request body in your Servlet:

import com.fasterxml.jackson.databind.ObjectMapper;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Initialize Jackson's ObjectMapper
    ObjectMapper objectMapper = new ObjectMapper();
    
    // Parse the JSON request body into your SystemForm object
    SystemForm formData = objectMapper.readValue(request.getInputStream(), SystemForm.class);

    // Access the data via the POJO's getters
    String systemName = formData.getSystemName();
    String ip = formData.getIP();
    // ... and so on for other fields
}

内容的提问来源于stack exchange,提问作者Michael Hu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:51:20