Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-mvc 3.0 application session scope

While using left menu I am not redirecting to the other page but using href to link other pages. But while doing that my session scope which is limited to request no longer exists. So here is my controller code:

Setting the session:

request.getSession(true).setAttribute("application", application);

Getting the session Object in other controller:

HttpSession session = request.getSession();
session.getAttribute("application"); //application null in href; redirect works fine

So is there any way I can use "application" session scope in Spring MVC 3. So that I can have the access to session through out my application.

I tried this code snippet in my application-servlet.xml

<!-- a HTTP Session-scoped bean exposed as a proxy --> 
<bean id="applicationVO" class="com.nypd.viewobjects.ApplicationVO" scope="globalSession"> 
<!-- this next element effects the proxying of the surrounding bean --> 
<aop:scoped-proxy/> 
</bean> 

I am injecting the object to set and retrieve the simple bean as below:

@Autowired private ApplicationVO applicationVO;

what I am I doing wrong here ?

I also tried @SessionAttribute on the controller @SessionAttributes("applicationVO") but it seems the problem still exists.

I will deeply appreciate if anyone can provide me a small example with two controllers.

like image 704
saurabh Avatar asked Feb 21 '11 16:02

saurabh


2 Answers

Read the reference for the defined bean scopes. Here they are:

bean scopes

So what you would usually do is define a bean and register it in scope session. Now you can inject it anywhere you need it. See the explanation here, but beware of this problem (singleton objects with non-singleton dependencies).


Or you can use the @SessionAttributes mechanism to store and retrieve arbitrary session data from your controllers. See the reference here.

Reference:

  • Bean Scopes > Session scope
  • Specifying attributes to store in a session with @SessionAttributes
like image 176
Sean Patrick Floyd Avatar answered Oct 20 '22 21:10

Sean Patrick Floyd


@Session attribute does not store data in session scope. It stores data in conversation scope which is a scope greater than request but less than session. This scope is internally managed by spring for a conversation(which spans across several requests) and removed once the conversation is finished

To store your bean in session scope you will have to declare the requestContextListner in your spring-context.xml which would expose the request to the current thread

like image 1
prashant Avatar answered Oct 20 '22 23:10

prashant