Migrating to DAOs and Spring from Servlets and JDBC, advice?
We've got webapps with servlets that make JDBC calls directly. We've mostly replaced the JDBC calls with Spring JDBC which has been a vast improvement (no more leaked connections!).
I'd like to go a little farther with this mess of code and use DAOs. I'm not sure how to do this with the servlets in the mix, however, because I know the servlets can't be @autowired.
As an example, right now I've got an interface:
public interface AdminDao
{
public boolean isAdmin(int开发者_Go百科 id);
}
and an implementation
package myapp.dao.impl;
@Repository
public class AdminDaoSpring extends SimpleJdbcDaoSupport implements AdminDao
{
private static final String _isAdminSql
= "SELECT count(*) from admin WHERE id=?";
public boolean isAdmin(int id);
{
int cnt = getSimpleJdbcTemplate().queryForInt(_isAdminSql, id);
return (cnt > 0);
}
}
In my applicationContext.xml I have
<bean id="adminDao" class="myapp.dao.impl.AdminDaoSpring"></bean>
I've got a servlet, AdminCheckServlet, that currently makes the above query. How do I change this to use an adminDao instance? I can't annotate the servlet with @Service because the DAO won't get injected as the servlet is constructed by the container (Tomcat) and not Spring.
Should I make another class, AdminService, and have that handle all the calls using AdminDao? The servlets affecting the Admin table would all then instantiate AdminService and use that instead of direct JDBC calls. That doesn't feel right, however.
Thanks!
Paul
I would look into SpringMVC, and use a Spring Controller instead of using java servlets directrly.
Spring MVC
It is pretty easy to use. You create a simple web.xml deployment descriptor to have your endpoints call Springs DispatcherServlet. With this done, you can create a controller class to map these endpoints to methods in the controller. Your controller can be defined as a part of your applicationContext, and can therefore have its DAO (or other services) injected.
You need to use a MVC Framework (the most popular are Struts 1.x, Struts 2 and Spring MVC), and you will be able to call you daos from your controllers (which are called "Actions" in Struts frameworks).
Here is a valuable resource about this : http://www.ibm.com/developerworks/java/library/j-sr2/index.html
I'm not sure you need services, if you don't have much reusable business logic.
精彩评论