国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

在Spring中使用JDBC

2019-11-18 16:08:25
字體:
來源:轉載
供稿:網友

SPRing對JDBC進行了非常優雅的封裝,通過一系列的模板方法,我們只需簡單的幾行代碼就可實現數據庫的訪問。

在上次的Web App的基礎上,我們將通過Spring的JdbcTemplate訪問數據庫從而實現用戶驗證。

為了盡量簡化,我們創建一個access數據庫,建立表Account,包含兩個字段:

    username:VARCHAR(20),主鍵;
    passWord:VARCHAR(20)。

然后輸入一些測試數據,注冊到系統DSN,名字為Blog。

接下來我們在Tomcat中配置一個名為“jdbc/blog”的DataSource如下:

在Spring中使用JDBC

如果你使用其他數據庫,只需要保證表的邏輯結構和JDNI名“jdbc/blog”。在AccountManager中,我們使用JdbcTemplate訪問數據庫來驗證用戶:

    Account getAccount(String username, String password) throws Exception {
        // validate the password:
        InitialContext ctx = new InitialContext();
        DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/blog");
        JdbcTemplate jt = new JdbcTemplate(dataSource);
        String pass = (String) jt.queryForObject(
            "select password from Account where username=?",
            new Object[] {username}, String.class);
        if(password.equals(pass))
        {
            Account account = new Account();
            account.setUsername(username);
            account.setPassword(password);
            return account;
        }
        throw new Exception("authorization failed.");
    }

編譯運行,我們可以輸入hello.c?username=xxx&password=xxx來測試用戶登錄,如果匹配數據庫中的記錄,會顯示出用戶名,否則可以看到authorization failed異常。要更友好的顯示登陸失敗,可以在Controller中導向一個login_failed.jsp并給出登陸失敗的原因。

下面我們來看這個AccountManager,很顯然在驗證邏輯中我們寫入了JNDI查找DataSource的代碼,這將導致比較“生硬”的編碼。“依賴注入”此刻顯示出了威力:我們讓容器注入DataSource:

public class AccountManager implements java.io.Serializable {
    private DataSource dataSource;
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    Account getAccount(String username, String password) throws Exception {
        JdbcTemplate jt = new JdbcTemplate(dataSource);
        ...
    }
}


OK,現在這個AccountManager變得優雅多了,現在如何配置DataSource的注入呢?Spring提供了一個DataSourceUtils類,通過靜態方法getDataSourceFromJndi來獲得容器中配置的DataSource。我們添加以下配置:

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DataSourceUtils"
          factory-method="getDataSourceFromJndi">
        <constrUCtor-arg><value>jdbc/blog</value></constructor-arg>
    </bean>
    <bean id="accountManager" class="AccountManager">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>

現在重新部署,效果和以前一樣,但是相關代碼已被“放到”配置文件中了。

:( 待續... :)

(出處:http://www.survivalescaperooms.com)



上一篇:在Spring中配置Bean

下一篇:Tomcat入門指南

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 车致| 长子县| 金坛市| 大石桥市| 顺义区| 宣武区| 维西| 柘荣县| 镇远县| 富民县| 封开县| 高清| 博野县| 河池市| 建始县| 阳西县| 清水县| 盈江县| 永川市| 灵山县| 鹰潭市| 呈贡县| 兴隆县| 城步| 长宁区| 永仁县| 抚顺县| 汝南县| 汤原县| 冀州市| 宁城县| 象山县| 宝应县| 新干县| 通河县| 阿坝| 祁门县| 怀远县| 西乡县| 通化市| 西畴县|