'Alerts or popup message boxes in Spring MVC

I am having a user add form userAdd.jsp. When I enter data and submit, I want to check whether the username field entered is unique compared with the databse. After checking and confirming only I insert the data to the database. I have done up to that point in Spring mvc successfully.
Now I want to give popup alerts or dialog boxes for the two instances in Spring MVC. - the username is already in the database - user is added successfully to the database

Following are my jsp view, controller method and the repository method

  1. userAdd.jsp snipplet

                      <div class="col-xs-4">
                      <form:input path="username" class="form-control" name="username_admin" id="username_admin" placeholder="User Name" type="text" required="required"/>
                    </div>
                    <div class="col-xs-4">
                      <form:input path="password" class="form-control" id="password1" placeholder="Password" type="text" required="required" onchange="validatePassword(password1)"/>
                    </div>
                    <div class="col-xs-4">
                      <form:input path="password" class="form-control" id="cpassword" placeholder="Password Confirm" type="text" required="required" onchange="passwordsEqual(cpassword,password1)"/>
                    </div>
    
  2. Controller method

        //to show the userAdd.jsp page
         @RequestMapping(value="/add",method=RequestMethod.GET)
         public ModelAndView showCustomer(){
         return new ModelAndView("userAdd", "command",new User());
         }
    
    
        //to handle the form data submission and check username 
       @RequestMapping(value="/addCustomer",method = RequestMethod.POST)
       public String saveOrUpdate(@ModelAttribute("newUser")  User newUser,
                               final RedirectAttributes redirectAttributes) throws SQLIntegrityConstraintViolationException {
    
        boolean usernameUnique=staffRepository.checkUsernameUnique(newUser);
        if(usernameUnique) {
            int i = staffRepository.add(newUser);
            if (i == 0)
                //alert saying server error in inserting data to mysql
            else {
    
                //alert or dialog box confirming successful user add
            }
        }else{
            //alert saying username exists in database
        }
        return "redirect:list";
    }
    
  3. Repository methods to insert user data to database and check username

      /*add a new staff member*/
       @Override
        public int add(User user) throws DuplicateKeyException {
    
        int row = 0;
    
        String un = user.getUsername();
        String pw = user.getPassword();
        String des = user.getDesignation();
        if (un != "" && pw != "" ) {
        {
    
    
                String sql = "INSERT INTO staff " +
                        "(title,username,password,first_name,last_name,email,mobile,address_line1,address_line2,address_line3," +
                        "designation,department,branch,register_date,status) VALUES (?,?,sha1(?),?,?,?,?,?,?,?,?,?,?,CURRENT_DATE,1)";
    
                row = jdbcTemplate.update(sql, new Object[]{user.getTitle(), user.getUsername(), user.getPassword(), user.getFirstName(), user.getLastName(),
                        user.getEmail(), user.getMobile(), user.getAddressL1(), user.getAddressL2(), user.getAddressL3(), user.getDesignation(),
                        user.getDepartment(), user.getBranch()});
                updateGroupStaff(des, un);
    
    
                log.info(row + " staff inserted");
                log.info(un);
            /*}else
                log.info("username already available");*/
        } else
            log.error("values cannot be empty");
    
        return row;
    
    }
    
    
    
       //check username availability
        @Override
        public boolean checkUsernameUnique(User user) {
    
        boolean result = true;
    
        String sql = "SELECT count(*) FROM staff WHERE  username = ? ";
    
        int count = jdbcTemplate.queryForObject(
                sql, new Object[]{user.getUsername()}, Integer.class);
    
        if (count > 0) {
            result = false;
            log.info("username already available");
        }
        log.info(result);
        return result;
    }
    

sql queries works very fine and I need a way to get popup alerts in Spring mvc. Thanks in advance :)



Solution 1:[1]

To open an alert box (in an classic web application) you need to send the form page (with the filled in fields) and the java script code for the error box back to the client, in response of the post request.

Typical one would not open an error box for form validation failures, instead one would mark the field with a red border, or something else, and write a hint about the problem next to it.

@RequestMapping(value="/addCustomer",method = RequestMethod.POST)
public ModelAndView saveOrUpdate(@ModelAttribute("newUser")  User newUser, BindingResult validationResult) throws SQLIntegrityConstraintViolationException {

   if (validationResult.hasErrors()) {
        new ModelAndView("userAdd", "command", newUser);
    }

    boolean usernameUnique=staffRepository.checkUsernameUnique(newUser);
    if(usernameUnique) {
        int i = staffRepository.add(newUser);
        if (i == 0)
            return new ModelAndView(new RedirectView("stangeFailurePage"));
        else {
            return new ModelAndView(new RedirectView("successPage"));
        }
    }else{
        validationResult.rejectValue("username", "error.username.exists", "The username is already in use.");
        new ModelAndView("userAdd", "command", newUser);
    }
    return new ModelAndView(new RedirectView("list"));
}

for Validation you need to add the errors-tag to each input field

 <form:input path="username" .../>
 <form:errors path="username" cssClass="error" />

Solution 2:[2]

In my question since I wanted to have an alert being in the same page without any redirection, I wrote another controller method as follows and a javascript code.. In this controller method a null User object is returned , so that "usernameUnique" variable is always true and gives the same alert message every time. (Consider there is a separate controller method to insert filled data to the database)

 @RequestMapping(value="/uniqueUsername",method=RequestMethod.POST)
 public @ResponseBody int checkUser(@ModelAttribute("newUser")  User newUser ){
 boolean usernameUnique ;
 int returnMsg;

 usernameUnique=staffRepository.checkUsernameUnique(newUser);
 if(!usernameUnique){
        returnMsg= 1;
 }else
        returnType=0;

 return returnType;

}

js code for that is as below. this is written for #username_admin textbox change function

$(document).ready(function(){
    $("#username_admin").change(function(){
        var uname = $(this).val();
        $.ajax({
            type: "POST",
            url: "https://localhost:8443/admin/users/uniqueUsername",
            data: {"uname": uname},
            success: function(msg){

                  if(msg == 0)
                    alert("OK");
                  else
                    alert("User name exists !... try another");*//*

                alert(msg + uname);


            },
            error:function(){
                alert("ajax failed" +uname);
            }
        });

    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ralph
Solution 2 difna