7. 配置 Struts 数据源 Return the specified data source for the current module.
一般步骤:
7.1 配置JNDI数据源
在struts-config.xml配置文件
7.2 获取数据源实例
通过org.apache.struts.action.Action类中定义的二个方法:
protected DataSource getDataSource(HttpServletRequest request, String key)
protected DataSource getDataSource(HttpServletRequest request)
关键代码:
DataSource ds = this.getDataSource(request);
查看org.apache.struts.action.Action类源代码:
/**
*
*
* @param request The servlet request we are processing
* @param key The key specified in the <data-sources>
* element.
*
* @since Struts 1.1
*/
protected DataSource getDataSource(HttpServletRequest request, String key) {
// Identify the current module
ServletContext context = getServlet().getServletContext();
ModuleConfig moduleConfig =
ModuleUtils.getInstance().getModuleConfig(request, context);
return (DataSource) context.getAttribute(key + moduleConfig.getPrefix());
}
protected DataSource getDataSource(HttpServletRequest request) {
return (getDataSource(request, Globals.DATA_SOURCE_KEY));
}
由此可知,数据源需要在自定义的Action处理类(继承自Action)中获取数据源.
参数说明:
request 一次用户请求
key
通过protected DataSource getDataSource(HttpServletRequest request)方法获取数据源
默认调用key值为Globals.DATA_SOURCE_KEY的数据源
引用自struts-config_1_2.dtd
key Servlet context attribute key under which this data source
will be stored. Default is the value specified by string
constant defined by Globals.DATA_SOURCE_KEY. The application
module prefix (if any) is appended to the key
(${key}$prefix}).
[org.apache.struts.Globals.DATA_SOURCE_KEY]
注: 该方法权限是protected,因为可以在不同包的子类中使用,无法在不同包非子类中被调用.另外,自定义的Action处理类构造函数只在第一次请求时,被调用.因此,自定义的Action处理类的实例化很可能用到单例模式.
7.3 数据库操作
一般步骤:
a) 通过数据源实例建立数据库连接
b) 创建Statement对象
c) 获取结果集
d) 关闭数据库连接资源(包括ResultSet,Statement,Connection实例)
关键代码:
Connection conn = ds.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
request.setAttribute("hint", bundle.getString("login.check.hint.success"));
return mapping.findForward("success");
}