|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object HttpServlet example.servlet.database.QueryServlet
Example of a database query from a servlet.
Database access has two components: looking up the data source using JNDI and using JDBC calls to retrieve the data.
The JNDI lookup finds the DataSource configured in the resin.conf
or web.xml. Since the JNDI lookup only needs to happen once,
it's usually put in the init() method. The database configuration looks
something like the following:
Different databasees will have different values for driver-name
and url. The max-connections and max-idle-time are configuration
values for Resin's database pooling. The servlet doesn't need to
worry about database pooling; Resin will take care of it automatically.
(The APIs used in the example are all from the J2EE standard.)
<resource-ref>
<res-ref-name>jdbc/test
<res-type>javax.sql.DataSource
<init-param driver-name="com.caucho.jdbc.mysql.Driver"/>
<init-param url="jdbc:mysql_caucho://localhost:3306/test"/>
<init-param max-connections="20"/>
<init-param max-idle-time="30"/>
</resource-ref>
Applications should always use the following pattern for all
database access. The try ... finally pattern is vital to make
sure the connection is released to the pool.
Connection conn = null;
try {
conn = dataSource.getConnection();
...
} finally {
if (conn != null)
conn.close();
}
Constructor Summary | |
QueryServlet()
|
Method Summary | |
void |
doGet(HttpServletRequest request,
HttpServletResponse response)
Handles GET requests. |
void |
init()
Initialize the servlet, caching the JNDI lookup of the DataSource. |
Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Constructor Detail |
public QueryServlet()
Method Detail |
public void init() throws ServletException
ServletException
public void doGet(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException
request
- the request object contains the data from
the browser's request.response
- the response object contains methods to send
data back to the browser.
java.io.IOException
ServletException
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |