谢谢。
这是具有相关代码的bean。
@ManagedBean(name = "scheduleAppBean")
@ViewScoped
public class ScheduleAppBean {
/*
variables omitted
*/
//datasource to access database
@Resource(name="jdbc/mydb") private DataSource source;
private Connection conn;
//constructor
public ScheduleAppBean(){
job= new ArrayList<ScheduleAppHelper>();
propertiesOptions= new ArrayList<SelectItem>();
try {
Context ctx = (Context) new InitialContext();
source = (DataSource) ((InitialContext) ctx).lookup("java:comp/env/jdbc/mydb");
conn=source.getConnection();
} catch (NamingException ex) {
Logger.getLogger(SchedulesBean.class.getName()).log(Level.SEVERE, null, ex);
}catch (SQLException ex) {
Logger.getLogger(ScheduleBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
//called when page first loads to fill propertiesOptions list
public void loadProperties(){
// clear any previous list data
propertiesOptions.clear();
try {
Connection conn=getDatabaseConnection();
PreparedStatement query= conn.prepareStatement("select propName from property;");
ResultSet result= query.executeQuery();
// reset variable to zero in case some data is present
propertiesNumber=0;
//track current customer number
int count=0;
//retrieve all clients and add to list, update propertiesNumber
while(result.next()){
propertiesOptions.add(new SelectItem(result.getString("propName")));
//increment variables
propertiesNumber++;
count++;
}
} catch(Exception ex){
Logger.getLogger(ScheduleBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Connection getDatabaseConnection(){
if(conn!=null)
return conn;
else{
try {
Context ctx = (Context) new InitialContext();
source = (DataSource) ((InitialContext) ctx).lookup("java:comp/env/jdbc/mydb");
conn=source.getConnection();
return conn;
} catch (NamingException ex) {
Logger.getLogger(SchedulesBean.class.getName()).log(Level.SEVERE, null, ex);
}catch (SQLException ex) {
Logger.getLogger(ScheduleBean.class.getName()).log(Level.SEVERE, null, ex);
}catch(Exception ex){
Logger.getLogger(ScheduleBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conn;
}
}
这是context.xml
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" removeAbandoned="true"
maxActive="20" maxIdle="10" maxWait="2000" name="jdbc/mydb" password="*****"
type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/******"username="*****"/>
这是我的JSF页面。
<h:body onload="#{scheduleAppBean.loadProperties()}">
<div class="scheduleNavigation">
<ul>
<li>
<h:form>
<h:commandLink value="Assign Schedule" styleClass="mainHeader" action="../administrator/assignschedule.xhtml">
</h:commandLink>
</h:form>
</li>
<li>
<h:form>
<!--This is the link I click repeatedly-->
<h:commandLink value="Schedule Now" styleClass="mainHeader" action="../administrator/appointments.xhtml">
</h:commandLink>
</h:form>
</li>
<li>
<h:form>
<h:commandLink value="My Schedule" styleClass="mainHeader" action="../administrator/myschedule.xhtml">
</h:commandLink>
</h:form>
</li>
</ul>
</div>
</h:body>