2012-12-27 14 views
0

我正在使用Spring MVC,並且需要對服務器進行異步調用並檢查用戶的憑據。如果匹配,那麼我將重定向到另一頁。如何在Spring MVC中使用AJAX在視圖中傳遞和獲取模型屬性

MyController.java

@RequestMapping("performingLogin.htm") 
public ModelAndView performingLogin(@RequestParam String username, @RequestParam String password) 
{ 
    //boolean value which decides whether its a valid user 
    myService.performingLogin(username, password); 

    //Currently returning the new model to be opened irrespective of valid user 
    ModelAndView model = new ModelAndView("newpage"); 
    return model; 
} 

MainView.jsp

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
<script type="text/javascript"> 
function doAjaxPost() { 

    $.ajax({ 
     url : "dologin.htm", 
     data : { 
     username: $('#username').val(), 
     password: $('#password').val() 
     }, 
     success : function(responseTxt,statusTxt,xhr) { 
     /* Opening new page */ 
     window.location.href="newpage.htm"; 
     } 
    }); 
} 

我需要知道我將如何驗證用戶在JSP結束,這樣我可以給一個警報,提醒憑據不正確。

回答

2

@ResponseBody檢查註釋

public @ResponseBody String performingLogin(@RequestParam String username, @RequestParam String password) 
{ 
} 
1

在你的代碼會完全無視返回的視圖中,做一個js重定向成功。只要你這樣做,返回ModelAndView@ResponseBody註釋值之間沒有真正的區別。

您可能想要返回401 Unauthorized http錯誤,然後在javascript中檢查該錯誤。

有很多種方法可以做到這一點。

一個是創建一個異常並用spring註釋標註它,然後拋出它。

東西沿着線:

@ResponseStatus(value = HttpStatus.UNAUTHORIZED) 
public class AuthenticationException extends RuntimeException { 
    private static final long serialVersionUID = 23949237498237948234l; 
} 

改變你的請求映射到:

@RequestMapping("performingLogin.htm") 
public ModelAndView performingLogin(@RequestParam String username, @RequestParam String password) 
{ 
    //boolean value which decides whether its a valid user 
    myService.performingLogin(username, password); 

    if (authenticationWentWrong) { 
     throw new AuthenticationException(); 

    } 

    //Currently returning the new model to be opened irrespective of valid user 
    ModelAndView model = new ModelAndView("newpage"); 
    return model; 
} 

,然後你的js代碼:

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
<script type="text/javascript"> 
function doAjaxPost() { 

    $.ajax({ 
     url : "dologin.htm", 
     data : { 
     username: $('#username').val(), 
     password: $('#password').val() 
     }, 
     success : function(responseTxt,statusTxt,xhr) { 
     /* Opening new page */ 
     window.location.href="newpage.htm"; 
     }, 
     statusCode : { 
      401: function(jqXHR, textStatus, errorThrown) { 
       //handle the authentication error here 
      } 
     } 

    }); 
} 
相關問題