web.xml中数据库连接配置:
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">
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();
}
}
}
}