2014-05-03 117 views
0

我有一个URL重定向的问题。我的Spring-MVC控制器应该更改URL - 至少我猜是这样。这马 让我们考虑这样的控制器:Spring MVC url重定向

@Controller 
@RequestMapping("/user") 
public class UserController { 

    @RequestMapping(value="/showLoginForm", method = RequestMethod.GET) 
    public String printWelcome(ModelMap model) { 
     return "loginView"; 
    } 

    @RequestMapping(value="/verifyLogin", method = RequestMethod.POST) 
    public String verifyLogin(@RequestParam String login, @RequestParam String password, ModelMap model) { 
     //some stuff here 
     return "redirect:/user/showLoginResult"; 
    } 

    @RequestMapping(value="/showLoginResult", method = RequestMethod.GET) 
    public String showLoginResultView(){ 
     return "loginResult"; 
    } 
} 

最初用户输入的网址:../user/showLoginForm并填充表单,点击提交按钮请求数据是由AJAX发送:

$.ajax({ 
    url: './verifyLogin', 
    method: 'POST', 
    data:{ 
      "login": login, 
      "password": password 
    }, 

    error: function(){ 
     //some stuff to do 
    }, 
    success: function(data){ 
     //some stuff to do 
     $("body").html(data) //fetching data from request to browser, is this correct? 
    } 
}); 

发送请求触发器将调用verifyLogin方法,该方法应该将URL重定向到:user/showLoginResult,但它肯定不会。但是,然后调用showLoginResultView方法,并将loginResult视图返回给ajax回调。

要明确:
1.我用Spring 4.0.4.RELEASE
2.我已经注册org.springframework.web.servlet.view.UrlBasedViewResolver实例。

现在的问题:为什么URL不会改变?

在此先感谢

回答

2

但肯定没有。但随后showLoginResultView方法被调用

这意味着,但它确实做的重定向和浏览器遵循重定向,而原来的AJAX请求的最终响应是给你的AJAX处理程序的成功回调。没有理由地址栏中的URL发生更改,因为您不是发送常规HTTP请求,而是发送AJAX请求。

另请参阅:Returning redirect as response to XHR request

+0

我认为这些请求是相同的HTTP请求。但我发送的请求不是直接从浏览器(通过URL)发送,而是通过AJAX发送,这就是为什么浏览器不遵循URL更改,对吧?进一步的回应是AJAX成功回调(而不是浏览器),我应该手动处理内容更改或URL更改,对吧? – Garet

+0

我不会这么说,但你基本上是对的。 –

+0

geez,谢谢:) – Garet