【问题标题】:How to redirect to another request mapping of a spring MVC controller from a jsp within a jsp如何从jsp中的jsp重定向到spring MVC控制器的另一个请求映射
【发布时间】:2018-06-17 18:00:05
【问题描述】:

情况: 我在一个jsp中有一个jsp。我使用 .html() 将另一个 jsp 加载到外部 jsp 的 div 中。我想将我的 url 重定向到来自控制器的全新 url 映射。

样品控制器:

@RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
            System.out.println("In controller");

            return "redirect:/anotherJSP";
}

@RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
            System.out.println("In another");

            return "anotherJSP";
}

jsp中的jsp:

$.ajax({
    type : "POST",
    url : "/main/submit",
    success : function(msg) {
        console.log('redirect');
    },
    error : function() {
        alert("Error.");
    }
});

现在,问题是外部jsp 保留,而/anotherJSP url 只加载到innerJSP 中。我想离开这两个 jsps 并转到新的请求映射 URL。无论如何我可以做到吗?提前非常感谢!

【问题讨论】:

  • 据我了解,您希望它在有人转到 /main/submit 时导航到 /anotherJSP?您的应用程序是否有必要通过 JS 来完成?
  • 是的,这只是一个例子,这就是为什么它没有发生任何其他逻辑。嗯,我实际上是从内部jsp发送数据到/main/submit/然后当提交成功时,它会重新加载整个jsp。

标签: java spring-mvc jsp redirect


【解决方案1】:

您不能重定向 POST

当您返回 redirect:/anotherJSP 时,服务器会向 Web 浏览器发送一个重定向指令,然后浏览器会针对给定的 URL 发送一个新的 GET 请求。

GET 请求将针对给定的 URL,并带有任何查询参数。这意味着 POST 有效载荷(数据)将丢失。

@RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) 更改为 @GetMapping("/anotherJSP")(假设 Spring 4.3 或更高版本)。

【讨论】:

  • 对不起,我忘了编辑它,requestmethod 设置为 GET 而不是另一个 JSP 的 POST。
【解决方案2】:

由于 ajax 调用是异步的,return "redirect:/anotherJSP"; 的效果不会影响浏览器窗口,相反,您应该在 ajax 调用中使用 window.location.href,如下所示:

$.ajax({
    type : "POST",
    url : "/main/submit",
    success : function(msg) {
        console.log('redirect');
        window.location.href = /anotherJSP;
    },
    error : function() {
        alert("Error.");
    }
});

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2015-10-08
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多