Servlets and sessions - good practices

Hello,
This is a newbie question.
The scenario:
Let's say I made a bank application that allows a user to log in and view 2 pages; the simple home page with just some static content and then a dynamic page that lists the last 10 transactions fetched from a database.
When the user goes to view the transactions, a servlet is invoked in which I create a connection object and query the db for the last 10 transactions, store the Collection in the session and then forward to displayTransactions.jsp.
The question:
Every time a user goes to view the last 10 transactions page, should I query the database each time or should I check to see if the list (Collection) was already loaded and present in the session, and if so, avoid the potentially expensive i/o operation of reading from a database and display the list from the session?
If the answer is to use the session, my follow up question is this: what if a transaction has been made since I queried the database and stored the results in the session. I wouldn't see the new transaction until I kill the session and query the database again right?
Best regards,
-b

If you want the last 10 transactions, you cannot (and should not) use the session. If you use the session the data can go stale, as you have figured out yourself. You need to fetch them on each request. Unless you have hundreds of visitors going to the page at the same time, it is far from expensive though, so why bother trying to optimize it? If your query is optimal (indexed, no queries that need full table scans, etc.), you shouldn't have any problems.

Similar Messages

  • Refresh code servlet and session bean don't work more.

    Hi all,
    I'm not sure if it's a problem with oc4j, but maybe someone can
    help me.
    I'm working with Jdev 10.1.3.0.4(SU4) on Fedora Core 5 and XP.
    I create an application with a servlet, ran the servlet and
    all things work. Change the code in servlet, recompile and refresh
    the browser and all work fine.
    But, when I create a CMP Entity Beans from Tables with EJB 3.0 on
    a simple table and change the code in servlet, recompile and refresh
    the browser the code of servlet stay old. Just restart oc4j make the changes
    work. Changes on entity bean ou session beans or junit class take
    the same problem, just after the restart oc4j do the job.
    Is it a bug? Is thera a workaround?
    Thanks for all,
    Luciano

    Oh and before you tell me to just use XSLT on the output to get it how I want it, or use XMLType views where the XML is generated on the database server, I can assure you I know both of those options, but they both cut into the profitability of running a high-volume service.
    The XSU (XML SQL Utility for those keyword searching) is great in that I can host it on middle tier servers in any servlet container and take the burden of XML generation and parsing off the $40K/processor server. If I can further take the burden of XSLT transformations off the middle tier, so much the better... The XSU allows me to run the same throughput on probably something like half the hardware and a tenth the licensing fees.
    So here's a huge vote in favor of continued development of the XSU...I would also like it to handle XML attributes on inserts/updates rather than having to use the "canonical" element form.
    If anyone knows an even better approach, please speak up!

  • Servlets and Sessions

    Hello,
    I have a servlet that saves a value to the session then redirects to a .jsp page. On the .jsp page I grab the value and display just fine. But when I hit the refresh button my value go's back to 0 ???
    I thought If you saved something in the session it stayed there for the session and I'm not sure what I'm doing wrong, maybe somebody can give me a clue.
    -thanks

    Wild guess... maybe you create a new session every
    time the JSP runs?Nope, I finally figured out it was something in my code. I was setting the attribute twice instead of setting it then getting it.
    It works just peachy now.
    Why would it create a new session everytime the jsp runs, bad wild guess.
    thanks

  • Applet+servlet+good practice

    Hi there,
    I'd like to know what is of "good taste" when it comes to transfer data between servlet and applet : using vector to carry the data or by some way transfer the resultset itself ?
    Or better : some sort of xml that would allow the end user to work disconnected from the servlet, do its changes when traveling (hope it's not by plane these times...) and then back to the office by some usual conciliation mechanism update the database ....?
    Currently i'm using the firs method, but, not sure it's the best way
    Any good practical (already improved) idea ?
    thanks and welcome to all

    I think the better way is to transfer XML data, because this way you are free to implement a client in a different language, not only java. XML is a standard for the interexchange of data between different platforms and different languages. I think it's the best option. But it has disadvantages too. You transfer more data than strictly necessary by the web and transfer times are higher, so if you are looking for efficiency, you should think in propietary formats of information (compressed...).
    I hope this helps you, and sorry about my English.

  • Good Practices and Code Conventions

    Hi All,
    What are the good practices in java? Are there coding convention to be followed?
    I would like to improve my coding standards and write better code. Please help me.
    Thanks
    Diana

    Diana12 wrote:
    Then how to make it excellent?Are you serious? Do you expect us to give you a 2-line summary of how to make "excellent" code?
    It takes some time to learn to write excellent code and it can't easily be summarized into 1-2 sentences. If it could, then it would be much easier to learn (that would be nice!).
    Experience, making mistakes, realizing they were mistakes, not making the same mistakes later on. Having your code criticized by someone who writes better code than you. That's how you learn to write excellent code.
    Write simple code, keep it clean, make each method do one thing, write code that doesn't need documentation, document where you must, adhere to the open-close principle, adhere to the KISS principle, adhere to the YAGNI principle, ...
    Grab [The Pragmatic Programmer|http://www.pragprog.com/the-pragmatic-programmer] and read it. Then read it again. Do some more exercises and read it a third time.

  • Connection to the database and session

    Friends I am developing a JSP based application ,and I am storing Connection (to the database) info in a session variable in my main menu , and then I retrieve the connection session in all the pages that I navigate to.
    But a friend of mine told me it is not a good programming practice.He adviced me to use the connection pooling to make effecient use of the connection.
    So using session for storing connection to the database is a bad idea ?
    I thought it is bad idea to get connected to the database everytime a jsp is thrown ...hence I was using session variable.
    Please give ur thought about this.
    Thanks.

    Well.
    You are using a kind of connection pooling already, since you make a connection and reuse it along every jsp page in a session but reusability is at the cut&paste level here.
    And what would you do if you needed to share a connection between sessions (scope:application)
    Or how would you resolve the need to connect to 2 databases in one JSP page ?? Duplicate the code from the "main menu" ?
    If you have let's say 5 applications written as you described and the connection data (ip address, SID, host) changes as someone moves the database to another machine (for example :-))) you will have to manually correct all 5 applications. So it's not much of flexibility in this kind of code.
    Connection pooling as I understood it (I might be wrong :-))) is placing the code in a bean or servlet and the parameters in a txt (or better xml) file so when something changes you don't rewrite applications, just rewrite one txt (xml) file and you are done.
    If you use a connection pool as a bean you have the bean scopes you can choose from and so on.....
    Visit
    http://www.codestudio.com/index.shtml
    for an example of a very well written connection pool. Maybe there you will find other issues to help you decide.
    Hope this helps!
    Bye

  • When to use servlets and jsp in an application like  shoping cart?

    Hi All
    I m going to design and implement a web application using servelts and jsp. I am still at its requirements analyze stage.
    The application is almost likely a shopping cart. So if any of you have the deep knowledge about this domain with servlets and jsp please help me for a good design. What I realy need to know is that
    1. what are the core requirements for a shoping cart ?
    2. use cases ?
    3. best way to follow mvc with servlets and jsp for it?
    you can answer to this at the abstract level. no need to go in detail.
    if you have any documents like design and use cases mail me to [email protected]
    your cooperation is highly appreciated in this regards.

    Look into this kid
    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Session-Tracking.htm

  • Proxying servlets and JSPs with apache

    We have a couple of servlets within our application, the rest of it
    being JSPs.
    We are having a problems maintaining the session state across links from
    the JSPs to the servlets. It works fine with WL as the web server when
    the servlet picks up the same session as the JSPs, but when we are using
    the apache bridge, the servlet seems to have a new session.
    We are using WL5.1.0 SP6 on solaris.
    The JSPs are proxied by extension, and the servlets by location -
    everything under the servlet directory being directed to a servlet.
    Is there anything we need to do in the configuration to allow this to
    work?
    Thanks,
    Steve

    Core Servlets is pretty good. I have both parts.
    One day I'm actually going to read them.you mean these two right?
    Core Servlets and Javaserver Pages: Core Technologies, Vol. 2 (2nd Edition) (Core) by Marty Hall, Larry Brown, and Yaakov Chaikin
    Core Servlets and JavaServer Pages, Vol. 1: Core Technologies, Second Edition by Marty Hall and Larry Brown
    I should buy the Vol 1 first right?

  • General Design With Database and Session Bean Question

    I have an application I am developing where users connect to individual databases located on a server. When they login an admin table is accessed which shows what databases they have permissions to. I am then storing the connection to the database in a backing bean. Hoping to use this connection throughout the session. Is this a good practice to have a users connection left open over the session? I can't create a database pool for each individual database and each user for that database.
    If I can store that database connection in a session bean. How do I access that connection from another bean. Or from another java class? I am using Glassfish for my application server with JSF1.2. I have looked at resource injection but have not had any luck with sharing the session bean information.
    Sorry if this is a trivial question. I have been a Java developer for years. But just starting developing webapps using JSF.
    Thanks

    JuCobb2 wrote:
    I am then storing the connection to the database in a backing bean. Hoping to use this connection throughout the session. Is this a good practice to have a users connection left open over the session? No it is not. Why should you do so? Always keep the lifetime of connection, statement and resultset as short as possible.

  • How to work with request, response and sessions in JSC

    Hi
    I have two Servlets ServletA and ServletB. ServletA creates a session and add some attributes to this session. Then it forwards the request to ServletB where the attributes of this session are retrieved and used in response object.
    Here is what I am doing in ServletB
    - Get the session attrribute. This attribute is of type byte[]
    byte[] mydata = (byte[]) request.getSession.getAttribute(data);
    response.setContentLength(mydata.length);
    OutputStream stream = response.getOutputStream();
    stream.write(mydata,0,mydata.length);
    stream.close();
    My question is ...
    How do I achieve this in Creator. ?
    Thanks in advance
    Srinivas

    Hi
    I have two Servlets ServletA and ServletB. ServletA
    creates a session and add some attributes to this
    s session. Then it forwards the request to ServletB
    where the attributes of this session are retrieved
    and used in response object.
    Here is what I am doing in ServletB
    - Get the session attrribute. This attribute is of
    type byte[]
    byte[] mydata = (byte[])
    request.getSession.getAttribute(data);
    response.setContentLength(mydata.length);
    OutputStream stream = response.getOutputStream();
    stream.write(mydata,0,mydata.length);
    stream.close();
    My question is ...
    How do I achieve this in Creator. ?
    Thanks in advance
    SrinivasBy "this" do you mean "how do I access a session attribute that has been placed there by another servlet?"
    The base class for all page beans has a bunch of convenience methods available. The simplest one to use for this purpose is getBean(), which searches through request scope, session scope, and application scope for a bean with the name you specify -- and, if its a managed bean, will create it for you as well. So, your code would look like this:
      String data = ...; // Name of the attribute you want
      byte[] mydata = (byte[]) getBean(data);There is an additional quirk related to what you're actually trying to do, though ... it looks like you are trying to write out binary content (perhaps an image loaded from the database or something). It is not possible to mix binary and text output in a single response.
    Your best bet for this particular purpose, then, is to continue using ServletA and ServletB just as you have been. The applications created by Creator are standard servlet-based web applications, so you can use additional servlets and all the other goodies (although you'll have to declare them yourself in the web.xml file, as usual).
    Craig

  • ATM model with Servlet and Cookies(class assignent)

    i am struggling starting a class assignment. I am suppose to use and access database, a servlet and cookies. If i understand correctly the servlet will have the buttons and GUI? What would i use the cookies for? or how would i use cookies in such an application? Please help.
    ty,
    max

    A servlet will typically generate HTML content. The generated HTML will contain tags which will be rendered into buttons and the like. Cookies are used for persisting state about a particular web browser across several sessions. For example, if a user enters their name in your system you could set a cookie (which would be stored on the client's machine). Then, when they return to the site you can re-access the cookie which was originally set.
    Good luck,
    -Derek

  • Intermediate networks (Good practice or false sense of security)?

    I'm not really sure what you call them, but is it good practice to create an intermediate network between your private network and public side. For instance private 192.168.1.0/24 <---> intermediate 10.1.1.0/24 <---> Public. What benefits are there for doing this? What are some negatives? Please enlighten me.
    Thanks

    I'm sure there will be different opinions on this - here is mine.
    I don't see any benefit to the intermediate network. As you mentioned, it's quite common to use a "three legged" firewall with an inside, outside and DMZ interface.
    On the ASA for example, the interfaces are usually numbered with inside 100, DMZ 50, and outside 0. Traffic is always permitted from high to low but never low to high unless a) it's a response to a request from a higher number interface or b) it's explicitly permitted in on an ACL.
    One big benefit to doing this "three leg" approach is that you can put an ACL on the outside interface to only let traffic in to the DMZ subnet but not to the inside subnet - making the inside better protected from the outside world.
    In the event that the DMZ does become compromised, it can not initiate sessions into the inside network because it has a security level higher than the DMZ.
    Having the intermediate network could be, in a way, an alternative approach to the "three leg" solution though not as elegant or effective. The intermediate network could be a DMZ with public servers which is further firewalled from the inside network.

  • Send data from bean to servlet and get results back to bean

    Hi,
    I'm new to this helpful forum and, as long as I'm practicing with JFS and Java Beans and Servlets, I really need some help about the following crappy issue.
    I made a JSP login page called "LoginPage.jsp" (using "Visual Web JSF Page" tool in NetBeans 6.0), and the action associated to the "Login" button pression is defined in the associated Java Bean "LoginPage.java":
    Code from "LoginPage.jsp":
    <webuijsf:button actionExpression="#{LoginPage.loginButton_action}" binding="#{LoginPage.loginButton}" id="loginButton" primary="true" style="height: 24px; left: 383px; top: 192px; position: absolute; width: 96px" text="Login"/>
    Code from "LoginPage.java":
    public String loginButton_action()
        if (usernameField.equals("guest") && passwordField.equals("guest")) // this control should be done by a servlet, not here!
            return "loginOK"; // this is the outcome for faces-config.xml that will lead to a "Welcome.jsp" page
        else
            return "loginERROR"; // this is the outcome for faces-config.xml that will lead to a "Error.jsp" page
    ...Now, the problem is that the username and password control should not be done by the bean itself, but by a servlet (call it "LoginServlet.java").
    In a few words, what I mean is that once the user writes username and password and presses the "Login" button, the called "loginButton_action()" forwards all the needed data to the servlet "LoginServlet.java", the servlet does the complete checks about login validity then prepares the result (it could be a string reporting "OK" or whatever else) and send it back to the bean "LoginPage.java", so that the flow can continue.
    My problem is that I absolutely don't know how to make a bean and a servlet communicate in both ways and respectively exchange data.
    Thanks in advance for any help, it will really be appreciated.

    Google for passing values in request and session.

  • How ServletContext and Session object differ in a Serlet

    Both ServletContext and Session allows storing objects as a name value pair set and they can be accessed across several servlets/JSP's. How do they differ?

    Hi
    The Main difference is their visibility or rather the scope of the varibles differs depending on whether they are stored in the session or the Servlet Context.
    When you say that an Object is stored in the session then it means that the Object is available to the application for duration of the particulars user's session i.e. as long as the user's session is active the Object is available though not for others who will have a different session and so will not be able to access this information.
    Whereas, when you add the Object to Servlet Context you are setting up the object to be visible throughout the application for duration of the application itself and for any component that is art of the application
    So if we have a list of Object storage/sharing mechanisms listed in descending order of object life span/visibility then we have:
    Application - ServletContext
    Session - HttpSession
    Request - ServletRequest
    Page
    Keep me posted on your progress.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems
    http://www.sun.com/developers/support

  • Using database connection in a servlet and get errors after 8 hours

    Hey,
    I'm running a poker script using applet/servlets and it works great. But for some reason about about 8 hours that database layer stops working. At first I thought it was the connections to mySQL that were timing out (because im using connection pooling) but after turning pooling off (I now create the connection each time) I'm still seeing that same error (I can create a connection but when I do an action ex. like a select statment I get an error). What i'm wondering could it be that the driver I load with Class.forName() some how unloads it's self after x amount of time not being used? Not sure if that is it but if anyone could give me some insight that would be great. The Error i recieve is below:
    INFO: Database Event:DatabaseController: Error executing database query.
    ERROR: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.net.SocketException
    MESSAGE: Software caused connection abort: recv failed
    STACKTRACE:
    java.net.SocketException: Software caused connection abort: recv failed
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:104)
         at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
         at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:172)
         at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1839)
         at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2288)
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2784)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2370)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2297)
         at com.mysql.jdbc.Statement.executeQuery(Statement.java:1183)
         at com.softnet.database.DatabaseController.executeDatabaseQuery(DatabaseController.java:190)
         at com.softnet.games.GameServer.validateUser(GameServer.java:438)
         at com.softnet.games.GameServer.handleData(GameServer.java:113)
         at com.softnet.network.HttpConnectionThread.run(HttpServletListener.java:191)
    ** END NESTED EXCEPTION **
    I know the query is good because it works all other times just not after about 8 hours.
    --Z3r0CooL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hey,
    Thanks for the responces. For the connection pooling I would open 5 connections and keep them open. So i though maybe after 8 hours after not being used they would timeout. Thats why i turned off conection pooling and create a new connection each time. Anyways i'll post the code below incase i made a mistake somewhere.
    package com.softnet.database;
    /************************ DatabaseControler **************************/
    import java.sql.*;
    import java.util.*;
    import com.softnet.database.DatabaseConnectionPool;
    import com.softnet.database.DatabaseSettings;
    public class DatabaseController
    implements DatabaseListener
         //Used to make sure the database driver is loaded
         private boolean databaseDriverState = false;
         //Used to store a database connection
         private Connection databaseConnection = null;
         //If to user connection pooling or not
         private boolean useConnectionPooling = false;
         //Used to hold the connection pool varible
         private DatabaseConnectionPool connectionPool = null;
         //Used to store database settings
         private DatabaseSettings databaseSettings;
         //Used to hold the DatabaseController listeners
         private List databaseControllerListeners = new ArrayList();
         //min number of connections for connection pool
         private int minNumberOfConnections = 1;
         //max number of connections for connection pool -1 is unlimited
         private int maxNumberOfConnections = -1;
         //DatabaseController Constructors
         public DatabaseController(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
              databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
         public DatabaseController(DatabaseSettings databaseSettings, boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
              this.databaseSettings = databaseSettings;
              this.useConnectionPooling = useConnectionPooling;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              if(useConnectionPooling == true)
                   connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
                   connectionPool.addDatabaseListener(this);
              else
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
         public DatabaseController() {}
         //Database Settings Get/Set
         public DatabaseSettings getDatabaseSettings()
              return databaseSettings;
         public void setDatabaseSettings(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
         //Connection Pooling Get/Set
         public boolean getConnectionPooling()
              return useConnectionPooling;
         public void setConnectionPooling(boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
              this.useConnectionPooling = useConnectionPooling;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              if(useConnectionPooling == true)
                   if(connectionPool == null)
                        connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
                        connectionPool.addDatabaseListener(this);
              else
                   if(connectionPool != null)
                        connectionPool.destroyConnections();
                        connectionPool.removeDatabaseListener(this);
                        connectionPool = null;
         //Return if there connected
         public boolean isConnected()
              boolean isConnected;
              if(databaseConnection != null)
                   isConnected = true;
              else
                   isConnected = false;
              return isConnected;
         //Used to connect to database or get a connection for the connection pool
         public void connect()
              if(databaseDriverState == false)
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //If we dont have a current connection, make one
              if(databaseConnection == null && databaseDriverState == true)
                   if(useConnectionPooling == false)
                        try
                             databaseConnection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                        catch (SQLException sqle)
                             //Raise event
                             raiseDatabaseEvent("DatabaseController: Error connecting to database. \nERROR: " + sqle.getMessage());
                             databaseConnection = null;
                   else
                        databaseConnection = connectionPool.getConnection();
         //Used to disconnect from the database or give back the connection to the connection pool
         public void disconnect()
              if(databaseConnection != null)
                   if(useConnectionPooling == false)
                        try
                             //Close DB Connection
                             databaseConnection.close();
                        catch(SQLException ignore) {}
                        finally
                             databaseConnection = null;
                   else
                        connectionPool.returnConnection(databaseConnection);
                        databaseConnection = null;
         public ResultSet executeDatabaseQuery(String sSQL)
              ResultSet databaseResult = null;
              if(databaseConnection != null)
                   try
                        Statement databaseStatement = databaseConnection.createStatement();
                        databaseResult = databaseStatement.executeQuery(sSQL);
                   catch(SQLException sqle)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error executing database query.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
              return databaseResult;
         public int executeDatabaseUpdate(String sSQL)
              int rowsAffected = -1;
              if(databaseConnection != null)
                   try
                        Statement databaseStatement = databaseConnection.createStatement();
                        rowsAffected = databaseStatement.executeUpdate(sSQL);
                   catch(SQLException sqle)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error executing database update.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
              return rowsAffected;
         //Used to load the Database Driver
         private boolean loadDatabaseDriver(String databaseDriver)
              boolean driverLoaded;
              if(databaseDriver.equals("") == false)
                   try
                        //Load Database Driver
                        Class.forName(databaseDriver).newInstance();
                        driverLoaded = true;
                   catch (Exception e)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + e.getMessage());
                        driverLoaded = false;
              else
                   driverLoaded = false;
              return driverLoaded;
         //Wrap the DatabaseConnectionPool Error to the DatabaseController
         public void databaseEventOccurred(DatabaseEvent de)
              raiseDatabaseEvent(de.getErrorMessage());
         //Event Handling Code
         //Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
    public synchronized void addDatabaseListener(DatabaseListener databaseControllerListener)
    databaseControllerListeners.add(databaseControllerListener);
    //Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
    public synchronized void removeDatabaseListener(DatabaseListener databaseControllerListener)
    databaseControllerListeners.remove(databaseControllerListener);
    //Used to send the raise event to the listeners
    private synchronized void raiseDatabaseEvent(String databaseError)
    DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
    Iterator listeners = databaseControllerListeners.iterator();
    while(listeners.hasNext())
         DatabaseListener listener = (DatabaseListener) listeners.next();
    listener.databaseEventOccurred(databaseEvent);
    /********************* DatabaseConnectionPool **************/
    package com.softnet.database;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import com.softnet.database.*;
    import com.softnet.database.DatabaseSettings;
    public class DatabaseConnectionPool
         //min number of connections
         private int minNumberOfConnections = 1;
         //max number of connections -1 is unlimited
         private int maxNumberOfConnections = -1;
         //Store the connections
         protected Hashtable databaseConnections = null;
         //Database Info
         protected DatabaseSettings databaseSettings;
         //to hold Driver state
         private boolean databaseDriverState = false;
         //To hold connection checker
         private DatabaseConnectionCheck connectionChecker = null;
         //Used to hold the DatabaseConnectionPool listeners
         private List databaseConnectionPoolListeners = new ArrayList();
         public DatabaseConnectionPool(DatabaseSettings databaseSettings, int minNumberOfConnections, int maxNumberOfConnections)
              this.databaseSettings = databaseSettings;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              //Load Driver
              databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //Create connection
              createConnections();
         public DatabaseConnectionPool(int minNumberOfConnections, int maxNumberOfConnections)
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
         //Database Settings Get/Set
         public DatabaseSettings getDatabaseSettings()
              return databaseSettings;
         public void setDatabaseSettings(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
         //Driver State Get
         public boolean getDatabaseDriverState()
              return databaseDriverState;
         public void createConnections()
              if(databaseDriverState == false)
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //Create all connections and load the minimum in the Hashtable
              if(databaseConnections == null)
                   if(databaseDriverState == true && minNumberOfConnections != 0)
                        databaseConnections = new Hashtable();
                        for(int i = 0; i < minNumberOfConnections; i++)
                             try
                                  databaseConnections.put(DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword()), Boolean.FALSE);
                             catch(SQLException sqle)
                                  //Problem break loop and destroy any connections
                                  destroyConnections();
                                  //Raise event
                                  raiseDatabaseEvent("DatabaseConnectionPool: Error creating database connections. \nERROR: " + sqle.getMessage());
                                  break;
              //If no connection check exists create one
              if(connectionChecker == null)
                   connectionChecker = new DatabaseConnectionCheck(this);
                   connectionChecker.start();
         public Connection getConnection()
              Connection connection = null;
              boolean errorWithConnection = false;
              Enumeration connections = databaseConnections.keys();
              synchronized (databaseConnections)
                   while(connections.hasMoreElements())
                        errorWithConnection = false;
                        connection = (Connection) connections.nextElement();
                        Boolean state = (Boolean) databaseConnections.get(connection);
                        //If connection is not used, use it.
                        if(state == Boolean.FALSE)
                             try
                                  connection.setAutoCommit(true);
                             catch(SQLException e)
                                  //Problem with connection remove connection and replace it
                                  databaseConnections.remove(connection);
                                  try
                                       connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                                  catch(SQLException sqle)
                                       errorWithConnection = true;
                             if(errorWithConnection == false)
                                  // Update the Hashtable to show this one's taken
                                  databaseConnections.put(connection, Boolean.TRUE);
                                  // Return the connection
                                  return connection;
                   //All connections being used check to max to see if we can make a new one
                   if(maxNumberOfConnections == -1 || maxNumberOfConnections > databaseConnections.size())
                        try
                             connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                        catch(SQLException sqle)
                             errorWithConnection = true;
                        if(errorWithConnection == false)
                             databaseConnections.put(connection, Boolean.TRUE);
                             return connection;
              //If not connections free and max connections reached wait for a free connection
              return getConnection();
         public void returnConnection(Connection connection)
              boolean errorWithConnection = false;
              //Make sure connection still works
              try
                   connection.setAutoCommit(true);
              catch(SQLException e)
                   //Problem with connection remove connection and replace it
                   databaseConnections.remove(connection);
                   try
                        connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                   catch(SQLException sqle)
                        errorWithConnection = true;     
              if(errorWithConnection == false)
                   databaseConnections.put(connection, Boolean.FALSE);
         public void destroyConnections()
              Connection connection = null;
              if(databaseConnections != null)
                   //Close all connections
                   Enumeration connections = databaseConnections.keys();
                   while (connections.hasMoreElements())
                        connection = (Connection) connections.nextElement();
                        try
                             connection.close();
                        catch(SQLException ignore) {}
                   //Free up hashtable
                   databaseConnections = null;
         private boolean loadDatabaseDriver(String databaseDriver)
              boolean driverLoaded;
              if(databaseDriver.equals("") == false)
                   try
                        //Load Database Driver
                        Class.forName(databaseDriver);
                        driverLoaded = true;
                   catch (ClassNotFoundException cnfe)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + cnfe.getMessage());
                        driverLoaded = false;
              else
                   driverLoaded = false;
              return driverLoaded;
         //Event Handling Code
         //Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
    public synchronized void addDatabaseListener(DatabaseListener databaseConnectionPoolListener)
    databaseConnectionPoolListeners.add(databaseConnectionPoolListener);
    //Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
    public synchronized void removeDatabaseListener(DatabaseListener databaseConnectionPoolListener)
    databaseConnectionPoolListeners.remove(databaseConnectionPoolListener);
    //Used to send the raise event to the listeners
    private synchronized void raiseDatabaseEvent(String databaseError)
    DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
    Iterator listeners = databaseConnectionPoolListeners.iterator();
    while(listeners.hasNext())
         DatabaseListener listener = (DatabaseListener) listeners.next();
    listener.databaseEventOccurred(databaseEvent);
    class DatabaseConnectionCheck extends Thread
         private DatabaseConnectionPool connectionPool;
         DatabaseConnectionCheck(DatabaseConnectionPool connectionPool)
              this.connectionPool = connectionPool;
         public void run()
              try
                   while(true)
                        //check threads every 30 seconds
                        this.sleep(300000);
                        if(connectionPool.databaseConnections != null)
                             Connection connection = null;
                             Enumeration connections = connectionPool.databaseConnections.keys();
                             synchronized (connectionPool.databaseConnections)
                                  while(connections.hasMoreElements())
                                       connection = (Connection) connections.nextElement();
                                       Boolean state = (Boolean) connectionPool.databaseConnections.get(connection);
                                       //If connection is not used, use it.
                                       if(state == Boolean.FALSE)
                                            try
                                                 connection.setAutoCommit(true);
                                            catch(SQLException e)
                                                 //Problem with connection remove connection and replace it
                                                 connectionPool.databaseConnections.remove(connection);
                                                 try
                                                      connection = DriverManager.getConnection(connectionPool.databaseSettings.getDatabaseURL(), connectionPool.databaseSettings.getUserName(), connectionPool.databaseSettings.getUserPassword());
                                                 catch(SQLException sqle)
                                                      connection = null;
                                                 // Update the Hashtable with new connection if its not null
                                                 if(connection != null)
                                                      connectionPool.databaseConnections.put(connection, Boolean.FALSE);
              catch(InterruptedException ignored) {}     
    Basicly the why it works is the connection pool hold the database connections. When the user needs a connection they use the database controller to request a connection (By create a instance and called the connect() method) and the connection is either created or grabed from the connection pool. After the user is done with the connection they call the disconnect() method which closes the connection or returns it to the connection pool.
    --Z3r0CooL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 

Maybe you are looking for

  • Call RFC (Abap) with Javascript

    Hi all, i'm new to Javascript. Now i have to write a small piece of code in Javascript that calls an Abap RFC. Does anyone have an example for something like that ? Greetings Henning

  • Flv dinamic in asp page

    Good Morning, I have a question: How i can to insert a dynamic flv in a asp page..(path is insert in a column of database)? When i try whit "insert flash video function>insert from dati source", an error occour: url can't insert because ther is not v

  • Marked edit point at 1 frame off from playhead

    The drugs wore off many years ago so I can't blame that. I move the playhead to a spot I want as an edit out point, in the timeline or viewer, mark the point and then notice the actual outpoint is 1 frame past the playhead thus making the duration 1

  • Second password¿?¿?

    Hi! I'm becoming CRAZY! I connected my BB to the computer to install the Desktop Manager and since that moment it asks me to enter a second password. When I set it up, I introduced the same code twice (pin and password) in order to not to forget them

  • How do I sync all my contacts on my iPhone to iCloud?

    When I sync my iPhone to iCloud not all my contacts on my phone are uploaded, where are the rest of my contacts and why won't they upload.  Also my contacts won't sync to my Outlook anymore when I sync my phone.  The list on Outlook matches the one f