Java Reference
In-Depth Information
public void
contextInitialized(ServletContextEvent event) {
System.out.println("Initializing UbiMail context...");
ServletContext context
#
event.getServletContext();
try
{
InitialContext initial
#
new InitialContext();
DataSource ds
#
(DataSource)
initial.lookup("java:comp/env/jdbc/CloudscapeDB");
Connection con
#
ds.getConnection();
Manager mgr
#
new
Manager(con);
context.setAttribute("manager",mgr);
if
(mgr.getError()!
#
null
){
System.out.println("Manager error:"
!
mgr.getError());
}
}
catch
(Exception e){ e.printStackTrace(); }
System.out.println("Completed.");
}
public
void contextDestroyed(ServletContextEvent event) {
System.out.println("UbiMail destroyed.");
}}
The use of a database from JSP requires some setup steps as described in
Sidebar 16.3.
The application descriptor is the
web.xml
file, located in the WEB-INF
folder. It provides a name for the application, then declares the
Context
Listener
class as a listener for the application. Then it defines “index.html” as
the welcome file. Finally it declares the database resource that is used to
connect to the database. The welcome file is the file that is sent to the user if
no specific file is requested (e.g. with the URL: http://server:8080/ UbiMail/).
<?xml version
#
"1.0" encoding
#
"ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>UbiMail - Ubiquitous Email</display-name>
<listener>
<listener-
class
>ContextListener</listener-
class
>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<resource-ref>
<res-ref-name>jdbc/CloudscapeDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>