我是 Spring 新手,我正在研究 CAS。我需要查询数据库以进行用户身份验证,但我使用 servlet 作为控制器。因此,我需要知道是否有任何方法可以在该 servlet 中设置 SimpleJdbcTemplate 并使用它来查询数据库。如果有如何配置 web.xml 文件或任何其他文件。
已经谢谢你了。
我是 Spring 新手,我正在研究 CAS。我需要查询数据库以进行用户身份验证,但我使用 servlet 作为控制器。因此,我需要知道是否有任何方法可以在该 servlet 中设置 SimpleJdbcTemplate 并使用它来查询数据库。如果有如何配置 web.xml 文件或任何其他文件。
已经谢谢你了。
JdbcTemplate直接注入或访问 aServlet或 a不是一个好主意Controller。
您可以DAO在两者之间设置一个层,然后将您的 DAO 注入您JdbcTemplate的 DAO 将是一种更好的方法。
为了使用 aJdbcTemplate您需要DataSource在配置中的某处定义(通过 xml 或注释的 Spring 上下文)。
如果你有一个UserDao,那么你的弹簧配置如下
<bean class="com.xxx.dao.UserDAOImpl" id="userDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
and here you need to difine your "dataSource" there are multiple ways to configure it, You may get better help from google.
现在,你UserDaoImpl看起来像
public class UserDAOImpl implements UserDAO {
private JdbcTemplate jdbcTemplate;
//setter and getter for jdbcTemplate
public List<Map<String, Object>> getUsers() {
String query = "select * from user";
return jdbcTemplate.queryForList(query, new HashMap<String, String>());
}
}
在您的 Servlet 中,您需要使用ServiceLocator
在 servlet 类中
...
public UserDAO getUserDao() {
return ServiceLocator.getBean(UserDAO.class);
}
...
同样有多种设计方法ServiceLocator,这里是简单的实现。
public class ServiceLocator implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* @return Returns the applicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(Class<T> requiredType) throws BeansException {
return getApplicationContext().getBean(requiredType);
}
/**
* @param applicationContext The applicationContext to set.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
ServiceLocator.applicationContext = applicationContext;
}
}
最后,所有这些都是独立的,您需要单独阅读,您将在 google 或 Spring 论坛上获得大量准确的帮助。