All sites hosted in the Aptana Cloud are bundled with MySQL. When you create a Java hosted site, two MySQL databases are also created automatically.
- <site_name>_public - To be used for the publicly-available (production) Java Web application.
- <site_name>_staging - To be used for the staging (test) Java Web application.
Contents |
JNDI Resources for the MySQL Databases
JNDI resources named jdbc/mysql are automatically created for both the public and staging sites. In the Java Web application, both databases can be referenced via this JNDI name. When the same web application is deployed in the public or staging site the correct database will be accessed by the application. For security purposes, a specific username and password for the datasource is set automatically so that it is only accessible within the site.
Adding the JNDI reference to your Web application
In order to access the MySQL database from your application, a resource reference must be added to the web.xml of your Web application. Edit the WEB-INF/web.xml file in your Web application and add the following lines:
<resource-ref> <res-ref-name>jdbc/mysql</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref>
Accessing the database from your application
Now your Java Web application is ready to access the database via the JNDI datasource name jdbc/mysql. For example, to access your database in a JSP file, you'd write the following:
<sql:query var="result" dataSource="jdbc/mysql">
SELECT * FROM Test
</sql:query>
<table border="1">
<tr>
<c:forEach var="columnName" items="${result.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<c:forEach var="row" items="${result.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td>
<c:out value="${column}"/>
</td>
</c:forEach>
</tr>
</c:forEach>
</table>
Note: The above example uses JSTL, so the appropriate JSTL header should be added to the JSP and the JSTL library must be added to WEB-INF/lib.
Sample project
To use this project you should create a Table called "Test" to the public or staging database in your Site MySQL.
