1

使用 Apache MyFaces JSF 2.0。

XHTML 代码:

<h:form id="searchUser" prependId="false">
    <h:selectManyListbox value="#{listManyBean.listUser}" id="userList"  size="10">
    <f:selectItems value="#{listManyBean.selListUser}"/> 
    </h:selectManyListbox>
    <h:commandButton id="clickGo" value="#{bundle.btn_login}"
     type="submit" 
    action="#{listManyBean.submitList}"/>
    <input type="button" value="Add" onclick="addUserToList();" />
</h:form>

添加到列表的脚本:

function addUserToList(){
     var UserListBox = document.getElementById('UserList');
     var UserNum = document.getElementById('UserNumber').value.toUpperCase();
     var UserOption = new Option(UserNum,UserNum);
     UserListBox.options[UserListBox.options.length] = UserOption;    
}

豆:

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.model.SelectItem;

@ManagedBean
@RequestScoped
public class ListManyBean {
    private List<String> listUser;
    private List<SelectItem> selListUser;

public List<SelectItem> getSelListUser() {
    return selListUser;
}


public List<String> getListUser() {
    return listUser;
}


public void setListUser(List<String> listUser) {
    this.listUser = listUser;
}

    public void submitList() {
        System.out.println("User List Value***" + this.listUser);
        System.out.println("User ListPan***++"+selListUser);
    }
}

无论添加一条或多条记录,我总是得到空值。请让我知道这里出了什么问题。

4

1 回答 1

1

您正在使用 JS 而不是使用 JSF 添加新项目。这样,JSF 就不会知道有关新项目的任何信息。此信息绝不会提交给服务器端。

用理智的 JSF 方法替换错误的 JS 方法:

<h:form>
    <h:selectManyListbox value="#{bean.selectedUsers}" size="10">
        <f:selectItems value="#{bean.availableUsers}" /> 
    </h:selectManyListbox>
    <h:commandButton value="submit" action="#{bean.submit}" />
    <h:inputText value="#{bean.user}" />
    <h:commandButton value="Add" action="#{bean.add}">
        <f:ajax execute="@form" render="@form" />
    </h:commandButton>
</h:form>

@ManagedBean
@ViewScoped
public class Bean {

    private List<String> selectedUsers;
    private List<String> availableUsers = new ArrayList<String>();
    private String user;

    public void add() {
        availableUsers.add(user);
        user = null;
    }

    public void submit() {
        System.out.println("Selected users: " + selectedUsers);
        System.out.println("Available users: " + availableUsers);
    }

    // ...
}
于 2012-10-25T17:07:50.810 回答