Tomcat + ActiveJDBC: open/close connection using servlet filter?

佐手、 提交于 2020-01-17 05:51:04

问题


My web application uses ActiveJDBC. This ORM framework requires to open new DB connection with every new thread (and of course close it when the thread finishes). I am wondering if the best way to achieve this is to use a Web Filter.

if this is the case, where do I call Base.open()? the options are init() or doFilter(). also, if I plan to call Base.close() in destroy(), I need to know that indeed destroy() is always called at the thread termination, whether it is normal or abnormal.

EDIT: after reading about servlet filters, I now believe that the proper processing would be to open and close the connection in doFilter():

public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException { 
  Base.open();
  chain.doFilter(request,wrapper);
  Base.close(); 
} 

is this the correct way?


回答1:


Yes, this is the correct way of opening and closing a connection for ActiveJDBC in a web environment.

In addition to that, this is the right place to manage exceptions. For instance, you might want to manage transactions like this:

try{
  Base.openTransaction(); 
  chain.doFilter(request,wrapper);
  Base.commitTransaction(); 
}catch(Exception e){
  // log exception
  Base.rollbackTransaction();
}finally{
  Base.close();
}

Ultimately rather than dealing with Servlets, why not give ActiveWeb a spin? See more here: http://javalite.io/database_configuration




回答2:


This is the correct implementation however, to scale up your application you may want a database connection pooler in which case you will want to keep your connections alive even after you do your db operations.



来源:https://stackoverflow.com/questions/38485175/tomcat-activejdbc-open-close-connection-using-servlet-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!