coderslay
coderslay

Reputation: 14370

How to pass and grab model attributes in a View using AJAX in Spring MVC

I'm using Spring MVC and I need to make an asynchronous call to the server and check user's credentials. If it matches then i am redirecting to another page.

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";
      }  
   }); 
}

I need to know how will i validate the user at the JSP end so that i can give a alert that credentials are incorrect.

Upvotes: 0

Views: 4725

Answers (3)

soulcheck
soulcheck

Reputation: 36767

In your code you're completely ignoring the returned view and doing a js redirect on success. As long as you do that, there's no real difference between returning ModelAndView or @ResponseBody annotated value.

You probably want to return 401 Unauthorized http error and then check for that in your javascript.

There are various ways to do it.

One is to create an exception and annotate it with spring annotations, then throw it.

Something along the lines:

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

changing your request mapping to:

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

and then your js code:

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

   });
}

Upvotes: 1

NimChimpsky
NimChimpsky

Reputation: 47290

Also, you may want to try HTTPResponseEntity, I think its often overlooked but gives you greater control - can be useful with the new testing packages of spring 3.2.

Upvotes: 0

nDijax
nDijax

Reputation: 521

Check @ResponseBody annotation

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

Upvotes: 2

Related Questions