创建一个下拉列表以在JSF中显示数据库数据

时间:2017-05-19 09:06:21

标签: jsf java-ee

(注意:我已经检查了类似标题的问题但没有帮助,或者我没有正确理解解决方案)

我尝试做的就是从数据库中检索国家/地区名称并将其显示在下拉列表中。问题来自JSF的实现,因为查询读取和连接工作正常。

的index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Top Ten</title>
    </h:head>
    <h:body>
        <h1>Choose a country</h1>
        <h:form>
            <h:selectOneMenu value="#{runner.getCountryList()}" >
            <f:selectItems value="#{runner.getCountryList()}"/>
            </h:selectOneMenu>
        </h:form>
    </h:body>
</html>

Results.java

package honolulu.marathon;

/* imports have been removed to make code compact */
@ManagedBean(name="runner")
@SessionScoped
public class Results implements Serializable{
        private Connection con = null;
    private DataSource ds;
    public Results(){
        try {
                Context ctx = new InitialContext();
                ds = (DataSource)ctx.lookup("jdbc/honolulu2017");
        } catch (NamingException e) {
                e.printStackTrace();
        }   
    }
    private Connection getConnection(){
        try {
            con = ds.getConnection();
        } catch(Exception e){
            e.printStackTrace();
        }
        return con;        
    }
    /* fill the drop-down list */
    public List<Runner> getCountryList() throws SQLException{
        getConnection();
        if(ds==null)     
                throw new SQLException("Can't get data source");
        //get database connection
        if(con==null)
                throw new SQLException("Can't get database connection");
        PreparedStatement ps 
                = con.prepareStatement(
                   "select COUNTRY from RESULTS_TEST");
        //get runner data from database
        ResultSet result =  ps.executeQuery();
        List<Runner> list = new ArrayList<>();
        while(result.next()){
                Runner runner = new Runner();
                runner.setCountry(result.getString("country"));
                //store all data into a List
                list.add(runner);
        }
        return list;  
      }

}

Runner.java

package honolulu.marathon;

public class Runner {

    public String country;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }    
}

输出:Click here for output 感谢

1 个答案:

答案 0 :(得分:0)

它必须是字符串列表的列表,即在结果中返回的国家/地区名称,而不是列表的运行者列表。您需要迭代结果集并将国家/地区“字符串”数据添加到列表中。你实际调用的是一个运行Managed Bean和getCountryList方法的实例,它应该返回一个字符串列表(国家名称)而不是Runner的列表。