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

点击按钮存数据并留当前页:Controller未调用问题求助

问题排查与修复建议

1. AJAX请求方法未正确设置

JS代码中let post;仅声明变量未赋值,导致type: post传递的是undefined,浏览器会默认使用GET请求,但你的Controller仅接受POST请求,这是Controller未被调用的核心原因之一。

修复JS代码:

$('#submit-form').on('click', function() {
    var form = $('#tweet-form');
    $.ajax({
        url: form.attr('action'),
        type: 'POST', // 明确指定POST请求方法
        success: function(result) {
            console.log("数据保存成功");
        }, error: function(xhr, status, error) {
            console.error("请求失败原因:", error);
            console.error("服务器响应:", xhr.responseText);
        }
    })
})

注:你的Controller仅需要路径参数,无需表单数据,可直接移除data: form.serialize(),避免空数据传递的潜在问题。

2. Thymeleaf路径拼接语法错误

HTML中th:action的字符串拼接写法不符合Thymeleaf规范,会生成无效URL(例如/api/userProfile/savedAdventureHolidays{/post/}123),导致请求无法匹配到正确的Controller地址。

修复HTML表单的action属性:

<form id="tweet-form" th:action="@{/api/userProfile/savedAdventureHolidays/post/{adventureId}(adventureId=${randomSummerCamp.id})}"
      th:method="post">
    <input id="submit-form" class="form-control" type="button" value="Submit" />
</form>

Thymeleaf的@{}语法支持直接在括号内传递路径变量,能正确生成/api/userProfile/savedAdventureHolidays/post/xxx格式的有效URL。

3. Controller映射路径前缀缺失

你的Controller的@PostMapping("/savedAdventureHolidays/post/{adventureHolidayId}")未包含/api/userProfile前缀,但HTML表单的action以该前缀开头,导致请求无法匹配到Controller。

修复Controller的映射路径:

@PostMapping("/api/userProfile/savedAdventureHolidays/post/{adventureHolidayId}")
public UserProfile saveAdventureHolidayElement(@PathVariable(value = "adventureHolidayId") String adventureHolidayId) {
    // 原有业务逻辑保持不变
}

若你的Controller类上已添加@RequestMapping("/api/userProfile")注解,则可保留原@PostMapping路径,无需额外添加前缀。

4. 额外排查与优化建议

  • 在Controller方法开头添加日志:logger.info("进入saveAdventureHolidayElement方法,adventureHolidayId: {}", adventureHolidayId);,用于确认请求是否到达Controller。
  • 检查Spring Security配置,确保/api/userProfile/savedAdventureHolidays/post/**路径允许POST请求;若启用了CSRF防护,需在AJAX请求中携带CSRF令牌(Thymeleaf可通过th:csrf自动为表单添加该参数)。

内容的提问来源于stack exchange,提问作者Stefan Jankovic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:25:21