SPRing對JDBC進行了非常優雅的封裝,通過一系列的模板方法,我們只需簡單的幾行代碼就可實現數據庫的訪問。
在上次的Web App的基礎上,我們將通過Spring的JdbcTemplate訪問數據庫從而實現用戶驗證。
為了盡量簡化,我們創建一個access數據庫,建立表Account,包含兩個字段:
username:VARCHAR(20),主鍵;
passWord:VARCHAR(20)。
然后輸入一些測試數據,注冊到系統DSN,名字為Blog。
接下來我們在Tomcat中配置一個名為“jdbc/blog”的DataSource如下:
如果你使用其他數據庫,只需要保證表的邏輯結構和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的代碼,這將導致比較“生硬”的編碼?!耙蕾?a href="http://www.49028c.com/tag-1.html">注入”此刻顯示出了威力:我們讓容器注入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.49028c.com)
新聞熱點
疑難解答