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

Spring Boot中PostMapping后如何不跳转仅显示‘成功’提示?

解决Spring Boot PostMapping后不跳转页面仅显示成功提示的方案

要实现点击按钮保存数据后停留在当前页面并弹出成功提示,核心是用异步请求(AJAX)替代传统的表单同步提交,同时修改控制器返回JSON响应而非视图重定向。

步骤1:修改控制器,返回JSON响应

将原来返回重定向视图的逻辑改为返回包含操作状态的JSON数据,让前端直接接收结果而不触发页面跳转:

@PostMapping("/savedAdventureHolidays/post/{adventureHolidayId}")
public ResponseEntity<Map<String, String>> saveAdventureHolidayElement(@PathVariable(value = "adventureHolidayId") String adventureHolidayId) {
    // 获取当前登录用户
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();

    // 查询目标数据,不存在则抛出异常
    AdventureHolidays post = adventureHolidaysRepository.findById(adventureHolidayId)
            .orElseThrow(() -> new ResourceNotFoundException("PostId " + adventureHolidayId + " not found"));

    // 构建并保存UserProfile
    UserProfile comment = new UserProfile();
    comment.setAdventureHolidaysList(Collections.singletonList(post));
    comment.setLoggedUserId(username);
    comment.setSavedHolidayTitle(post.getTitle()); // 复用已查询的post对象,避免重复查库
    userProfileRepository.save(comment);

    // 构造成功响应
    Map<String, String> response = new HashMap<>();
    response.put("status", "success");
    response.put("message", "保存成功");
    return ResponseEntity.ok(response);
}

步骤2:前端修改为异步提交请求

原来的按钮如果是通过表单同步提交,现在需要改成用JavaScript监听点击事件,发送AJAX请求:

HTML部分(以Thymeleaf模板为例)

<!-- 保存按钮,通过data-id传递adventureHolidayId -->
<button id="saveBtn" data-id="${adventureHoliday.id}">保存到我的收藏</button>

<!-- 页面内的成功提示框,默认隐藏 -->
<div id="successTip" style="display: none; padding: 10px; background-color: #d4edda; color: #155724; border-radius: 4px;">
    保存成功!
</div>

JavaScript部分(原生JS实现)

document.addEventListener('DOMContentLoaded', function() {
    const saveBtn = document.getElementById('saveBtn');
    const successTip = document.getElementById('successTip');

    saveBtn.addEventListener('click', function() {
        const holidayId = this.dataset.id;

        // 发送POST请求
        fetch(`/savedAdventureHolidays/post/${holidayId}`, {
            method: 'POST'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('请求失败');
            }
            return response.json();
        })
        .then(data => {
            // 显示成功提示,3秒后自动隐藏
            successTip.style.display = 'block';
            setTimeout(() => {
                successTip.style.display = 'none';
            }, 3000);
            // 也可以用alert弹窗:alert(data.message);
        })
        .catch(error => {
            console.error(error);
            alert('保存失败,请稍后重试');
        });
    });
});

额外注意事项

  • 若项目使用Spring Security,确保AJAX请求不会被CSRF拦截,需要在请求中携带CSRF令牌(可通过页面隐藏域获取,比如Thymeleaf的th:csrf-token)。
  • 可以用Bootstrap等UI框架的alert组件替代自定义提示框,提升视觉体验。
  • 建议全局处理控制器异常,返回统一格式的错误JSON,让前端能更友好地处理失败场景。

内容的提问来源于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.15 18:15:48