utiliser Spring MVC et ajax pour gérer une liste d’objects

avec AJAX et Spring MVC, Comment renvoyer la liste des objects de Spring Controller et avec Jquery

demande Ajax ci-dessous:

$.ajax({ type: "POST", url: "allUser.html", dataType:'json', data: "select=" + selectedCheckboxArray, success: function(data){ var userListContent=""; var json =data.message; $.each(json, function(i, obj) { userListContent=userListContent+""; userListContent=userListContent+" "; userListContent=userListContent+""+obj.firstName+" "+obj.lastName +""; userListContent=userListContent+""+ obj.gender +""; userListContent=userListContent+""+ obj.userName +" "; userListContent=userListContent+" "+ obj.userType +""; userListContent=userListContent+""+ obj.status +""; userListContent=userListContent+""+ obj.emailId +""; userListContent=userListContent+""+ obj.address +""; userListContent=userListContent+""+ obj.contactNo +""; userListContent=userListContent+""; }); $('#rounded-corner tbody').html(userListContent); //console.log(userListContent); }, error: function(e){ alert('Error: ' + e.responseText); } }); 

MVC Contrller

  @RequestMapping(value="/deleteUser",method= RequestMethod.POST) public @ResponseBody Map deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException { System.out.println("Ajax Request Received for delete User..............."); Map model = new HashMap(); JsonResponse js=new JsonResponse(); js.setResult("pass"); js.setStatus("active"); // Ssortingng operation=request.getParameter("operation"); Ssortingng[] selectedUserIdParameter = request.getParameterValues("select"); System.out.println("Length:"+selectedUserIdParameter.length); /* Code Description: * Array "selectedUserIdParameter" above has ID like {1,2,3,.....}, * we need to use array like {1 2 3 4 } without (,).so first we must convert. * Following code doing the same. * After Conversion Array "selectedUserId" will have ID like {1 2 3 4 } * If You Know PHP explode()" function ,following is doing something like what explode() function does . */ Ssortingng msg="hello"; List usersList = userService.getAllUser(); int no=usersList.size(); System.out.println("Size:"+no); model.put("message", usersList); model.put("jso", js); return model; } 

    Vous allez accepter et renvoyer des objects sous la forme de JSON, ajoutez donc le bean jackson mapper dans spring dispatcher servlet xml. Jackson mapper fait tout. Vous n’avez pas besoin de faire la cartographie ou la conversion manuellement.

               

    Maintenant, votre contrôleur serait comme ça:

     @RequestMapping(value = "/deleteUser", method = RequestMethod.POST) public @ResponseBody List deleteUser(@RequestBody UserDetails userDetails) { // fetch the userid to be deleted from the userDetails // remebmer the id of user to be deleted will be set in the ajax call userService.deleteUser(userDetails.getUserId()); // again populate the user list to display on page List userList = userService.getAllUser(); return userList; } 

    Maintenant, votre appel ajax ressemblera à ceci:

     function deleteUser() { // set variables into javascript object which you need to send to spring controller // the variable name here should be same as it is in your java class UserDetails.java var user = new Object(); user.userId = 120; // id of user to be deleted $.ajax({ type : 'POST', url : '/${your project context path here}/deleteUser', dataType : 'json', data : JSON.ssortingngify(user), contentType : 'application/json', success : function(data) { //here in data variable, you will get list of all users sent from // spring controller in json format, currently its object // iterate it and show users on page showUsers(data); }, error : function() { alert('error'); } }); } function showUsers(data) { // and here you show users on page //following code just example $('#allUsers').append(""); for ( var i = 0, len = data.length; i < len; ++i) { var user = data[i]; $('#allUsers').append(""); } } la function deleteUser() { // set variables into javascript object which you need to send to spring controller // the variable name here should be same as it is in your java class UserDetails.java var user = new Object(); user.userId = 120; // id of user to be deleted $.ajax({ type : 'POST', url : '/${your project context path here}/deleteUser', dataType : 'json', data : JSON.ssortingngify(user), contentType : 'application/json', success : function(data) { //here in data variable, you will get list of all users sent from // spring controller in json format, currently its object // iterate it and show users on page showUsers(data); }, error : function() { alert('error'); } }); } function showUsers(data) { // and here you show users on page //following code just example $('#allUsers').append(""); for ( var i = 0, len = data.length; i < len; ++i) { var user = data[i]; $('#allUsers').append(""); } } la function deleteUser() { // set variables into javascript object which you need to send to spring controller // the variable name here should be same as it is in your java class UserDetails.java var user = new Object(); user.userId = 120; // id of user to be deleted $.ajax({ type : 'POST', url : '/${your project context path here}/deleteUser', dataType : 'json', data : JSON.ssortingngify(user), contentType : 'application/json', success : function(data) { //here in data variable, you will get list of all users sent from // spring controller in json format, currently its object // iterate it and show users on page showUsers(data); }, error : function() { alert('error'); } }); } function showUsers(data) { // and here you show users on page //following code just example $('#allUsers').append(""); for ( var i = 0, len = data.length; i < len; ++i) { var user = data[i]; $('#allUsers').append(""); } } les function deleteUser() { // set variables into javascript object which you need to send to spring controller // the variable name here should be same as it is in your java class UserDetails.java var user = new Object(); user.userId = 120; // id of user to be deleted $.ajax({ type : 'POST', url : '/${your project context path here}/deleteUser', dataType : 'json', data : JSON.ssortingngify(user), contentType : 'application/json', success : function(data) { //here in data variable, you will get list of all users sent from // spring controller in json format, currently its object // iterate it and show users on page showUsers(data); }, error : function() { alert('error'); } }); } function showUsers(data) { // and here you show users on page //following code just example $('#allUsers').append(""); for ( var i = 0, len = data.length; i < len; ++i) { var user = data[i]; $('#allUsers').append(""); } } 

    Cela fonctionnera.

    Renvoyer la liste de tableaux directement devrait fonctionner …

     @RequestMapping(value="/deleteUser",method= RequestMethod.POST) public @ResponseBody ArrayList deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException { System.out.println("Ajax Request Received for delete User..............."); // Ssortingng operation=request.getParameter("operation"); Ssortingng[] selectedUserIdParameter = request.getParameterValues("select"); System.out.println("Length:"+selectedUserIdParameter.length); /* Code Description: * Array "selectedUserIdParameter" above has ID like {1,2,3,.....}, * we need to use array like {1 2 3 4 } without (,).so first we must convert. * Following code doing the same. * After Conversion Array "selectedUserId" will have ID like {1 2 3 4 } * If You Know PHP explode()" function ,following is doing something like what explode() function does . */ Ssortingng msg="hello"; List usersList = userService.getAllUser(); int no=usersList.size(); System.out.println("Size:"+no); return usersList; } 

    C’est peut-être trop tard maintenant, mais juste pour vous montrer comment appeler une action jusqu’au spring en utilisant jQuery Ajax, je fournis ici tout ce que j’avais fait dans mon projet: (Appel Ajax Pour la validation de l’utilisateur)

    Fonction Ajax à écrire dans le fichier * .js:

     function validateUserBeforeCreatingUser(email){ var url='validateUser.htm?'&email='+email; $.ajax({ url: url, cache: false, success: function(response){ $("#errors").html(jQuery.sortingm(response)); //if errors not present if(jQuery.sortingm(response)==''){ createUser(); } }, error: function(response){ } }); } - function validateUserBeforeCreatingUser(email){ var url='validateUser.htm?'&email='+email; $.ajax({ url: url, cache: false, success: function(response){ $("#errors").html(jQuery.sortingm(response)); //if errors not present if(jQuery.sortingm(response)==''){ createUser(); } }, error: function(response){ } }); } 

    Et voici l’ action que j’ai écrite dans le contrôleur : (J’ai créé la page errors.jsp pour les erreurs de rendu)

     public ModelAndView validateUser(HttpServletRequest request, HttpServletResponse response) throws Exception { /* write code to validate user, if user with specified email not found then create error else keep errors page blank */ return new ModelAndView("partial", "errors", errors); } 

    J’espère que cela vous fournit la réponse et désolé pour l’indentation, je ne peux pas le faire correctement 🙁