下面的代码是我们用于项目的“基础”servlet:
public class MyServlet extends Servlet {
private static final long serialVersionUID = 1L;
protected Connection conn;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
}
protected void connectDB() throws NamingException, SQLException {
// get database settings
InitialContext cxt = new InitialContext();
DataSource ds =(DataSource)cxt.lookup( "java:/comp/env/jdbc/MyDB" );
conn = ds.getConnection();
}
protected void closeDB() throws SQLException {
try {
if (conn!=null) conn.close();
}
finally {
conn = null;
}
}
protected void addCacheControl(HttpServletResponse response) {
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, pre-check=0, post-check=0");
response.setHeader("Pragma", "no-cache");
}
}
例如SomeServlet extends MyServlet
...
现在SomeServlet
是在浏览器中访问它对forward()
JSP 页面进行访问,然后刷新一段时间(比如 10 秒)。
页面打开一段时间后,此代码抛出 NullPointerException:
stmt = conn.prepareCall("{call sp_someSP(?, ?, ?)}");