如何将列表从javascript传递给spring控制器

时间:2013-08-17 17:11:11

标签: java javascript jquery spring-mvc freemarker

我有一个问题,javaScript如何将两个sepparate列表传递给spring控制器。在我的freeMarker模板上,我选择更改两个列表的集合。 这是两个列表的呈现:

编辑:我发现Jquery有Ui plagin

.sortable("toArray", { key: "id" }) 

方法,所以我将Id值添加到<李>标签

<div class="span5" id="listBox">
            <h3>Assigned Servers</h3>
            <#if assignedServers?has_content>
                <ul id="sortable1" class="connectedSortable">
                    <#list assignedServers as responsible >
                        <li class="ui-state-default"
                            id="${responsible.id}" >${responsible.server_name}</li>
                    </#list>
                </ul>
            <#else>
                <h4>This employee have no assigned servers yet.</h4>
            </#if>
        </div>

        <div class="span5" id="listBox">
            <h3>Available Servers</h3>
            <#if availableServers?has_content>
                <ul id="sortable2" class="connectedSortable">
                    <#list availableServers as available >
                        <li class="ui-state-default"
                            id="${available.id}" >${available.server_name}</li>
                    </#list>
                </ul>
            <#else>
                <h4>There is no available servers to assign.</h4>
            </#if>
        </div>

编辑:我改变了JQuery功能:

<script>
        $(function() {
            var assigned = "";
            var available = "";

            $('#sortable1').sortable({
                connectWith: '#sortable2',
                update: function(event, ui) {
                    assigned = $(this).sortable("toArray", { key: "id" });
                    }
            }).disableSelection();

            $('#sortable2').sortable({
                connectWith: '#sortable1',
                update: function(event, ui) {
                    available = $(this).sortable("toArray", { key: "id" });
                    }
            }).disableSelection();

            $('#assign').click(function(){
                $.ajax({
                    type: "POST",
                    url: "/ServerMonitoring/employee_management/serv_assignment/2",
                    data: JSON.stringify({
                         serversListModel: {
                             "assignedServers": assigned,
                             "availableServers": available
                         }
                     }),
                    datatype: "jsondata",
                    contentType: 'application/json',
                    success: function(data) {
                        alert("Success");
                    },
                    error: function (e) {
                        alert("Error: " + e);
                    }
                });
                return false;
            });
            //debugger
        });
    </script>

编辑:这是我的新弹簧控制器:

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public @ResponseBody ModelAndView onSubmit(
        @ModelAttribute("serversListModel") ServersListModel serversListModel,
        @PathVariable("id") Long responsibleId,
        BindingResult result,
        HttpServletRequest request,
        HttpServletResponse response,
        SessionStatus status) throws ParseException {

    if (!result.hasErrors()) {
        if (serversListModel.getAvailableServers() != null) {
            for (String id : serversListModel.getAvailableServers()) {
                ServerEntity entity = employeeService.getServerById((long)Integer.parseInt(id));
                entity.setResponsible(responsibleId);
                adminService.updateServer(entity);
            }
        }

        if (serversListModel.getAssignedServers() != null) {
            for (String id : serversListModel.getAssignedServers()) {
                ServerEntity entity = employeeService.getServerById((long)Integer.parseInt(id));
                entity.setResponsible((long) 0);
                adminService.updateServer(entity);
            }
        }
        status.setComplete();
        return new ModelAndView("redirect:/employee_management/employee_manager");


    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("redirect:/employee_management/serv_assignment");
    }

}

EDITED:new ServersListModel - 它是一个带有两个vars的简单POJO

public class ServersListModel {

private List<String> assignedServers;

private List<String> availableServers;
...
}

通过在FireBug中调试JSON传递的字符串:

{"serversListModel":{"assignedServers":["2","4"],"availableServers":["1","5","3","6","7","8"]}}

但是,我仍然无法恢复该字符串,我的模型中的变量stil在debuging中包含NULL。 将@RequestBody anotation置于@ModelAttribute(“serversListModel”)的位置使得Jquery抛出BadRequest错误。 如果,在方法体内,我调用

String jsonBody = IOUtils.toString(request.getInputStream());

它将返回带有requerd id的JSON String对象,所以我很接近回答。

请帮我查一下Controller中的错误。谢谢。

1 个答案:

答案 0 :(得分:0)

我设法解决了我的问题,我想与您分享解决方案:

我将模型更改为Long类型:

public class ServersListModel {

private List<Long> assignedServers;

private List<Long> availableServers;

然后我添加了Maven依赖:

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

并将Jackson配置为:

<bean id="jacksonMessageConverter"
      class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

<bean id="defaultViews"
      class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

(如果所有这些都很重要,我就不会因此而死)。)

Naw my JQury.Ajax脚本看起来像这样:

 $(function() {
            var assigned = "";
            var available = "";

            $('#sortable1').sortable({
                connectWith: '#sortable2',
                dropOnEmpty: true,
                update: function(event, ui) {
                    assigned = $(this).sortable("toArray", { key: "id" });
                    }
            }).disableSelection();

            $('#sortable2').sortable({
                connectWith: '#sortable1',
                dropOnEmpty: true,
                update: function(event, ui) {
                    available = $(this).sortable("toArray", { key: "id" });
                    }
            }).disableSelection();

            $('#assign').click(function(){
                $.ajax({
                    type: "POST",
                    url: "/ServerMonitoring/employee_management/serv_assignment/2",
                    data: JSON.stringify({
                            assignedServers: assigned,
                            availableServers: available
                    }),
                    datatype: "json",
                    'scriptCharset': "utf-8",
                    'contentType': "application/json;charset=UTF-8",
                    success: function(data) {
                        //alert("Success");
                    },
                    error: function (e) {
                        //alert("Error: " + e);
                    }
                });
                return false;
            });
            //debugger
        });

最终我的MVC控制器:

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public @ResponseBody  ModelAndView onSubmit(
        @RequestBody ServersListModel serversListModel,
        @PathVariable("id") Long responsibleId,
        BindingResult result,
        SessionStatus status) throws ParseException, IOException {

    if (!result.hasErrors()) {
        if (serversListModel.getAssignedServers() != null) {
            for (Long id : serversListModel.getAssignedServers()) {
                ServerEntity entity = employeeService.getServerById(id);
                entity.setResponsible(responsibleId);
                adminService.updateServer(entity);
            }
        }

        if (serversListModel.getAvailableServers() != null) {
            for (Long id : serversListModel.getAvailableServers()) {
                ServerEntity entity2 = employeeService.getServerById(id);
                entity2.setResponsible((long) 0);
                adminService.updateServer(entity2);
            }
        }
        status.setComplete();
        return new ModelAndView("redirect:/employee_management/employee_manager");
    } else {
        return new ModelAndView("redirect:/employee_management/serv_assignment");
    }
}

一切都很完美。享受!!!