servlet mysql web.xml_Servlet 读取web.xml文件中的配置参数连接数据库

web.xml中数据库连接配置:

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">

Servelt_ReadingDBFromWebXml

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp

driver

com.mysql.jdbc.Driver

url

jdbc:mysql://localhost:3306/sample

username

root

password

admin

DBServlet

demo.DBServlet

driver

com.mysql.jdbc.Driver

url

jdbc:mysql://localhost:3306/sample

username

root

password

admin

DBServlet

/readingDB

Servlet代码:

/**

*

*/

package demo;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* Reading DB Config from web.xml

*/

public class DBServlet extends HttpServlet {

/**

*

*/

private static final long serialVersionUID = 1L;

private String diverClass;

private String userName;

private String password;

private String url;

@Override

public void init() throws ServletException {

diverClass = /* getServletConfig(). */getServletContext().getInitParameter("driver");

userName = /* getServletConfig(). */getServletContext().getInitParameter("username");

password = /* getServletConfig(). */getServletContext().getInitParameter("password");

url = /* getServletConfig(). */getServletContext().getInitParameter("url");

try {

Class.forName(diverClass);

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Connection connection = null;

PreparedStatement statement = null;

try {

connection = DriverManager.getConnection(url, userName, password);

statement = connection.prepareStatement("select * from customer");

ResultSet rs = statement.executeQuery();

PrintWriter printWriter = resp.getWriter();

while (rs.next()) {

printWriter.println(rs.getString("id"));

printWriter.println(rs.getString("name"));

}

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

if (statement != null) {

statement.close();

}

if (connection != null) {

connection.close();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值