最简单方法,直接在servlet中添加连接数据库的程序:
在web.xml中增加配置信息:
<servlet>
<servlet-name>CreateDBServlet</servlet-name>
<servlet-class>org.free.servlet.CreateDBServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306</param-value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>1234</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CreateDBServlet</servlet-name>
<url-pattern>/createdb</url-pattern>
</servlet-mapping>
添加一个管理数据库的servlet:
public class CreateDBServlet extends HttpServlet{
private String url;
private String user;
private String password;
private String clr ="drop database if exists bookstore";
private String createDB ="CREATE DATABASE bookstore";
private String useDB = "USE bookstore";
private String createTB = "CREATE TABLE bookinfo("
+ "id INT not null primary key,"
+ "title VARCHAR(50) not null,"
+ "author VARCHAR(50) not null,"
+ "bookconcern VARCHAR(50) not null,"
+ "publishdate DATE not null,"
+ "price FLOAT(6,2) not null,"
+ "amount SMALLINT,"
+ "remark VARCHAR(200))ENGINE = InnoDB";
private String insertB1 = "INSERT INTO bookinfo values(1,'Java Web','孙鑫','电子工业出版社','2006-4-20',79.0,35,null)";
private String insertB2 = "INSERT INTO bookinfo values(2,'SSH','汪峰','北邮出版社','2007-11-20',52.0,21,null)";
private String insertB3 = "INSERT INTO bookinfo values(3,'Linux内核','胡一菲','人大出版社','2010-1-15',152.23,null,null)";
public void init() throws ServletException {
String driverClass = getInitParameter("driverClass");
url = getInitParameter("url");
user = getInitParameter("user");
password = getInitParameter("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException ce){
throw new ServletException("加载数据库失败");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
stmt.execute(clr);
stmt.executeUpdate(createDB);
stmt.executeUpdate(useDB);
stmt.executeUpdate(createTB);
stmt.addBatch(insertB1);
stmt.addBatch(insertB2);
stmt.addBatch(insertB3);
stmt.executeBatch();
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("数据库创建成功");
out.close();
} catch(SQLException e) {
throw new ServletException(e);
} finally {
try {
stmt.close();
} catch (SQLException e) {
stmt = null;
e.printStackTrace();
}
stmt = null;
try {
conn.close();
} catch (SQLException e) {
conn = null;
e.printStackTrace();
}
conn = null;
}
}
}
在web.xml中增加context-param和创建的listener信息:
<context-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/bookstore?
useUnicode=true&characterEncoding=utf8</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>test</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>1234</param-value>
</context-param>
<listener>
<listener-class>org.free.db.DBServletContext</listener-class>
</listener>
继承servletcontextlistener,实现应用上下文监听器:
public class DBServletContext implements ServletContextListener {
private String driverClass;
private String url;
private String user;
private String password;
private final static String CONNECTION = "CONNECTION";
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
Connection conn = (Connection) sc.getAttribute(CONNECTION);
sc.removeAttribute(CONNECTION);
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
driverClass = sc.getInitParameter("driverClass");
url = sc.getInitParameter("url");
user = sc.getInitParameter("user");
password = sc.getInitParameter("password");
Connection conn = null;
try {
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
sc.setAttribute(CONNECTION, conn);
}
}
在涉及到访问数据库的情况,在servlet中调用getServletContext,然后从中取得连接即可:
/**
* curl -d "" http://localhost:8080/JavaWeb/querybook <br/>
* <br/>
* [{"id":"1","title":"Java Web"},{"id":"2","title":"SSH"},{"id":"3","title":"Linux内核"}]
*
*/
public class BookServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext sc = getServletContext();
Connection conn = (Connection) sc.getAttribute("CONNECTION");
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement("select title,id from bookinfo");
rs = stmt.executeQuery();
resp.setContentType("application/x-javascript;charset=utf-8");
PrintWriter out = resp.getWriter();
......
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}