Java web hosting - JavaSercer Pages finally { try { if (isPartOfTransaction

January 27, 2007 on 10:17 pm | In Java |

JavaSercer Pages finally { try { if (isPartOfTransaction && isExceptionThrown) { // Reset auto commit in case the connection is // pooled before it’s returned to the pool by close conn.setAutoCommit(true); conn.close( ); } else if (!isPartOfTransaction) { // If we’re not part of a transaction, the // connection is in auto commit mode so we only // close it conn.close( ); } } catch (SQLException e) { e.printStackTrace(System.err); } } // Save the result with the specified id in the specified scope if (id != null) { pageContext.setAttribute(id, result, scope); } return EVAL_PAGE; } The interesting code is in the catch and finally clauses of the try block. If the execution of the SQL statement causes an exception to be thrown, the transaction is rolled back and a JspException is thrown. This aborts the processing of the rest of the page and informs the user about the error. A boolean flag is also set to be able to handle this case in the finally clause. The finally clause is executed whether or not an exception is thrown. If this action is part of a transaction and an exception is thrown by the execute( ) method, the Connection is returned to the pool by calling the close( ) method after auto commit is turned on again to reset it to its default state. If the action is not part of a transaction, there’s no need to reset the auto commit since it has never been changed; the Connection is just returned to the pool by calling the close( ) method. If the action is part of a transaction and no exception is thrown, the result is saved in the specified scope, and processing continues with the next nested database action. Note that the Connection is not closed in this case, as the same Connection must be used for all SQL statements in the transaction. If all actions execute successfully, the TransactionTag ’s doEndTag( ), shown in Example 17.26, is invoked. Example 17.26. The TransactionTag’s doEndTag( ) Method public int doEndTag( ) throws JspException { try { conn.commit( ); conn.setAutoCommit(true); conn.close( ); } catch (SQLException e) { throw new JspException(”SQL error: ” + e.getMessage( )); } return EVAL_PAGE; } The doEndTag( ) method commits the transaction, resets the auto commit for the Connection, and returns the Connection to the pool by calling the close( ) method. page 256
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

No Comments yet

TrackBack URI

Sorry, the comment form is closed at this time.