运行环境:Tomcat 7.0.x
(1) Tomcat 配置
打开tomcat/conf/context.xml 在文件中增加
(2) web.xml 配置
<Resource
name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password=""
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/test"
/>
解决mysql中中文乱码在url中增加:?useUnicode=true&characterEncoding=utf-8
(2) web.xml 配置
在项目中web.xml中增加以下内容:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
配置类
public class MyConfig extends JFinalConfig {
public void configConstant(Constants me) {
loadPropertyFile("survey.config.txt"); // 加载配置文件
me.setDevMode(getPropertyToBoolean("devMode", true)); // 设置开发者模式
me.setBaseViewPath("/WEB-INF/html"); // 设置视图基本路径
}
public void configRoute(Routes me) {
me.add("/", IndexController.class);// 设置路由
me.add("/sys", SysController.class);// 设置路由
}
public void configPlugin(Plugins me) {
/*
String jdbcUrl = getProperty("jdbcUrl");
String user = getProperty("user");
String password = getProperty("password").trim();
DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, user, password);
me.add(druidPlugin);
ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
arp.setShowSql(getPropertyToBoolean("showSql", false));
me.add(arp);// 接入ActiveRecord插件
// 管理系统 Model
arp.addMapping("subject", Subject.class);
arp.addMapping("options", Options.class);
arp.addMapping("statistical", Statistical.class);
*/
final String JNDINAME = "java:comp/env/jdbc/mysql" ;
DataSource datasource;
try {
// datasource = (DataSource)new InitialContext().lookup("java:MySqlDs");
datasource = (DataSource)new InitialContext().lookup(JNDINAME);
Connection conn = datasource.getConnection() ;
System.out.println("connection auto commit info==="+conn.getAutoCommit());
ActiveRecordPlugin arp = new ActiveRecordPlugin(datasource);
// 管理系统 Model
arp.addMapping("subject", Subject.class);
arp.addMapping("options", Options.class);
arp.addMapping("statistical", Statistical.class);
me.add(arp);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void configInterceptor(Interceptors me) {
me.add(new SessionInViewInterceptor(true));
// me.add(new SysInterceptor());// 后台全局拦截器
}
public void configHandler(Handlers me) {
me.add(new ContextPathHandler("BasePath"));
}
public static void main(String[] args) {
// JFinal.start("WebRoot", 80, "/", 5);
System.out.println(String.format("deregistering jdbc driver: %s",
new ContextPathHandler("BasePath")));
}
}
按照上面的配置就可以正常的使用Tomcat基于JNDI的数据源了。