参考:https://blog.csdn.net/chaonigema/article/details/84214228
数据库配置在tomcat的文件中:%TOMCAT_HOME%/conf/context.xml
<Resource name="jndi/mpsdb" auth="Container" type="javax.sql.DataSource" maxactive="100" maxidle="100" maxwait="300" username="mpsgxzq" factory="%path%.TomcatSecurityDataSourceFactory" password="bXBzZ3h6cQ==" driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:mps"/>
factory配置的是用来处理加密密码的
import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory; import com.hylandtec.mps.bas.util.CryptoUtil; /** * tomcat7 jndi 加密 * @author ccc * */ public class TomcatSecurityDataSourceFactory extends BasicDataSourceFactory { @Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { Object o = super.getObjectInstance(obj, name, nameCtx, environment); if (o != null) { BasicDataSource ds = (BasicDataSource) o; if (ds.getPassword() != null && ds.getPassword().length() > 0) { // 密码解密逻辑 String pwd = CryptoUtil.decrypt_Base64(ds.getPassword()); ds.setPassword(pwd); } return ds; } else { return null; } } }
这部分代码可以以jar包的形势放到tomcat服务器的lib下,也可以直接以类的形势放到本地项目中,注意factory引用就好了
加密解密算法可以自己写,笔者这边是利用BAS64进行加密解密,此加密算法java1.7也可使用
import java.math.BigInteger; import java.security.MessageDigest; import org.apache.commons.codec.binary.Base64; public class CryptoUtil { /*** * Base64加密 * @param str 需要加密的参数 * @return * @throws Exception */ public static String encrypt_Base64(String str) throws Exception { byte[] result = Base64.encodeBase64Chunked(str.getBytes("UTF-8")); //String result = Base64.getEncoder().encodeToString(str.getBytes("UTF-8")); return new String(result); } /*** * Base64解密 * @param str 需要解密的参数 * @return * @throws Exception */ public static String decrypt_Base64(String str) throws Exception { byte[] asBytes = Base64.decodeBase64(str.getBytes()); //byte[] asBytes = Base64.getDecoder().decode(str); String result = new String(asBytes,"UTF-8"); return result; } }