【发布时间】:2016-03-17 20:14:59
【问题描述】:
我已尝试阅读有关在我的 Web 应用程序中使用静态或不使用静态的信息,并想快速询问我的实现是否良好。
以下是我的servlet
Integer total = HousingDAO.getTotal(AppUtils.getId(request));
Integer used = HousingDAO.getUsed(AppUtils.getId(request));
request.setAttribute("total", total);
request.setAttribute("used", used);
request.getRequestDispatcher("system/housing.jsp").forward(request, response);
这是我的 DAO
public class HousingDAO {
public static Integer getTotal(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id ";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
public static Integer getUsed(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id AND person IS NOT NULL";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
}
所以这些都是静态的,不需要像这样是静态的吗?
HousingDAO dao = new HousingDAO();
Integer total = dao.getTotal(AppUtils.getId(request));
Integer used = dao.getUsed(AppUtils.getId(request));
request.setAttribute("total", total);
request.setAttribute("used", used);
request.getRequestDispatcher("system/housing.jsp").forward(request, response);
有了这个 DAO
public class HousingDAO {
public Integer getTotal(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id ";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
public Integer getUsed(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id AND person IS NOT NULL";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
}
只是想知道第一个是否可以,还是我需要像第二个一样?
编辑
这是 ConnectionManager 类
public static Sql2o getSql2o(){
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
return new Sql2o(PropertiesManager.getProperty("dburl")
+ PropertiesManager.getProperty("dbname"),
PropertiesManager.getProperty("dbusername"),
PropertiesManager.getProperty("dbpassword"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
【问题讨论】: