2012-12-27 1 views
0

Spring MVC를 사용하고 있으며 서버에 대한 비동기 호출을 수행하고 사용자의 자격 증명을 확인해야합니다. 일치하면 다른 페이지로 리디렉션됩니다.Spring MVC에서 AJAX를 사용하여 View에서 모델 속성을 전달하고 잡는 방법

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 완전히 돌려보기를 무시하고 JS 성공에 리디렉션하고있는 코드에서

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

주석. 당신이 그렇게하는 한, ModelAndView 또는 @ResponseBody 주석 값을 반환하는 것 사이에는 실제적인 차이가 없습니다.

아마도 401 Unauthorized http 오류를 반환하고 자바 스크립트에서 확인하고 싶을 것입니다.

다양한 방법이 있습니다.

하나는 예외를 만들고이를 스프링 주석으로 주석 처리 한 다음 던져 넣는 것입니다. 라인을 따라

뭔가 : 다음

@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 코드 :

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

는 귀하의 요청 매핑을 변경 또한

<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 
      } 
     } 

    }); 
} 
0

, 당신은 HTTPResponseEntity,을 시도 할 수 있습니다 나는 그것이 종종 간과 되기는하지만 당신에게 더 큰 통제력을 줄 것이라고 생각한다 - 새로운 testin에 유용 할 수있다. g 패키지 spring 3.2.

관련 문제