java - 为 Servlet 设置 SimpleJdbcTemplate

标签 java spring servlets jdbc spring-jdbc

我是 Spring 的新手,我正在研究 CAS。我需要查询数据库以进行用户身份验证,但我使用 servlet 作为 Controller 。因此我需要知道是否有任何方法可以在该 servlet 中设置 SimpleJdbcTemplate 并使用它来查询数据库。如果有如何配置 web.xml 文件或任何其他文件。

已经谢谢你了。

最佳答案

JdbcTemplate 直接注入(inject)或访问 ServletController 不是一个好主意。
你可以在两者之间有一个 DAO 层并在你的 DAO 中注入(inject)你的 JdbcTemplate 将是一个更好的方法。
为了使用JdbcTemplate,您需要在配置中的某处定义DataSource(通过 xml 或注释的 Spring 上下文)。
如果您有一个 UserDao,那么您的 spring 配置将如下所示

<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 获取此 Dao 的引用

在 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 论坛上获得更多准确的帮助。

关于java - 为 Servlet 设置 SimpleJdbcTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12085490/

相关文章:

java - Thymeleaf HTML 页面转发问题到 Spring Boot App 中的外部网站

java - 通过 spring 作为单例 bean 创建时清晰的 GUI 表单

java - spring boot中两个实体之间的多对多关系

jsp - 我的主机将 java web 文件显示为原始文件

java - 需要从过滤 @WebFilter 中排除 js/css/jpg 等文件

java - web-app_2_5.xsd 在 Weblogic 中验证 web.xml 时显示错误

java - 链表在方法java之后删除

java - 在跟踪此程序时,我可以使用哪种图表方法来保持一切井井有条?

spring - 以编程方式将 cacerts 文件添加到信任库

java - Jmeter 2.11 : Getting Peer Not Authenticated