如果我正确理解您的问题,您的问题是如何与您的 Restlet 验证程序中的数据库进行交互,以及如何在您的 Restlet 应用程序中协同工作。
最好的方法是定义一个实现数据库交互逻辑的 DAO。像这样的东西:
public class SecurityDao {
private DataSource dataSource;
public SecurityDao() {
// Intialize your datasource using DBCP or C3P0
dataSource = new com.mchange.v2.c3p0.ComboPooledDataSource();
dataSource.setDriverClass(MyDriverClass.class);
dataSource.setJdbcUrl("jdbc:mysql://locahost/mydb");
dataSource.setUser("username");
dataSource.setPassword("pwd");
// Don't forget to clean the pool when Restlet application stop
// with ComboPooledDataSource#close method
}
public boolean hasUserPassword(String user, String password) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// Some SQL request like that
ps = conn.prepareStatement("select * from <MYTABLE> where USER = ? and PASSWORD = ?");
ps.setString(1, user);
ps.setString(2, password);
rs = ps.executeQuery();
return rs.next();
} catch(Exception ex) {
(...)
} finally {
// close rs
// close ps
// close conn
}
}
}
现在我们已经实现了 DAO,我们将从 Restlet 应用程序类实例化它并在您的验证器中设置它:
public class zeus extends Application {
private SecurityDao securityDao;
public zeus() {
securityDao = new SecurityDao();
}
@Override
public Restlet createInboundRoot() {
(...)
UserVerifier verifier = new UserVerifier();
verifier.setSecurityDao(securityDao);
(...)
return guard;
}
}
您现在需要调整一下您的验证器,如下所述:
public class UserVerifier extends SecretVerifier {
private SecurityDao securityDao;
public void setSecurityDao(SecurityDao securityDao) {
this.securityDao = securityDao;
}
public boolean verify(String identifier, char[] secret) {
System.out.println(identifier);
System.out.println(secret);
return securityDao.hasUserPassword(identifier, new String(secret));
return true;
}
}
实际上,Restlet 应用程序的 createInboundRoot 方法初始化了路由。这在应用程序启动时完成一次,即当第一个请求完成时。然后,当接收到 HTTP 请求时,Restlet 会自动调用验证器,并在该请求中提供安全提示。您不必显式调用验证器的验证方法,Restlet 框架会这样做......
希望它可以帮助你,蒂埃里