Reputation: 18639
I have the following problem, I have configured the following class which should be stored in session.
<bean id="Users" class="com.doolloop.DlUser" scope="session">
<aop:scoped-proxy/>
</bean>
Then I in my Dispatcher servlet I would like to access this class user and set
@RequestMapping(value="/authenticate.do",method = RequestMethod.POST)
public String sampleAuthentication(@Valid Person person, BindingResult result,
Map model,HttpServletRequest request){
...... /some code
HttpSession session = request.getSession();
DlUser user = (DlUser) session.getAttribute("Users");
/// some uses for user object
}
The problem is that I'm always getting null Value of user object.
What am I doing wrong?
Second problem, I read in articles that accessing HttpSession
is not thread-safe, how can it be done safe way? Should be kind of Singleton? Why this is not Thread Safe operation?
Thank you in advance.
Danny.
Upvotes: 1
Views: 7349
Reputation: 597106
That's a special case when you want to inject a bean with a shorter scope into a bean with a longer scope (i.e. a session-scoped bean into a singleton-scoped bean)
You can use a lookup-method
:
<bean id="yourSingletonBean"
class="your.singleton.BeanClass">
<lookup-method name="getDLUser" bean="Users"/>
</bean>
You'll need to make your singleton bean abstract
, and create an abstract
method public DLUser getDLUser()
That, however, is not a perfect solution. The idea is to hold in the session as little as possible. If you don't need to store a bean in the session, but only the current user, you can easily call session.setAttribute(..)
when the user logs in, and then access the current user with session.getAttribute(..)
, without the user being a bean at all.
A way that I chose for the current user in my application is to create a custom @SessionAttribute
annotation. See this question on how to achieve that.
Upvotes: 2
Reputation: 4152
objects scoped "session" are not STORED in session, they are available to the session through the regular direct injection paradigm. It's just that they are session-tied. So, if you need to have this available, you need to inject this bean into your controller. Read here for more info.
Upvotes: 1