Announcement Announcement Module
Collapse
No announcement yet.
Accessing a session-scoped bean from dispatcher-servlet.xml in my views Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Accessing a session-scoped bean from dispatcher-servlet.xml in my views

    I have configured a session-scoped bean in my dispatcher config:

    Code:
    <bean id="mySessionScopedBean" class="net.sandbox.pojos.MySessionScopedBean" scope="session">
        <aop:scoped-proxy />
    </bean>
    If I want to access the data inside this bean from my views, I have to explicitly do model.addAttribute(mySessionScopedBean) from my controllers every time I want to show information from the session-scoped bean in a view. (Provided, of course, that the controller has @Autowired'd the bean.)

    I thought I had found a trick to automatically make the session-scoped bean accessible for a JSP page.

    Code:
    <jsp:useBean id="mySessionScopedBean" scope="session" class="net.sandbox.pojos.MySessionScopedBean" />
    But this doesn't seem to use the Spring-created instance of the session-scoped bean. Instead, it appears that a separate session-scoped bean was created. Is there a way to access the session-scoped bean that was defined in my dispatcher-servlet.xml in my JSP pages without having to pass it to the view using model.addAttribute each time?

  • #2
    Although I wouldn't suggest doing it this way (and simply put it in the model) you can use the RequestContextUtils to get access to the applicationcontext. With that you can access the bean you want by simply calling getBean...

    Comment


    • #3
      I'm looking at RequestContextUtils.getWebApplicationContext(Servl etRequest request) and WebApplicationContext.getBeansOfType(Class<T> type) to do the job. Is this a good way to do it? If not, can you point me to a code sample that shows me how to do it?

      Comment


      • #4
        As stated simply use the RequestContextUtils to get the ApplicationContext and use that to retrieve the bean. As I also stated I would strongly recommend against it, instead I probably would write a HandlerInterceptor which adds this bean to the model or as a request attribute. You should keep your views as lean as possible.

        Comment


        • #5
          I downloaded an example of a project that uses HandlerInterceptor for this. Here's what I came up with...

          I added this to dispatcher-servlet.xml.
          Code:
          <bean id="sessionBeanInserter" class="net.sandbox.handlerinterceptors.SessionBeanInserter" />
          Here's my net.sandbox.handlerinterceptors.SessionBeanInserte r.
          Code:
          public class SessionBeanInserter extends HandlerInterceptorAdapter {
              @Autowired
              private MySessionScopedBean mySessionScopedBean;
              
              public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                  // Insert the session-scoped bean
                  modelAndView.addObject("mySessionScopedBean", mySessionScopedBean);
              }
          }
          This results in a server error. The exception is as follows:

          Code:
          javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
          	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
          	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
                  ...
          Root cause:

          Code:
          java.lang.NoClassDefFoundError: javax/portlet/PortletRequest
          	java.lang.Class.getDeclaredConstructors0(Native Method)
          	java.lang.Class.privateGetDeclaredConstructors(Class.java:2406)
                  ...
          What am I doing wrong?

          Comment


          • #6
            Judging from the exception you use the wrong HandlerInterceptor the one from the portlet instead of the servlet package... However I suggest posting the full stacktrace that should give more information.

            In short you have introduced a dependency to the portlet stuff somewhere...

            Comment


            • #7
              Here's the full stack trace.

              Exception

              Code:
              javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
              	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
              	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
              	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
              	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
              	org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:284)
              	org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:322)
              	org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1714)
              	java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
              	java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
              	java.lang.Thread.run(Thread.java:636)
              Root cause
              Code:
              java.lang.NoClassDefFoundError: javax/portlet/PortletRequest
              	java.lang.Class.getDeclaredConstructors0(Native Method)
              	java.lang.Class.privateGetDeclaredConstructors(Class.java:2406)
              	java.lang.Class.getDeclaredConstructors(Class.java:1853)
              	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:227)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:930)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:903)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
              	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
              	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
              	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
              	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
              	org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
              	org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
              	org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
              	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
              	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
              	org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
              	org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
              	org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
              	javax.servlet.GenericServlet.init(GenericServlet.java:160)
              	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
              	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
              	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
              	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
              	org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:284)
              	org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:322)
              	org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1714)
              	java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
              	java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
              	java.lang.Thread.run(Thread.java:636)
              Root cause
              Code:
              java.lang.ClassNotFoundException: javax.portlet.PortletRequest
              	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
              	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
              	java.lang.Class.getDeclaredConstructors0(Native Method)
              	java.lang.Class.privateGetDeclaredConstructors(Class.java:2406)
              	java.lang.Class.getDeclaredConstructors(Class.java:1853)
              	org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:227)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:930)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:903)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
              	org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
              	org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
              	org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
              	org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
              	org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
              	org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
              	org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
              	org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
              	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
              	org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
              	org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
              	org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
              	org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
              	javax.servlet.GenericServlet.init(GenericServlet.java:160)
              	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
              	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
              	org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
              	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
              	org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:284)
              	org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:322)
              	org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1714)
              	java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
              	java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
              	java.lang.Thread.run(Thread.java:636)

              Comment


              • #8
                Judging from the stacktrace it looks like one of your classes has a dependency on the PortletRequest... I suggest checking your constructors and/or checking your imports. It might even be that you use something else that has a dependency on the PortletRequest.

                Comment


                • #9
                  Apparently javax.portlet isn't a default part of the servlet API, so I downloaded http://repository.jboss.org/portlet/...ortlet-api.jar. I still can't access the session-scoped object from my view though...

                  Code:
                  MySessionScopedBean mySessionScopedBean = (MySessionScopedBean) request.getAttribute("mySessionScopedBean");
                  out.println("[DEBUG] " + mySessionScopedBean);
                  This outputs [DEBUG] null.

                  Comment


                  • #10
                    As I stated there must be something which has a dependency on the portlet api portlet != servlet.. .I suggest a read on what a portlet is... Judging from what you tell you don't need the portlet api and thus you are using something wrong in your application (something which is dependend on the portlet api).

                    Figure out the error instead of slapping jars in there which won't solve your problem.

                    Comment


                    • #11
                      You're right, I accidentally imported org.springframework.web.portlet.handler.HandlerInt erceptorAdapter instead of org.springframework.web.servlet.handler.HandlerInt erceptorAdapter... d'oh. Still though, I'm seeing

                      Code:
                      [DEBUG] null
                      and a breakpoint I put on

                      Code:
                      modelAndView.addObject("mySessionScopedBean", mySessionScopedBean);
                      is never reached.

                      Comment


                      • #12
                        If it isn't reached then the interceptor isn't called. So that must be something in your configuration...

                        Comment


                        • #13
                          I figured it out by looking at some more examples and the Spring documentation. Thanks for your advice!

                          Comment

                          Working...
                          X