Archive for January, 2007

JavaSercer Pages Appendix A. JSP Elements (System web hosting) Syntax Reference

Monday, January 29th, 2007

JavaSercer Pages Appendix A. JSP Elements Syntax Reference JSP defines three types of elements: directives, scripting elements, and action elements. In addition, you can define your own custom actions. This appendix contains descriptions of all JSP elements as well as the general syntax rules for custom actions. A.1 Directive Elements Directive elements are used to specify information about the page itself, especially information that doesn’t differ between requests for the page. The general directive syntax is: <%@ directiveName attr1="value1" attr2="value2" %> The attribute values can be enclosed with single quotes instead of double quotes. The directive name and all attribute names are case-sensitive. A.1.1 include Directive The include directive includes a static file, merging its content with the including page before the combined result is converted to a JSP page implementation class. The include directive supports the attribute described in Table A.1. Table A.1, include Directive Attribute Attribute Name Default Description file No default A page-relative or context-relative URI path for the file to include A page can contain multiple include directives. The including page and all included pages together form what is called a JSP translation unit. Example: <%@ include file="header.html" %> A.1.2 page Directive The page directive defines page-dependent attributes, such as scripting language, error page, and buffering requirements. It supports the attributes described in Table A.2. Table A.2, page Directive Attributes Attribute Name Default Description autoFlush true Set to true if the page buffer should be flushed automatically when it’s full, or to false if an exception should be thrown when it’s full. buffer 8kb Specifies the buffer size for the page. The value must be expressed as the size in kilobytes followed by kb, or be the keyword none to disable buffering. contentType text/html The MIME type for the response generated by the page, and optionally the charset for the source page as well as the response; e.g., text/html;charset=Shift_JIS. errorPage No default A page-relative or context-relative URI path for the JSP page to forward to if an exception is thrown by code in the page. extends No default The fully qualified name of a Java class that the generated JSP page implementation class extends. The class must implement the JspPage or HttpJspPage interface in the javax.servlet.jsp package. Note that the recommendation is to not use this attribute. Specifying your own superclass restricts the JSP container’s ability to provide a specialized, high-performance superclass. page 260
Hint: If you are looking for good and high quality web space to host and run your java application check Vision java web hosting services


JavaSercer Pages In the doEndTag( ) method, all (Postgres hosting)

Sunday, January 28th, 2007

JavaSercer Pages In the doEndTag( ) method, all request parameters with information about the employee are first retrieved. If a parameter is missing, an exception is thrown. Then an SQLCommandBean instance is created, the DataSource object fetched from the application scope, and a Connection created and provided to the bean. The bean is used to execute a SELECT statement to find out if the specified employee is already defined in the database. If not, the bean is used to execute an INSERT statement with all the information provided through the request parameters. Otherwise, the bean is used to execute an UPDATE statement. The tag handler class described here is intended only to show how you can use the database access classes to implement your own custom actions. The tag handler class could be improved in several ways. For instance, it could provide default values for missing parameters, such as the current date for a missing employment date, or an email address based on the employee’s first and last names if the email address is missing. You could also use a bean as input to the action instead of reading request parameters directly. This would allow the bean to be used as described in Chapter 6, and Chapter 8, to capture and validate the user input until all information is valid, and then pass it on to the custom action for permanent storage of the information in a database. page 259
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

JavaSercer Pages Vector values = new Vector( );

Sunday, January 28th, 2007

JavaSercer Pages Vector values = new Vector( ); values.addElement(new StringValue(userName)); sqlCommandBean.setSqlValue(sqlValue); sqlCommandBean.setValues(values); Vector rows = sqlCommandBean.executeQuery( ); // Create values for insert/update values.removeAllElements( ); values.addElement(new StringValue(password)); values.addElement(new StringValue(firstName)); values.addElement(new StringValue(lastName)); values.addElement(new StringValue(dept)); values.addElement(new DateValue( new Date(StringFormat.toDate(empDate, “yyyy-MM-dd”).getTime( )))); values.addElement(new StringValue(emailAddr)); values.addElement(new TimestampValue( new Timestamp(System.currentTimeMillis( )))); values.addElement(new StringValue(userName)); if (rows.size( ) == 0) { // New user. Insert StringBuffer sb = new StringBuffer( ); sb.append(”INSERT INTO Employee “). append(”(Password, FirstName, LastName, Dept, “). append(”EmpDate, EmailAddr, ModDate, UserName) “). append(”VALUES(?, ?, ?, ?, ?, ?, ?, ?)”); sqlCommandBean.setSqlValue(sb.toString( )); } else { // Existing user. Update StringBuffer sb = new StringBuffer( ); sb.append(”UPDATE Employee “). append(”SET Password = ?, FirstName = ?, “). append(”LastName = ?, Dept = ?, EmpDate = ?, “). append(”EmailAddr = ?, ModDate = ? “). append(”WHERE UserName = ?”); sqlCommandBean.setSqlValue(sb.toString( )); } sqlCommandBean.executeUpdate( ); } catch (SQLException e) { throw new JspException(”SQL error: ” + e.getMessage( )); } catch (UnsupportedTypeException e) { throw new JspException(”Query result error: ” + e.getMessage( )); } catch (ParseException e) { throw new JspException(”Invalid empDate format: ” + e.getMessage( )); } finally { try { if (conn != null) { conn.close( ); } } catch (SQLException e) { // Ignore } } return EVAL_PAGE; } public void release( ) { dataSourceName = null; super.release( ); } } This tag handler has one property, named dataSource. It’s marked as required in the TLD for the tag, so it will always be set: … saveEmployeeInfo com.mycompany.tags.SaveEmployeeInfoTag empty dataSource true … page 258
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services

JavaSercer Pages 17.4 Developing Application-Specific Database Components The (Top web hosting companies)

Sunday, January 28th, 2007

JavaSercer Pages 17.4 Developing Application-Specific Database Components The classes described in this chapter can also be used for application-specific components that access a database. Chapter 15 includes one example of an application-specific bean, the EmployeeRegisterBean, that uses the SQLCommandBean to execute its SQL statements. You can also use these classes in your application-specific custom actions. One example is the custom action that’s mentioned in Chapter 9 as an alternative to the generic database actions for inserting or updating employee information: <%@ page language="java" contentType="text/html" %> <%@ taglib uri="/orataglib" prefix="ora" %> <%@ taglib uri="/mytaglib" prefix="myLib" %> <%-- Get the new or updated data from the database --%> SELECT * FROM Employee WHERE UserName = ? <%-- Redirect to the confirmation page --%> Example 17.27 shows one way to implement this custom action. Example 17.27. SaveEmployeeInfoTag Class package com.mycompany.tags; import java.sql.*; import java.text.*; import java.util.Vector; import javax.sql.*; import javax.servlet.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.ora.jsp.sql.*; import com.ora.jsp.sql.value.*; import com.ora.jsp.util.*; public class SaveEmployeeInfoTag extends TagSupport { private String dataSourceName; public void setDataSource(String dataSourceName) { this.dataSourceName = dataSourceName; } public int doEndTag( ) throws JspException { // Get all request parameters ServletRequest request = pageContext.getRequest( ); String userName = request.getParameter(”userName”); String password = request.getParameter(”password”); String firstName = request.getParameter(”firstName”); String lastName = request.getParameter(”lastName”); String dept = request.getParameter(”dept”); String empDate = request.getParameter(”empDate”); String emailAddr = request.getParameter(”emailAddr”); if (userName == null || password == null || firstName == null || lastName == null || dept == null || empDate == null || emailAddr == null) { throw new JspException(”Missing a mandatory parameter”); } SQLCommandBean sqlCommandBean = new SQLCommandBean( ); DataSource dataSource = (DataSource) pageContext.getAttribute(dataSourceName, PageContext.APPLICATION_SCOPE); if (dataSource == null) { throw new JspException(”The data source ” + dataSource + ” is not found in the application scope”); } Connection conn = null; try { conn = dataSource.getConnection( ); sqlCommandBean.setConnection(conn); // See if the user exists String sqlValue = “SELECT * FROM Employee WHERE UserName = ?”; page 257

Hint: This post is supported by Gama web hosting php mysql provider

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

Saturday, January 27th, 2007

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


Ssh hosting - JavaSercer Pages The package scope getConnection( ) method,

Saturday, January 27th, 2007

JavaSercer Pages The package scope getConnection( ) method, also shown in Example 17.23, is used by the tag handlers for the and actions. To see how it’s used, let’s look at the method with the same name in the DBTag class that we skipped earlier. The DBTag ’s getConnection( ) method is shown in Example 17.24. Example 17.24. The DBTag’s getConnection( ) Method private Connection getConnection( ) throws JspException { Connection conn = null; TransactionTag transactionTag = (TransactionTag) findAncestorWithClass(this, TransactionTag.class); if (transactionTag != null) { conn = transactionTag.getConnection( ); isPartOfTransaction = true; if (dataSourceName != null) { throw new JspException(”A dataSource must not be ” + “specified when the action is part of a ” + “transaction”); } } else { DataSource dataSource = (DataSource) pageContext.getAttribute(dataSourceName, PageContext.APPLICATION_SCOPE); if (dataSource == null) { throw new JspException(”dataSource ” + dataSourceName + ” not found”); } try { conn = dataSource.getConnection( ); } catch (SQLException e) { throw new JspException(”SQL error: ” + e.getMessage( )); } } return conn; } The findAncestorWithClass( ) is used to find out whether or not the action is nested in the body of an tag. If a TransactionTag is found, the action is part of a transaction, so the TransactionTag’s get-Connection( ) is used to retrieve the shared Connection, and a boolean flag is set to remember that the action is part of a transaction. If a parent tag handler is not found, the action is not part of a transaction. In this case, the DBTag’s dataSource property value is used instead to locate the DataSource in the application scope and get a Connection. The doEndTag( ) method in the DBTag class contains some details related to database transactions that we also skipped earlier. Let’s revisit this method, shown in Example 17.25. Example 17.25. The DBTag’s doEndTag( ) Method public int doEndTag( ) throws JspException { Connection conn = getConnection( ); sqlCommandBean.setConnection(conn); sqlCommandBean.setSqlValue(sqlValue); sqlCommandBean.setValues(values); Object result = null; try { result = execute(sqlCommandBean); } catch (SQLException e) { try { isExceptionThrown = true; conn.rollback( ); } catch (SQLException se) { // Ignore, probably a result of the main exception } throw new JspException(”SQL error: ” + e.getMessage( )); } catch (UnsupportedTypeException e) { try { isExceptionThrown = true; conn.rollback( ); } catch (SQLException se) { // Ignore, probably caused by the main exception } throw new JspException(”Query result error: ” + e.getMessage( )); } page 255
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

Web hosting packages - JavaSercer Pages 17.3.3 The Action The final database

Saturday, January 27th, 2007

JavaSercer Pages 17.3.3 The Action The final database action in the example tag library is the action. A database transaction consists of the execution of a number of SQL statements on the same Connection; they either all succeed or all fail. As you may recall, the data changes resulting from executing all statements are then either permanently saved by committing the transaction, or ignored by rolling back the transaction. The task for the action is to provide a Connection to all database actions enclosed in its body, and commit the transaction when they have all been executed. The nested database actions must cooperate with the action tag handler by retrieving the shared Connection and rolling back the transaction if they fail. Let’s look at how the Connection is handled first. Example 17.22 shows the TransactionTag class declaration, the dataSource property setter method, and the doStartTag( ) method. Example 17.22. Part of the TransactionTag Class package com.ora.jsp.tags.sql; import java.io.*; import java.util.*; import java.sql.*; import javax.sql.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class TransactionTag extends TagSupport { private String dataSourceName; private Connection conn; public void setDataSource(String dataSourceName) { this.dataSourceName = dataSourceName; } public int doStartTag( ) throws JspException { conn = getTransactionConnection( ); return EVAL_BODY_INCLUDE; } The TransactionTag class extends the TagSupport class. It doesn’t need to access its body content; it only needs to tell the JSP container to execute all actions and possible scripting elements in the body, so the TagSupport class is the proper choice. The dataSource property corresponds to the attribute with the same name. The page author sets it to the name of the DataSource object in the application scope to use for all nested database actions. The doStartTag( ) method, invoked by the container before the actions in the body are processed, sets the conn instance variable by calling the get-TransactionConnection( ) method, shown in Example 17.23. Example 17.23. The TransactionTag’s getTransactionConnection( ) and getConnection( ) Methods private Connection getTransactionConnection( ) throws JspException { DataSource dataSource = (DataSource) pageContext.getAttribute(dataSourceName, PageContext.APPLICATION_SCOPE); if (dataSource == null) { throw new JspException(”dataSource ” + dataSourceName + ” not found”); } try { conn = dataSource.getConnection( ); conn.setAutoCommit(false); } catch (SQLException e) { throw new JspException(”SQL error: ” + e.getMessage( )); } return conn; } Connection getConnection( ) { return conn; } This method retrieves the DataSource object from the application scope and gets a Connection. A Connection automatically commits each SQL statement by default. In order to use the Connection to execute more than one statement within the same transaction, the setAutoCommit( ) method is called with the value false. page 254

Hint: This post is supported by Gama php5 hosting services

JavaSercer Pages 17.3.2 The Action A set of (Cms hosting)

Saturday, January 27th, 2007

JavaSercer Pages 17.3.2 The Action A set of value actions can be used inside the body of an or action to set the values for placeholders in the SQL statement. The example tag library contains value actions for date/time values as well as for numeric and string values. The tag handlers for all these actions have a great deal in common, so they all extend a common superclass called com.ora.jsp.tags.sql.value.ValueTag . This superclass contains instance variables and property setter methods for the attributes shared by all value actions: stringValue, pattern, param, name, and property. In addition, it contains methods used by the subclasses to get the value when it’s specified as a parameter name or a bean name plus a property name. Let’s look at the tag handler class for the action as an example. All other value actions follow the same pattern. The com.ora.jsp.tags.sql.IntValueTag class extends the ValueTag class as shown in Example 17.21. Example 17.21. The IntValueTag Class package com.ora.jsp.tags.sql.value; import java.lang.reflect.*; import java.text.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import com.ora.jsp.sql.value.*; import com.ora.jsp.tags.sql.ValueTagParent; import com.ora.jsp.util.*; public class IntValueTag extends ValueTag { private int value; public void setValue(int value) { this.value = value; } public int doEndTag( ) throws JspException { if (stringValue != null) { value = toInt(stringValue, pattern); } else if (param != null) { String paramValue = getParameter(param); value = toInt(paramValue, pattern); } else if (name != null) { value = getInt(name, property, pattern); } ValueTagParent parent = (ValueTagParent) findAncestorWithClass(this, ValueTagParent.class); if (parent == null) { throw new JspException(”The sqlIntValue action is not ” + “enclosed by a supported action type”); } parent.addValue(new IntValue(value)); return EVAL_PAGE; } … } The Java datatype is different for each value action, so all subclasses implement their own value property setter methods to store the value in an instance variable. The value property for the IntValueTag is of course an int. Besides the value attribute, all value actions support three other ways to set the value: as a String value specified by the stringValue attribute, as a request parameter specified by the param attribute, or as a bean property specified by the name and property attributes. The ValueTag superclass contains the setter methods and instance variables for these attributes, and the ValueTagExtraInfo class makes sure that a page author uses only one of these alternatives to specify the value. The doEndTag( ) method finds out which alternative is used by looking at all property instance variables in turn. If it’s a String value, defined by the stringValue or param attributes, the method converts the value to an int using a private toInt( ) method. If it’s specified as a bean property, another private method, getInt( ) , is used to invoke the bean to get the value. These private methods are not shown here, but you can look at the source code if you want to see how they work. The enclosing or action’s tag handler is then located, as described in Chapter 16, using the findAncestorWithClass( ) method. The tag handlers for the enclosing actions implement the ValueTagParent interface used as the parent class argument. If an enclosing action is found, its addValue( ) method is called to add the int value wrapped in an IntValue object to the parent’s value list. page 253

Hint: This post is supported by Gama php5 hosting services

JavaSercer Pages Example 17.18. The QueryTag’s execute( ) (Christian web host)

Friday, January 26th, 2007

JavaSercer Pages Example 17.18. The QueryTag’s execute( ) Method public Object execute(SQLCommandBean sqlCommandBean) throws SQLException, UnsupportedTypeException { return sqlCommandBean.executeQuery( ); } This method simply calls the bean’s executeQuery( ) method. The UpdateTag tag handler uses the bean’s executeUpdate( ) method instead, and wraps the returned int in an Integer object, as shown in Example 17.19. Example 17.19. The UpdateTag’s execute( ) Method public Object execute(SQLCommandBean sqlCommandBean) throws SQLException, UnsupportedTypeException { return new Integer(sqlCommandBean.executeUpdate( )); } The reason for wrapping the int in an Integer is that only real objects can be saved as JSP scope objects; primitive types are not supported. The and the actions define separate TagExtraInfo classes, named QueryTagExtraInfo and UpdateTagExtraInfo, respectively. They both extend a class called com.ora.jsp.tags.sql.DBTagExtraInfo. The isValid( ) method for the DBTagExtraInfo class makes sure a valid value is specified for the scope attribute. It’s shown in Example 17.20. Example 17.20. The DBTagExtraInfo Class package com.ora.jsp.tags.sql; import javax.servlet.jsp.tagext.*; public class DBTagExtraInfo extends TagExtraInfo { /** * Returns true only if a valid scope value is specified: * page, request, session or application. */ public boolean isValid(TagData data) { boolean isValid = false; String scope = data.getAttributeString(”scope”); if (scope == null || scope.equals(”page”) || scope.equals(”request”) || scope.equals(”session”) || scope.equals(”application”)) { isValid = true; } return isValid; } } The QueryTagExtraInfo and UpdateTagExtraInfo classes implement the getVariableInfo( ) method to tell the container about the result variables they create. Here’s the UpdateTagExtraInfo class: package com.ora.jsp.tags.sql; import javax.servlet.jsp.tagext.*; public class UpdateTagExtraInfo extends DBTagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { if (data.getAttributeString(”id”) == null) { return new VariableInfo[0]; } else { return new VariableInfo[] { new VariableInfo(data.getAttributeString(”id”), “java.lang.Integer”, true, VariableInfo.AT_END) }; } } } The QueryTagExtraInfo class is almost identical. The only difference is that it sets the class name to com.ora.jsp.sql.Row instead of java.lang.Integer. page 252
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services

Jboss hosting - JavaSercer Pages Example 17.15. The DBTag’s doAfterBody( )

Friday, January 26th, 2007

JavaSercer Pages Example 17.15. The DBTag’s doAfterBody( ) Method public int doAfterBody( ) throws JspException { sqlValue = bodyContent.getString( ); return SKIP_BODY; } The SQL statement may contain question marks as placeholders for values set by nested value actions. As you will see later, the value actions create the appropriate Value subclass and call the DBTag ’s addValue( ) method, shown in Example 17.16. Example 17.16. The DBTag’s addValue( ) Method public void addValue(Value value) { if (values == null) { values = new Vector( ); } values.addElement(value); } This method creates a Vector to hold all values the first time it’s called, and then adds the Value object to the Vector. When called by subsequent value action tag handlers, the Value objects are simply added to the list. The real processing happens in the doEndTag( ) method, shown in Example 17.17. This method is called by the container when the action element’s body has been processed and the end tag is encountered. Example 17.17. The DBTag’s doEndTag( ) Method public int doEndTag( ) throws JspException { Connection conn = getConnection( ); sqlCommandBean.setConnection(conn); sqlCommandBean.setSqlValue(sqlValue); sqlCommandBean.setValues(values); Object result = null; try { result = execute(sqlCommandBean); } catch (SQLException e) { … } catch (UnsupportedTypeException e) { … } finally { … } // Save the result with the specified id in the specified scope if (id != null) { pageContext.setAttribute(id, result, scope); } return EVAL_PAGE; } The private getConnection( ) method is used to get a Connection. The Connection is retrieved either from the DataSource specified by the dataSource attribute value for the or the action itself, or from an enclosing element. We’ll return to getConnection( ) and the exception handling code later when we look at transaction support. The Connection, the SQL statement, and all values (if any) are passed to the bean. Then, the abstract execute( ) method is called to ask the bean to execute the SQL statement. The Object returned by execute( ) is saved in the scope specified by the scope attribute, using the name specified by the id attribute. The implementation of the execute( ) method is the only thing that differs between the tag handlers for the action and the action. The corresponding tag handler classes, QueryTag and UpdateTag, extend the DBTag class and implement the execute( ) method. Example 17.18 shows the implementation in the QueryTag tag handler. page 251

Hint: This post is supported by Gama web hosting php mysql provider