如何无需POJO/JSP将HTML表单数据发送至Spring Boot的@PostMapping控制器
无POJO/JSP实现HTML表单值传递到Spring Boot @PostMapping
原代码存在的问题
- input标签缺少
name属性,Spring无法识别要接收的参数 - JS里用
window.location.href发起的是GET请求,无法匹配@PostMapping接口 - 控制器方法未定义参数接收前端传递的值
修改后的完整实现
1. HTML代码
给input添加name属性(Spring靠这个识别参数),保持原有结构:
<body> <form method="post" id="form"> <!-- 新增name属性,值与后端参数名对应 --> <input type="text" name="inputVal" id="inputField"/> </form> <button type="button" id="button2">Submit2</button> <script src="script2.js"></script> </body>
2. Script2.js代码
用fetch API发起POST请求传递参数,避免跳转式的GET请求:
const inputEle = document.getElementById('inputField'); const submitBtn = document.getElementById('button2'); submitBtn.onclick = function() { const inputValue = inputEle.value.trim(); if (!inputValue) { alert('请输入内容'); return; } // 发起POST请求,采用表单编码格式 fetch('/posting', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // 编码参数避免特殊字符乱码 body: `inputVal=${encodeURIComponent(inputValue)}` }) .then(response => response.text()) .then(data => { console.log('后端返回:', data); alert(data); }) .catch(error => { console.error('请求出错:', error); }); };
3. MyController.java代码
用@RequestParam直接接收单个参数,无需创建POJO:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping(value = "/posting") // 参数名与input的name属性值保持一致 public String po(@RequestParam("inputVal") String inputVal) { System.out.println("收到前端值: " + inputVal); return "hello, 你输入的是: " + inputVal; } }
补充说明
- 若不想用fetch,也可以用传统的
XMLHttpRequest,逻辑完全一致 encodeURIComponent用于处理中文、空格等特殊字符,避免参数传递乱码- 控制器用
@RestController可直接返回字符串,若用@Controller则需在方法上添加@ResponseBody
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

