Spring Boot项目中Ajax传参至Controller存值为Null问题求助
Let's break down the issues causing your null value problem step by step—there are a few clear mismatches between your Ajax request, Controller setup, and Entity definition that are preventing proper parameter transmission.
1. Request Method Mismatch
Your Controller's addNewStatus method uses @GetMapping(path="/insert"), but your Ajax code explicitly uses type: "POST". Spring won't route a POST request to a GET-mapped endpoint, which means your Controller never receives the parameters at all.
Fix:
Switch the Controller annotation to match your Ajax request method (POST is better practice for data insertion):
@PostMapping(path="/insert") // Changed from @GetMapping public @ResponseBody String addNewStatus (@RequestParam String xml_to_json) { // ... existing code ... }
Or if you prefer to keep GET (not recommended for writes), update your Ajax type to "GET".
2. Unnecessary Request Param & Missing Entity Field
Your Controller includes a @RequestParam String json_to_xml parameter, but:
- The
Statusentity has no correspondingjson_to_xmlfield - You've commented out the setter for it anyway
This is a problem because @RequestParam is required by default—if your Ajax doesn't send this parameter, your request will fail outright.
Fix:
- If you don't need the
json_to_xmlfield, remove the parameter from your Controller method entirely:public @ResponseBody String addNewStatus (@RequestParam String xml_to_json) { - If you do need it, add the field and accessors to your
Statusentity:@Entity @Table(name="tbl_status") public class Status { // ... existing id and xml_to_json fields ... private String json_to_xml; public String getJson_to_xml() { return json_to_xml; } public void setJson_to_xml(String json_to_xml) { this.json_to_xml = json_to_xml; } }
3. Incomplete Ajax Request Setup
Your Ajax code is cut off, but here's a complete, working example that ensures parameters are correctly passed to your Controller:
var xml2json = function(_data){ $.ajax({ type: "POST", url: "/insert", // Ensure this matches your full backend URL (add context path if needed) data: { xml_to_json: _data // Parameter name must exactly match @RequestParam in Controller }, success: function(response) { console.log("Data saved successfully: " + response); }, error: function(xhr, status, error) { console.error("Error saving data: " + error); } }); }
4. Debugging Steps for Future Issues
If you still run into problems:
- Add logging to your Controller to verify parameter receipt:
System.out.println("Received xml_to_json value: " + xml_to_json); - Use your browser's DevTools (F12 → Network tab) to inspect the request: check the URL, request method, and form data/query params being sent
- Verify there are no CORS issues (if frontend and backend run on different ports/domains) by adding CORS configuration to your Spring Boot app
内容的提问来源于stack exchange,提问作者Alice Cho

