JDBC 4.0 and Oracle JDeveloper for J2EE Development
上QQ阅读APP看书,第一时间看更新

Connecting to a Database from a Web Application

If a Java application is used to connect to a database, a JDBC connection may be obtained using the getConnection() method of the DriverManager class. If a JDBC connection is to be obtained in a web application, a data source with a JNDI naming service binding must be configured in an application server, such as the OC4J embedded in JDeveloper IDE. The data source object configured in data-sources.xml may be used in a Servlet or JSP in JDeveloper. In this section, we will connect to MySQL database using the managed data source we configured in the previous section. First, we need to create a project in JDeveloper with File | New. In the New Gallery window, select General | Applications in Categories and Application in Items and click on OK. Specify the Application Name in the Create Application window and click on the OK button. Specify the Project Name in the Create Project window and click on the OK button. A new project is added to the Applications Navigator.

Connecting to a Database from a Web Application

In the Applications Navigator window right-click on the Project node and select New. In the New Gallery window, select Web Tier | JSP in Categories, and JSP in Items, and click on OK.

Connecting to a Database from a Web Application

The Create JSP Wizard gets started. In the Web Application window, select J2EE 1.4 as the J2EE version and click on Next. In the JSP File window, specify a File Name and click on Next.

Connecting to a Database from a Web Application

Select the default settings in the Error Page Options window, if an error page is not to be used to handle unhandled exceptions. If an error page is to be used to handle unhandled exceptions, select Use an Error Page and click on the Next button. Select the Default Settings in the Tag Libraries window as we will not be using any tag libraries in this chapter, and click on Next. Select the Default Settings in the HTML Options window, with the the HTML Version being 4.0.1 Transitional, and click on Next.

On clicking finish in the Finish window, a JSP gets added to the project. To the web.xml file, add a resource-ref element in the Managed Data Source.

Connecting to a Database from a Web Application

The res-ref-name specifies the JNDI name of the Managed Data Source. The resource-ref element is listed below:

<resource-ref>
<res-ref-name>jdbc/MySQLConnectionDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

We also need to copy mysql-connector-java-5.1.3-rc-bin.jar to the C:\JDeveloper\j2ee\home\applib directory, which adds the MySQL Connector/J JDBC 4.0 driver to the runtime class path of the web application.