闲来无事觉得以前用过的一些东西过一段时间会忘记,所以开始想着发博文,第一次发博文,如有问题大家请多多指正。
1,首先在application.xml里面配置数据源
1
2
3
4
5
|
<
bean
id
=
"dataSource"
class
=
"org.springframework.jndi.JndiObjectFactoryBean"
>
<
property
name
=
"jndiName"
>
<
value
>java:comp/env/jdbc/userDataSource</
value
>
</
property
>
</
bean
>
|
2,配置web.xml,刚开始配置的时候,由于没有配置web.xml导致一直连接不上,后面查了一些资料才发现web.xml也需要配置。
1
2
3
4
5
6
|
<
resource-ref
>
<
description
>my DB Connection</
description
>
<
res-ref-name
>jdbc/userDataSource</
res-ref-name
>
<
res-type
>javax.sql.DataSource</
res-type
>
<
res-auth
>Container</
res-auth
>
</
resource-ref
>
|
3,打开tomcat目录下的conf,找到context.xml在里面配置数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<
Resource
name
=
"jdbc/userDataSource"
auth
=
"Container"
type
=
"javax.sql.DataSource"
driverClassName
=
"com.mysql.jdbc.Driver"
url
=
"jdbc:mysql://ip/myDataDaseName"
username
=
"root"
password
=
"password"
maxIdle
=
"40"
maxWait
=
"4000"
maxActive
=
"250"
removeAbandoned
=
"true"
removeAbandonedTimeout
=
"180"
logAbandoned
=
"true"
factory
=
"org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
/>
|
现在jndi应该是可以连接数据库了。
注意:如果修改了context里面的数据库连接,导致启动项目连接的还是以前的数据库地址请把eclipse里面Servers下面的tomcat删除掉,然后重新加入就OK了。
以上只是简单的用jndi连接数据库。
现在说一下怎么把数据库密码进行加密。其实很简单,tomcat里面的这个数据库连接配置最后还是指向
1
|
org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory
|
这个连接,反编译一看,发现就是在这个里面获取用户名密码以及其他参数的,所以我们在这里面动下手脚就OK了。源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
value = properties.getProperty(
"password"
);
if
(value !=
null
) {
dataSource.setPassword(value);
}
value = properties.getProperty(
"url"
);
if
(value !=
null
) {
dataSource.setUrl(value);
}
value = properties.getProperty(
"username"
);
if
(value !=
null
) {
dataSource.setUsername(value);
}
|
我是把这个BasicDataSourceFactory文件复制改名重写了一遍,改后的代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
value = properties.getProperty(
"password"
);
if
(value !=
null
) {
dataSource.setPassword(decode(value));
//解密操作
}
//自定义的解密方法,里面引用了AESEncrypt数字签名加密文件,config.properties里面配置了key钥
private
static
String decode(String password)
throws
Exception {
byte
[] bas = AESEncrypt.parseHexStr2Byte(password);
InputStream is =
new
FileInputStream(
"/opt/config/config.properties"
);
Properties prop =
new
Properties();
prop.load(is);
String key = prop.getProperty(
"key"
);
is.close();
byte
[] decr = AESEncrypt.decrypt(bas, key);
return
new
String(decr);
}
|
然后factory连接指向这个新建的文件就行了
1
|
factory="org.apache.tomcat.dbcp.dbcp.DecodeBasicDataSourceFactory"
|
重写写一个类,是文件方便切换,如果不要加密直接指向BasicDataSourceFactory就行了。