Spring MVC:在@ResponseBody 中重定向

Kar*_*cki 5 spring spring-mvc

我想在 spring mvc 方法中重定向到另一个 .jsp。我不想使用 javascripts 方法,例如:window.location.replace(url)。

我的方法:

@RequestMapping(value= "loginUser", method=RequestMethod.POST)
public @ResponseBody String loginUser (@RequestParam("name") String name,   @RequestParam("password") String password){ 

   return "";
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*cky 3

当您的请求需要 json 响应时,您无法从 Spring 进行重定向。您可以设置重定向参数,以便在进入成功块时可以使用 来检查重定向参数window.location.reload();。例如,从类似的帖子中,检查这个答案,

Ajax Jquery 调用重定向

一种想法是让浏览器知道它应该通过向结果对象添加重定向变量并在 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); 
         } 

    }); 
});
Run Code Online (Sandbox Code Playgroud)

您也可以添加一个用于重定向的响应标头,如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...
        }
    }
Run Code Online (Sandbox Code Playgroud)

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