Recently learned JSP. After reading the book, after reading some simple counters written online, I started to write one, now share it. It is also possible, for beginners, it should be a nice learning example, which is designed to have some simple questions from JavaBean, connecting to databases, and sessions, but for beginners can deepen the understanding of these concepts. The simple statistical device I made, mainly realizing the anti-refresh, records IP, and the number of statistics IP first design a database first. I have used a simple Access (mainly easy to use), first design two tables in Access: 1. Counter table (including two columns: numbers, counters) --- This table is used to record access to the number of objectives. 2, iptables table (including two columns: number, IP) ---- This table is used to record the IP address of the visitor. Ok, the database is designed, as long as the ODBC is registered on your machine, I can pull it, I'm registering the ODBC data source is good, I will put the program code code: //counterbean.javaPackage YG; Import java.io. *; import java.sql. *;
public class CounterBean extends Object {String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; String sConnStr = "jdbc: odbc: count"; private Connection conn = null; private Statement stmt = null; ResultSet rs = null; // Register Database driver public counterbean () {try {class.forname (sdbdriver);} catch (java.lang.classnotfoundexception e) {system.err.println ("counterbean (): E.getMessage ());}}
// Establish a database connection and define data query Public ResultSet ExecuteQuery (String SQL) {RS = NULL; try {conn = drivermanager.getConnection (sconnstr); stmt = conn.createstatement (); rs = stmt.executeQuery (SQL); Catch (SQLException E) {system.err.println ("ExecuteQuery:" E.GetMessage ());} Return Rs;}
// definition data operations public void executeUpdate (String sql) {stmt = null; rs = null; try {conn = DriverManager.getConnection (sConnStr); stmt = conn.createStatement (); stmt.executeUpdate (sql); stmt.close (); Conn.close ();} catch (sqlexception ex) {system.err.println ("ExecuteUpdate:" ex.getMessage ());}} // Turns off the database public void closestMT () {TRY {STMT. Close ();} catch (sqlexception e) {E.PrintStackTrace ();}}
Public void closeconn () {Try {conn.close ();} catch (sqlexception e) {E.PrintStackTrace ();}} // Synchronization Update Counter public synchronized int getCount () {int count = 0; rs = null; Try {ExecuteUpdate ("Update Counter Set Counter = Counter 1); RS = ExecuteQuery; rs.next (); count = rs.Getint (" counter "); stmt.close () Conn.close ();} catch (SQLEXCEPTION E) {} Return Count;}} // counter = "@ Page ContentType = Text / HTML; Charset = GB2312"%> <% @ Page Import = "YG .Counterbean "%> <% @ page import =" java.io. * "%> <% @ page import =" java.sql. * "%>