【发布时间】:2011-07-17 23:11:02
【问题描述】:
Servlets 在多个线程中运行,所以我的问题是:
如果我有很多调用某个实用程序类(例如 DbUtils)的 servlet
Connection c = DbUtils.getConnection();
//....some action with db here
我应该为 DbUtils 中的同步假设额外的操作吗?
其实我想把 HttpServlet 继承成 DatabaseInvokerServlet 之类的东西:
public abstract class DatabaseInvokerServlet extends HttpServlet
方法:
public abstract void getResultSets(Connection connection) throws SQLException;
private AbstractUser currentUser;
private HttpServletRequest request;
private HttpServletResponse response;
protected void processData() {}
protected void afterRequestProcessed() throws ServletException, IOException {}
protected void beforeRequestProcessed() throws ServletException, IOException {}
protected void execute() {
Connection c = null;
try {
c = DbUtils.getConnection();
getResultSets(c);
processData();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public AbstractUser getCurrentUser() {
return currentUser;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
this.request = request;
this.response = response;
this.currentUser = (AbstractUser) request.getSession().getAttribute("currentUser");
}
然后我只需将我的 DatabaseInvokerServlet 继承到新的 servlet 以执行自定义操作。原因是很多地方都没有用try-catch-finally复制粘贴数据库调用块。
但正如我所见,由于同步问题,这种方法不起作用。我说的对吗?
【问题讨论】:
-
请贴出DbUtils.getConnection()的代码;
标签: java servlets jdbc synchronization