Announcement Announcement Module
Collapse
No announcement yet.
problem displaying file contents Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • problem displaying file contents

    hi i am testing out this web application where one can upload files text files
    and stored and then view then (not download them) on the browser.
    i am using hibernate/spring mvc and spring
    i am using hibernate3.

    but i keep getting LazyInitizationException any time i click on the link that will view my file what can i do to correct this
    here is a bit of my code
    Code:
    	
            	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    		<property name="jndiName" value="java:comp/env/box79DS"/>
    	</bean>
    	
    	<!-- Hibernate SessionFactory -->
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource" ref="dataSource"/>
    		
                    <property name="mappingDirectoryLocations">
            <list>
            <value>classpath:/com/mw/model/hibernate</value>
            </list>
                </property>
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    				<prop key="hibernate.show_sql">true</prop>
    			<prop key="hibernate.generate_statistics">true</prop>
                            <prop key="hibernate.hbm2ddl.auto">create</prop>			
    			</props>
    		</property>
    		<property name="eventListeners">
    			<map>
    				<entry key="merge">
    					<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
    				</entry>
    			</map>
    		</property>
                    </bean>
    
    	<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory"/>
    	</bean>
            
            <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
         <property name="sessionFactory">
         <ref bean="sessionFactory"/>
         </property>
    </bean>
    <bean id="userDAO" class="com.mw.dao.UserDAO">
      <property name="hibernateTemplate">
    <ref bean="hibernateTemplate"/>
    </property>
    </bean>
    <!--use if not using transactions-->
    <!--
    <bean id="userManager"
    class="com.mw.service.impl.UserManagerImpl">
    <property name="userDAO"><ref local="userDAO"/></property>
    </bean>
    -->
    
    <bean id="userManagerTarget"
    class="com.mw.service.impl.UserManagerImpl">
    <property name="userDAO"><ref local="userDAO"/></property>
    </bean>
    <bean id="userManager"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
    <ref local="transactionManager"/>
    </property>
    <property name="target">
    <ref local="userManagerTarget"/>
    </property>
    <property name="transactionAttributes">
    <props>
    <prop key="load*">PROPAGATION_REQUIRED</prop>
    <prop key="update*">PROPAGATION_REQUIRED</prop>
    <prop key="remove*">PROPAGATION_REQUIRED</prop>
    <prop key="*">PROPAGATION_REQUIRED</prop>
    </props>
    </property>
    </bean>
    </beans>
    my dao
    Code:
    public class UserDAO extends HibernateDaoSupport
            implements Box79 {
          public Collection getUsers()
        throws DataAccessException {
            return getHibernateTemplate().find("from User u order by u.username");
        }
            public User loadUser(int id)
        throws DataAccessException {
            return (User)getHibernateTemplate().load(com.mw.model.User.class, new Integer(id));
        }
       
        public void storeUser(User user)
        throws DataAccessException {
            getHibernateTemplate().save(user);
        }
        public void updateUser(User user)
        throws DataAccessException {
            getHibernateTemplate().update(user);
        }
         
        public void removeUser(int id)  throws DataAccessException {
            User user= (User)getHibernateTemplate().load(com.mw.model.User.class, new Integer(id));
            getHibernateTemplate().delete(user);
        }
    }
    then my controller streamhandler method is what is responsible for handling streaming the contents of the file to the browser.
    Code:
    public class Box79Controller extends MultiActionController
    {
         
        
        public ModelAndView streamHandler(HttpServletRequest request, HttpServletResponse response)
            throws ServletException
        {
       String userId=request.getParameter("userId");
           User user= userManager.loadUser(userId);
        /*try {
       BufferedOutputStream out;
            try {
                out = new BufferedOutputStream(response.getOutputStream());
              response.setContentType("text/html");
                response.setContentLength(user.getSomeByte().length);
    
    // write the bytes to the outputstream
                out.write(user.getSomeByte());
                out.close();
    
    } 
            catch(Exception e){
    
            e.printStackTrace();
    }
    
          */
               try {
               
         
                response.setContentType("text/html");
                FileCopyUtils.copy(user.getSomeByte(),response.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
       
         
         return null;
        }        
         public ModelAndView userHandler(HttpServletRequest request, HttpServletResponse response)
            throws ServletException
        {
        
            return new ModelAndView("addUser");
        }
          public ModelAndView listUserHandler(HttpServletRequest request, HttpServletResponse response)
            throws ServletException
        {
          ArrayList listUser=(ArrayList)userManager.getUsers();
          HttpSession session=request.getSession();
          session.setAttribute("listUsers",listUser);
            //   System.out.println();
        	return new ModelAndView("listUsers", "users", listUser);
            
        }
           public ModelAndView deleteHandler(HttpServletRequest request, HttpServletResponse response)
            throws ServletException
        {
            String userid=request.getParameter("userId");
            userManager.removeUser(userid);
            return new ModelAndView("redirect:listUserAction.htm");
    
        }
          public ModelAndView addUserHandler(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,BindException
        {
       
     // apply binder to custom target object
     ServletRequestDataBinder binder = new ServletRequestDataBinder(user);
     binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
     binder.bind(request);
     // optionally evaluate binding errors
     Errors errors = binder.getErrors();
     User user = (User)binder.getTarget(); 
        
    
    userManager.storeUser(user);
    
    return new ModelAndView("redirect:addUser.htm");
           
        }
    }
    Code:
        <body>
    
        <title>Users List</title>
     <A href="<c:url value="/addUser.htm"/>">Add User</A>  
        <table border="1" >
    <thead>
    <tr>
    <th>User Id</th>
    <th>user Name</th>
    <th>password</th>
    <th> </th>
    
    <th> view database</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="user" items="${users}" >
    <tr>
    <td><a href=""><c:out value="${user.id}"/></a></td>
    <td><c:out value="${user.username}"/></td>
    <td><c:out value="${user.password}"/></td>
    <td><c:out value="${user.password}"/></td>
    <td><a href="deleteAction.htm?userId=<c:out value="${user.id}"/>">delete User </a> ;nsp <a href="updateAction.htm?userId=<c:out value="${user.id}"/>"> Update User </a>
    </td>
    <td><a target="blank" href="streamAction.htm?userId=<c:out value="${user.id}"/>">View File -</a></td>
    </tr>
    </c:forEach>
    </tbody>
    </table>
    then some stacktraces
    Code:
    exception 
    org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
    	org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)
    	org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)
    org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:134)
    com.mw.model.User$$EnhancerByCGLIB$$e9d9eb0e.getSomeByte(<generated>)
    	com.mw.web.Box79Controller.streamHandler(Box79Controller.java:91)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	java.lang.reflect.Method.invoke(Method.java:324)
    org.springframework.web.servlet.mvc.multiaction.MultiActionController.invokeNamedMethod(MultiActionController.java:369)
    	org.springframework.web.servlet.mvc.multiaction.MultiActionController.handleRequestInternal(MultiActionController.java:325)
    	org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:139)
    	org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44)
    	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:717)
    	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:658)
    	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:392)
    	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:347)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    rg.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
    i read somewhere that hibernate closes it's session after each transaction but i thought the hibernateTemplate was suppose to open it for as long ?!(probably wrong?)
    help pls
    pls what am i doing wrong ?
    i had to send abridged version of my because i am only allowed to send 10000 characters

  • #2
    You probably need the OpenSessionInViewInterceptor:-

    Code:
    <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
        <property name="sessionFactory">
            <ref bean="sessionFactory"/>
        </property>
    </bean>
    which you just then plug into your handler mapping:-

    Code:
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="openSessionInViewInterceptor"/>
            </list>
        </property>
        <property name="mappings">
            <props>
                <!-- Mappings Here -->
            </props>
        </property>
    </bean>
    This will keep the Hibernate session open for the duration of the request, not just the individual transaction.

    Bob

    Comment


    • #3
      OpenSessionInViewFilter/OpenSessionInViewInterceptor may be of use. However there are also disadvantages to using that approach. Doing a search for OpenSessionInViewFilter and OpenSessionInViewInterceptor on the forum should get you a number of posts discussing the tradeoffs.

      In the end, my opinion is that it's better for your transactional service layer to ensure all data needed by the view layer is pre-loaded...

      Regards,

      Comment


      • #4
        wiring an interceptor with mvc.multiaction.PropertiesMethodNameResolver

        Originally posted by Cowboy Bob
        You probably need the OpenSessionInViewInterceptor:-

        Code:
        <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
            <property name="sessionFactory">
                <ref bean="sessionFactory"/>
            </property>
        </bean>
        which you just then plug into your handler mapping:-

        Code:
        <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="interceptors">
                <list>
                    <ref bean="openSessionInViewInterceptor"/>
                </list>
            </property>
            <property name="mappings">
                <props>
                    <!-- Mappings Here -->
                </props>
            </property>
        </bean>
        This will keep the Hibernate session open for the duration of the request, not just the individual transaction.

        Bob


        thanks for ur reply but i am not using org.springframework.web.servlet.handler.SimpleUrlH andlerMapping

        i am using org.springframework.web.servlet.mvc.multiaction.Pr opertiesMethodNameResolver

        so i am having a problem wiring the interceptors

        Comment


        • #5
          sorry my bad got it thanks

          Comment

          Working...
          X