imwaiting wrote:
1.U said Strategy 1 separate the database operations details from the controlle layer,but Strategy 1 just get the Session from the HibernateUtil,if i don't use a DAO, i must write commit,save,delete ect in my controller servlet,but if i use DAO,i should pass the Session reference to the DAO as an argument,this also can work in Strategy 2,because Strategy 2 also return a Session Reference.
With strategy 1 you don't have to pass a Session object to the DAOs. That's just the trick of the thread-local pattern. Each and every DAO object just has to use HibernateUtil.getSession() and they will all get the same object if they are used in the same thread.
imwaiting wrote:
2.Why and How must i close the Session within a ServletFilter? A ServeltFilter has a doFilter() method to implement the filter details,but it works just before the request has been past to the specific Servlet,so i want to know, why and how must i close the Session within it?
You can work perfectly without it. It just makes things easier in my opinion.
You should always close the Session.
If you separated your controller from the view you may have a JSP (a view) which uses persistent POJOs to be displayed. These POJOs may have unitialized properties (because of lazy loading). If you closed the Session in your controller (the servlet) the uninitialized properties are not available any more and you will get an exception. If you want them to be available you will have to keep the Session open until the JSP is processed. Then you need a ServletFilter to do some cleanup e.g. close the Session.
It depends on the implementation of your doFilter method whether the work is done before the servlet's work or after it. It is something like:
Code:
public void doFilter(...) {
...
chain.doFilter(...)
// do cleanup
HibernateUtil.closeSession()
}