views:

47

answers:

1

Hello everyone.

I need to initialize every new http session with some values. How do I do that?

I tried to create a session-scoped component and initializing session in @PostConstruct, but session-scoped beans are not eagerly created until I request access them.

+3  A: 

If you are absolutely certain that your want eager initialization, you can do the following:

  • define an interceptor for all beans
  • defina a <lookup-method> for that interceptor:

    <lookup-method name="getCurrentSessionBean"
         bean="yourSessionBeanToInitialize"/>
    
  • define the interceptor abstract, with an abstract method getCurrentSessionBean()

  • create a flag initialized on the bean
  • on each interception, call the lookup method and it will return an instance of the bean from the current session. If it is not initialized (the flag), initialize it
  • you can also use @PostConstruct and spare the initizlied flag

Another option is to:

  • define a HttpSessionListener in web.xml (or with annotations if using servlet 3.0)
  • use WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) to obtain the context
  • call getBean(..) to get an instance of the session-scoped bean
  • it will be initialized with @PostConstruct at that point

The first option is "more spring", the second is easier and faster to implement.

Bozho
In method 2 where do I get servletContext?
artemb
Got it: HttpSessionEvent.getSession().getServletContext()
artemb
I use an aop-proxied session-scoped bean UserInfo to hold user session information. The problem is that the instance of UserInfo I get in the session listener is different from the one I get in my controller. I guess this may be a problem of different contexts but I am not sure
artemb