使用Spring MVC和ajax来处理对象列表 [英] using Spring MVC and ajax to handle list of objects

查看:120
本文介绍了使用Spring MVC和ajax来处理对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用AJAX和spring MVC,如何从Spring Controller返回对象列表并使用Jquery显示它们。

在下面发出Ajax请求:

making Ajax request below:

$.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+"<tr>";
                            userListContent=userListContent+"<td><input type='checkbox' value='"+obj.id+"'  id='select' name='select'/></td> ";
                            userListContent=userListContent+"<td id='NameColumn'>"+obj.firstName+" "+obj.lastName +"</td>";
                            userListContent=userListContent+"<td id='genderColumn'>"+ obj.gender +"</td>";
                            userListContent=userListContent+"<td id='userNameColumn'>"+ obj.userName +" </td>";
                            userListContent=userListContent+"<td id='userTypeColumn'> "+ obj.userType +"</td>";
                            userListContent=userListContent+"<td id='statusColumn'>"+ obj.status +"</td>";
                            userListContent=userListContent+"<td id='emailIdColumn'>"+ obj.emailId +"</td>";
                            userListContent=userListContent+"<td id='addressColumn'>"+ obj.address +"</td>";
                            userListContent=userListContent+"<td id='contactnoColumn'>"+ obj.contactNo +"</td>";
                            userListContent=userListContent+"</tr>";

                            });

                        $('#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<String, Object> deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException
     {
         System.out.println("Ajax Request Received for delete User...............");
         Map<String, Object> model = new HashMap<String, Object>(); 

      JsonResponse js=new JsonResponse();
      js.setResult("pass");
      js.setStatus("active");
    // String operation=request.getParameter("operation");
     String[] 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 .
      */


     String msg="hello";
     List<UserDetails> usersList = userService.getAllUser();
     int no=usersList.size();
     System.out.println("Size:"+no);
     model.put("message", usersList);
     model.put("jso", js);

     return model;

 }


推荐答案

你将接受并以JSON的形式返回对象,所以在spring dispatcher servlet xml中添加jackson mapper bean。杰克逊映射器完成所有操作。你不需要做映射或者手动转换。

You are going to accept and return objects in the form of JSON, so add the jackson mapper bean in spring dispatcher servlet xml. Jackson mapper does it all. You don't need to do mapping or conversion manually.

<beans:bean id="jacksonMessageChanger"  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <beans:property name="supportedMediaTypes" value="application/json" />
</beans:bean>

<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <beans:property name="messageConverters">
        <util:list id="beanList">
            <beans:ref bean="jacksonMessageChanger" />
        </util:list>
    </beans:property>
</beans:bean>

现在您的控制器将是这样的:

Now your controller would be like this :

@RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public @ResponseBody
List<UserDetails> 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<UserDetails> userList = userService.getAllUser();

    return userList;
}

现在你的ajax调用会是这样的:

Now you ajax call will be something like this :

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.stringify(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("<option value='-1'>Select User</option>");
        for ( var i = 0, len = data.length; i < len; ++i) {
            var user = data[i];
            $('#allUsers').append("<option value=\"" + user.userId + "\">" + user.userName+ "</option>");
    }
}

这将有效。

这篇关于使用Spring MVC和ajax来处理对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆