Spring MVC:在@ResponseBody中重定向
问题内容:
我想在springmvc方法中重定向到另一个.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 "";
}
问题答案:
当您的请求需要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重定向到另一个页面