example.servlet.database
Class QueryServlet
example.servlet.database.QueryServlet
- public class 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:
<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>
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.)
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();
}
Method Summary |
void |
doGet(example.servlet.database.HttpServletRequest request,
example.servlet.database.HttpServletResponse response)
Handles GET requests. |
void |
init()
Initialize the servlet, caching the JNDI lookup of the DataSource. |
QueryServlet
public QueryServlet()
init
public void init()
throws example.servlet.database.ServletException
- Initialize the servlet, caching the JNDI lookup of the DataSource.
doGet
public void doGet(example.servlet.database.HttpServletRequest request,
example.servlet.database.HttpServletResponse response)
throws java.io.IOException,
example.servlet.database.ServletException
- Handles GET requests. Resin will call the doGet method when
the browser sends a GET request.
- Parameters:
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.