Using a Generic Database Bean
Some consider using the JSTL database
access actions in JSP pages a bad
idea because so much business logic ends up in the presentation layer
(the View). For a very simple application, it’s no
big deal, but for a more complex application it’s
better to move the SQL statements to some other component type. You
have basically two options: move it to a Controller servlet (or an
action class that the servlet delegates to), as in the Chapter 19 example, or encapsulate it in a custom action.
In both cases it makes sense to add yet another abstraction layer in
the form of a bean that encapsulates the SQL statements and let the
servlet or tag handler access the data in a purer form. One example
of such a bean is the EmployeeRegistryBean
used in
Chapter 19 for authentication as well as for
retrieving and saving information about an employee.
When you develop this type of database access components, you can of
course use the JDBC API directly. I find it handy to use a generic
JDBC bean, such as the
com.ora.jsp.beans.sql.SQLCommandBean
described in
this section. Besides taking care of a lot of the grunt work, it also
converts a query result into an instance of the same class that the
JSTL <sql:query>
action uses to expose the
result. This makes it easy to use in a JSP page that renders the
result.
The SQLCommandBean
has three write-only
properties. Example 24-4 shows the beginning of the
class file
with the setter
methods.
Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.