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

如何通过AJAX请求向Spring Boot Controller传值并跳转至新JSP页面

我来帮你理清这个问题并给出可行的解决方案~

问题核心原因

首先得明确:AJAX请求本身不会自动触发页面跳转或打开新视图,它的设计初衷就是在当前页面后台和服务器静默交互。所以哪怕你的Spring Boot Controller执行了业务代码并返回了JSP视图,AJAX只会接收该视图的HTML内容,不会自动帮你渲染成新页面。

接下来给你两种常用的解决思路:

思路1:后端返回跳转URL,前端手动触发跳转

适合需要在当前页面跳转到目标JSP的场景。

后端Controller修改

把原来直接返回视图的逻辑改成返回包含跳转路径的JSON响应:

@PostMapping("/message1")
@ResponseBody
public Map<String, String> handleMessage(@RequestParam String message) {
    // 这里处理你的业务逻辑,比如存储消息、调用服务等
    System.out.println("收到前端消息:" + message);
    
    // 返回要跳转的页面URL(需确保该URL已映射到对应JSP)
    Map<String, String> response = new HashMap<>();
    response.put("redirectUrl", "/resultPage");
    return response;
}

同时需要给目标JSP配置映射Controller:

@GetMapping("/resultPage")
public String showResultPage(Model model, @RequestParam(required = false) String msg) {
    // 给JSP页面传递数据
    model.addAttribute("receivedMsg", msg);
    return "result"; // 对应你的JSP文件路径,比如src/main/webapp/WEB-INF/jsp/result.jsp
}

前端AJAX修改

在AJAX的成功回调里拿到跳转URL,用window.location.href触发页面跳转:

var hello = "Hello World!";
$.ajax({
    type: "POST",
    url: "/message1",
    data: { message: hello },
    dataType: 'json',
    success: function(response) {
        // 跳转到目标页面
        window.location.href = response.redirectUrl;
    },
    error: function(xhr, status, error) {
        console.error("请求出错:", error);
    }
});

思路2:AJAX成功后直接打开新标签页

适合需要在新窗口显示JSP的场景,可通过Session或URL参数传递数据。

后端Controller修改

把需要传递的数据存入Session,方便新页面读取:

@PostMapping("/message1")
@ResponseBody
public Map<String, String> handleMessage(@RequestParam String message, HttpSession session) {
    // 将数据存入Session,供新页面获取
    session.setAttribute("receivedMessage", message);
    
    Map<String, String> response = new HashMap<>();
    response.put("targetPage", "/resultPage");
    return response;
}

前端AJAX修改

在成功回调里用window.open()打开新标签页:

var hello = "Hello World!";
$.ajax({
    type: "POST",
    url: "/message1",
    data: { message: hello },
    dataType: 'json',
    success: function(response) {
        // 打开新标签页加载目标JSP
        window.open(response.targetPage, "_blank");
    },
    error: function(xhr, status, error) {
        console.error("请求出错:", error);
    }
});

额外提醒

如果你之前的Controller是直接返回JSP视图名(比如return "message"),AJAX会收到该JSP的HTML源码,但不会自动渲染成页面。必须通过前端的跳转方法(window.location.href或window.open)来触发页面加载,这是AJAX的特性决定的~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:28:32