【发布时间】:2017-05-19 09:06:20
【问题描述】:
(注意:我已经检查了具有类似标题的问题,但没有帮助或我没有正确理解解决方案)
我要做的就是从数据库中检索国家名称并将它们显示在下拉列表中。问题源于 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>
结果.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 谢谢
【问题讨论】:
-
问题来自于 JSF 的实现?请发布您面临的确切错误?
-
@RahulSaini 如果您单击最后的图像,您将看到输出。我没有收到错误,我要么显示输出错误(JSF),要么我没有正确检索数据。谢谢
-
抱歉,但您必须了解,在办公室访问时无法打开/解析指向 imgur、facebook、twitter 等的链接,因为这些链接是被禁止的。因此看不到错误图像。您可以尝试将 arrayList 存根,即创建一个虚拟 arrayList 并返回它,看看错误是否仍然存在?
-
它必须是 String List
的列表,即要在结果中返回的国家/地区名称,而不是跑步者 List 的列表。您只需遍历结果集并将国家/地区“字符串”数据添加到列表中。您实际调用的是 runner Managed Bean 的一个实例,并从中调用 getCountryList 方法,它应该返回一个字符串列表(国家名称)而不是 Runner 列表。 -
@RahulSaini 当我在 getCountryList 中放置一个虚拟列表并将方法更改为
而不是 一切正常,因此它必须与信息的检索一样。
标签: jsf jakarta-ee