Search code examples
javaajaxspring-mvcjspmodelattribute

How to use SpringMVC Form tags along with AJAX


Suppose I have a Login Object, when I make a get request for 'login', I send the Login object and in the JSP Page I use model attribute and paths to map the attributes as follows:

ViewController:

    @GetMapping("/login")
    public String login(Model model){
       Login login = new Login();
       model.addAttribute("login",login);
       return "login";
    }

JSP Page:

 ...

<form:form action="login" method="post" modelAttribute="login">
        <form:hidden path="id"/>
        <label for="username">UserName</label>
        <form:input path="username"/><br>
        <label for="password">Password</label>
        <form:password path="password"/><br>
        <form:button>Login</form:button>
</form:form>
...

Now when I hit on the Login Button, the login object is sent to the appropriate controller and it returns a ResponseEntity Object accordingly with some message.Once the processing is done, the page refreshes and the message in the ResponseEntity object is displayed, say "Login Successful".

But I want to display this message in the form of an alert. To do that I'll have to make an AJAX request and upon success call the alert with the message, but in this approach I can no longer use the modelAttribute and AJAX has so sent a Login object, would that be possible?

Is there any way to use the functionality of the modelAttribute and also making AJAX requests?


Solution

  • After digging up for details about the same, I finally got the solution!

    I had to make the following changes.

    Login.jsp - Add a new button tag outside the tag

      ...
        <form:form id="myform" action="login" method="post" modelAttribute="login">
            <form:hidden path="id"/>
            <label for="username">UserName</label>
            <form:input path="username"/><br>
            <label for="password">Password</label>
            <form:password path="password"/><br>
        </form:form>
        <button id="login-btn">Login</button>
      ...
    

    AJAX Script:

           $(document).ready(function () {
               $("#login-btn").click(function () {
                   $.ajax({
                       type: "POST",
                       url: "login",
                       data : $("#myform").serialize(),
                       success: function (data) {
                           alert(data);
                       },
                       error: function(data){
                           alert(data);
                      }
                   });
               }) 
            });
    
    
    

    Controller:(to check if the login was valid or not)

    @PostMapping("/login")
        public ResponseEntity<?> login(@ModelAttribute("login") Login login){
            boolean status = loginDao.isValidLogin(login);
            String message = (status)?"Login Succcessful":"Incorrect Login Credentials!";
            return new ResponseEntity<>(message,HttpStatus.OK);
        }