Spring MVC得到multiple =“true”select作为Controller

时间:2016-12-26 10:23:22

标签: spring spring-mvc

我有Channel,Node和Channel_Node类。

public class Node {
    private String name;
    private String address;
    private Long idNode;
    private String description;
    private Organization organization;
    private Region region;
    private NodeType nodeType;
    private Integer bound;
    private Collection<ChannelNode> channelNodes;
    ....

public class Channel {
    private Long idChannel;
    private String name;
    private String description;
    private Long diameter;
    private Long capacity;
    private Long currentCapacity;
    private ChannelType channelType;
    private Long length;
    private Collection<ChannelNode> channelNodes;
    ....

public class ChannelNode {
    private Long idChannelNode;
    private String name;
    private Node node;
    private Channel channel;
    ....

我有以下Spring表单:在我的addChannel.jsp

中选择
<form:select path= "channelNodes" multiple="true" id="nodeBox">

我需要将channelNodes作为集合并将其设置为我的控制器类的create方法中的Channel对象。

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(HttpServletRequest request, @Valid @ModelAttribute("channel") Channel channel,
        BindingResult result) {

    LOG.info(String.format("Create new channel: %s", channel));

    /*
     * if (result.hasErrors()) { return CHANNEL_ADD_VIEW; } else {
     */
    ChannelType channel_type = channelTypeService.getOne(Long.parseLong(request.getParameter("channelType")));
    channel.setChannelType(channel_type);

    channelService.create(channel);

    return CHANNEL_LIST_VIEW_REDIRECT;
    // }

}

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题:

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(HttpServletRequest request, @Valid @ModelAttribute("channel") Channel channel,
        BindingResult result) {

    LOG.info(String.format("Create new channel: %s", channel));

    /*
     * if (result.hasErrors()) { return CHANNEL_ADD_VIEW; } else {
     */
    ChannelType channel_type = channelTypeService.getOne(Long.parseLong(request.getParameter("channelType")));
    channel.setChannelType(channel_type);

    List<ChannelNode> channelNodes = new ArrayList<ChannelNode>();
    ChannelNode channel_node;

    String[] channel_nodes = request.getParameterValues("channelNodes");

    for (String id_node : channel_nodes) {

        channel_node = new ChannelNode();
        channel_node.setNode(nodeService.getOne(Long.parseLong(id_node)));
        channel_node.setChannel(channel);
        channelNodes.add(channel_node);
    }

    channel.setChannelNodes(channelNodes);

    channelService.create(channel);

    return CHANNEL_LIST_VIEW_REDIRECT;
    // }

}