更新时间:2021-08-24 来源:黑马程序员 浏览量:

在项目开发中,除了需要设计实体类,还需要设计一些工具类,用于完成不同的操作。下面分别介绍工具类的设计。
(1)DbUtil类
在utils包下新建DbUtil类,用于获取数据库连接,DbUtil类具体实现如文件13-5所示。
文件13-5 DbUtil.java
public class DbUtil {
private String dbDriver = "com.mysql.jdbc.Driver";
private String dbUrl=
"jdbc:mysql://localhost :3306/bookmanager?characterEncoding=utf-8";
private String dbUserName =”root";
private String dbPassword = "root";
public Connection getConnection()throws Exception{
Class. forName (dbDriver) ;
Connection cor =
(Connection)DriverManager.getConnection(dbUr1,dbUserName,dbPassword);
return con;
}
public void closeCon Connection con) throws Exception {
if (con!=null) {
con.close () ;
}
}
}在文件13-5中,第2~6行代码创建JDBC所需的4个连接参数;第7~12行代码用于获取数据库连接;第13~18行代码用于关闭JDBC连接对象资源。
(2)tolUtil类
在utils包下新建toolUtil类,在该类中定义一些方法,用于判断字符串是否为空、获取当前时间、对时间进行格式化和获取当前登录用户等。toolUtil 类具体实现如文件13-6所示。
文件13-6 toolUtil.java
public class toolUtil
public static boolean isEmpty (String str) {
if (str != null && !"".equals (str.trim( ) ) ){
return false;
}
return true;
public static Long getTime () {
long time=System.currentTimeMillis () ;
return time;
public static string getDateByTime (Long time) {
simpleDateFormatformat new SimpleDateFormat ("yyy-MM-dd14HH:mm:ss") ;
String string = format.format(new Date (time) ) ;
return string;
}
public static User getUser (HttpSession session) {
User user = (User) session.getAttribute ("user") ;
return user;
public static void setUser (HttpSession session, User user){
session.setAttribute ("user", user) ;
}
}在文件13-6中,第2~7行代码用于判断字符串是否为空;第8~11行代码用于获取当前时间;第12~17行代码用于对时间进行格式化;第18~21行代码用于获取当前登录用户;第22~24行代码用于设置用户登录。
1024首播|39岁程序员逆袭记:不被年龄定义,AI浪潮里再迎春天
2025-10-241024程序员节丨10年同行,致敬用代码改变世界的你
2025-10-24【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19