您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring MVC:在@ResponseBody中重定向

Spring MVC:在@ResponseBody中重定向

当您的请求需要json响应时,您将无法从Spring进行重定向。您可以设置用于重定向的参数,以便在输入成功块时可以使用来检查要重定向的参数window.location.reload();

一种想法是通过将重定向变量添加到结果对象并在JQuery中进行检查,从而使浏览器知道它应该重定向

$(document).ready(function(){
    jQuery.ajax({
        type: "GET",
        url: "populateData.htm",
        dataType:"json",
        data:"userId=SampleUser",
        success:function(response){
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        },
     error: function(xhr, textStatus, errorThrown) {
            alert('Error!  Status = ' + xhr.status);
         }

    });
});

您也可以添加一个响应标头以进行重定向,例如response.setHeader("REQUIRES_AUTH", "1"),在jQuery成功中,

success:function(response){
        if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
            window.location.href = 'login.htm';
        }
        else {
            // Process the expected results...
        }
    }

引用类似的问题:Spring Controller重定向到另一个页面

Java 2022/1/1 18:24:26 有585人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶