【问题标题】:using Spring MVC and ajax to handle list of objects使用 Spring MVC 和 ajax 处理对象列表
【发布时间】:2012-10-23 23:09:00
【问题描述】:

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

在下面发出 Ajax 请求:

$.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 控制器

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

 }

【问题讨论】:

  • 请正确格式化代码,现在完全不可读
  • 您的问题或问题是什么?

标签: java javascript jquery ajax spring-mvc


【解决方案1】:

直接返回 ArrayList 应该可以工作...

@RequestMapping(value="/deleteUser",method= RequestMethod.POST)
     public @ResponseBody ArrayList<UserDetails> deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException
     {
         System.out.println("Ajax Request Received for delete User...............");


    // 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);

     return usersList;

 }

【讨论】:

    【解决方案2】:

    您将以 JSON 的形式接受和返回对象,因此在 spring dispatcher servlet xml 中添加 jackson mapper bean。杰克逊映射器做到了这一切。您无需手动进行映射或转换。

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

    现在你的控制器应该是这样的:

    @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 调用将是这样的:

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

    这会起作用。

    【讨论】:

    • @Ayush 我已经根据 OP 提供的输入和 sn-ps 回答了这个问题。理想情况下,删除操作的请求映射方法应该是DELETE和http状态响应402。
    【解决方案3】:

    现在可能为时已晚,但只是为了向您展示如何使用 jQuery Ajax 在 spring 中调用一个动作,我在这里提供了我在项目中所做的一切:(用于用户验证的 Ajax 调用)

    要在 *.js 文件中编写的 Ajax 函数:

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

    这是我在 in controller 中编写的 action :(我创建了 errors.jsp 页面用于呈现错误)

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

    希望这可以为您提供答案,对于缩进感到抱歉,我做不到 :-(

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2020-07-13
      • 2015-07-31
      • 1970-01-01
      • 2014-07-28
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多