用戶登錄和退出日志
當用戶登錄系統時,在日志表中插入一條記錄,記錄用戶登錄的時間,在用戶退出系統時記錄用戶退出系統的時間。
我們利用HttpSessionBindingListener接口來完成記錄登錄和退出日志的功能,該接口中定義了兩個方法:
·valueBound(HttpSessionBindingEvent event)
·valueUnbound(HttpSessionBindingEvent event)
如果一個類實現了HttpSessionBindingListener接口,當對象通過session.setAttribute()被綁定到Session中時,則對象的接口方法valueBound()被自動調用,當對象從session中移出時(通過調用session.invalidate()、session.removeAttribute()或session自動過期時),valueUnbound()方法將被自動調用。
下面我們使User.java類實現HttpSessionBindingListener接口,調整後的代碼如下所示:
代碼清單 18 實現了HttpSessionBindingListener的User.java
1. package bookstore;
2. import javax.servlet.http.HttpSessionBindingListener;
3. import javax.servlet.http.HttpSessionBindingEvent;
4. import java.sql.*;
5. import java.text.SimpleDate表單at;
6. import java.util.Date;
7.
8. public class User implements HttpSessionBindingListener
9. {
10. …
11. private String loginDatetime;//用戶登錄時間
12. …
13. public void valueBound(HttpSessionBindingEvent event)
14. {
15. Connection conn = null;
16. String sqlStr = "insert into T_LOGIN_LOG(ID, USER_ID, DT_LOGIN) " +
17. " values(SEQ_LOGIN_LOG_ID.NEXTVAL,?,? )";
18. try
19. {
20. conn = DBConnection.getConnection();
21. PreparedStatement pStat = conn.prepareStatement(sqlStr);
22. loginDatetime = getCurrDatetimeStr(); //當前時間串
23. pStat.setString(1, userId);
24. pStat.setString(2, loginDatetime);
25. pStat.executeUpdate();
26.
27. } catch (SQLException e)
28. {
29. throw new RuntimeException(
30. "用戶登陸日志寫入出錯");
31. } finally
32. {
33. try
34. {
35. if (conn != null)
36. {
37. conn.close();
38. }
39. } catch (SQLException ex)
40. {
41. ex.printStackTrace();
42. }
43. }
44. }
45.
46. public void valueUnbound(HttpSessionBindingEvent event)
47. {
48. Connection conn = null;
49. String sqlStr = " update T_LOGIN_LOG set DT_LONOUT = ? " +
50. " where USER_ID=? and DT_LOGIN = ?";
51. try
52. {
53. conn = DBConnection.getConnection();
54. PreparedStatement pStat = conn.prepareStatement(sqlStr);
55. pStat.setString(1, getCurrDatetimeStr());
56. pStat.setString(2, userId);
57. pStat.setString(3, loginDatetime);
58. pStat.executeUpdate();
59.
60. } catch (SQLException e)
61. {
62. throw new RuntimeException(
63. "用戶退出日志寫入出錯");
64. } finally
65. {
66. try
67. {
68. if (conn != null)
69. {
70. conn.close();
71. }
72. } catch (SQLException ex)
73. {
74. ex.printStackTrace();
75. }
76. }
77. }
78.
79. //獲取當前時間字串,以yyyyMMddHHmmss格式返回,如20050505010101
80. private static String getCurrDatetimeStr()
81. {
82. SimpleDate表單at sdf = new SimpleDate表單at("yyyyMMddHHmmss");
83. return sdf.表單at(new Date());
84. }
85. }