JBuilder2005实战JSP之日志和部署(7)
用户登录和退出日志当用户登录系统时,在日志表中插入一条记录,记录用户登录的时间,在用户退出系统时记录用户退出系统的时间。
我们利用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. } |
补充:Web开发 , Jsp ,