servlet连接mysql数据库连接池_从连接池获取数据库连接

小编典典

一次执行一次,ServletContextListener而不是每次在init()许多servlet中执行一次。contextInitialized()在webapp启动期间,该方法仅执行一次。

public class Config implements ServletContextListener {

private static final String ATTRIBUTE_NAME = "config";

private DataSource dataSource;

@Override

public void contextInitialized(ServletContextEvent event) {

ServletContext servletContext = event.getServletContext();

String databaseName = servletContext.getInitParameter("database.name");

try {

dataSource = (DataSource) new InitialContext().lookup(databaseName);

} catch (NamingException e) {

throw new RuntimeException("Config failed: datasource not found", e);

}

servletContext.setAttribute(ATTRIBUTE_NAME, this);

}

@Override

public void contextDestroyed(ServletContextEvent event) {

// NOOP.

}

public DataSource getDataSource() {

return dataSource;

}

public static Config getInstance(ServletContext servletContext) {

return (Config) servletContext.getAttribute(ATTRIBUTE_NAME);

}

}

在中进行如下配置web.xml:

database.name

jdbc/mysqldb

com.example.Config

您可以按以下方式在servlet中获取它(init()或doXXX()选择方法):

DataSource dataSource = Config.getInstance(getServletContext()).getDataSource();

但是,我将进一步重构它,最好将JDBC代码放在其自己的类中,而不是在servlet中。查找DAO模式。

2020-06-08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值