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

如何无需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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:36:28