what is the difference between request and session scope in spring? - spring

In request scope, a bean is defined to an HTTP request whereas in session scope, it is scoped to an HTTP session.
So for an instance,
if the bean scope is request and, a user makes more than one request for a web page in his user session, then on every request a new bean would be created.
Whereas if the scope is defined as session for the bean, if a user makes a request for a web page more than once, then on every request same bean would be returned.
please let me know if this understanding is correct?

Your understanding is correct. However I would like to add something
Whereas if the scope is defined as session for the bean, if a user
makes a request for a web page more than once, then on every request
same bean would be returned.
I would change it as "Whereas if the scope is defined as session for the bean, if a user makes a request for a web page more than once, then on every request same bean would be returned, as long as the requests are within the same user session and made from a client which is capable of maintaining the session (You can't expect the curl to maintain the usersession unless you pass the cookie/session identifier header)."

Session Scope -- when the scope is session,the values of formbean(form data) would be available throughout the session. it will not destroyed until session timeout up or session destroyed.
Request Scope -- when the scope is request,the values of formbean(form data) would be available for the current request. it will refresh on every request of same user/different user.
because http is stateless protocol

Related

request.isRequestedSessionIdValid() returns true after invalidating the session

When I'm logging out the user, I'm invalidating his session by calling session.invalidate() and redirecting myself back to the login page.
Each and every page other than the login page in my application is a JSP page. What I'm checking in every JSP page is if the requested session exists and if the requested session ID is valid.
After logging out the user and calling session.invalidate(), if I try to directly open the url of my home page, it still returns request.isRequestedSessionIdValid() as true. Also, calling session.invalidate() does not make the session null.
The following is my code:
Logout.java
session.inValidate();
In my home.jsp. I am explicitly checking if the requested session is valid.
The following is the code:
HttpSession session=request.getSession();
boolean a=request.isRequestedSessionValid()
if(session==null || a==false){
...
...
}
Trouble is session does not return null and a is still true, even after logging out the user( invalidating the session ).
Any help is appreciated!
I'm invalidating his session by calling session.invalidate() and redirecting myself back to the login page.
If the client makes a new request after its session is invalidated then the webapp will handle that request in the context of a new, initially valid session. If the webapp sends a response to the client between the session invalidation and the new request, including, but not limited to, a redirect response, then that new request is unlikely to request the invalidated session's ID. That's because whatever the means by which session association is maintained, the response gives the webapp an opportunity to communicate the end of the previous session to the client, if it even needs to do so at all.
The client might or might not request any session ID at all in that case. If it does not, then you will see request.isRequestedSessionIdValid() returning false; otherwise, the main scenario in which you will see request.isRequestedSessionIdValid() returning false is when the session has timed out since the most recent response. You cannot rely on this to determine whether the user has authenticated.
After logging out the user and calling session.invalidate(), if I try to directly open the url of my home page, it still returns request.isRequestedSessionIdValid() as true.
Why should it not?
Also, calling session.invalidate() does not make the session null.
No, it doesn't, nor should it. If you want to be able to detect whether the session has been invalidated then you can make use of the fact that after it is invalidated, most of its methods will throw IllegalStateException. But if you find yourself needing to know that -- other than by catching and handling the IllegalStateException in an appropriate context -- then you're probably doing something wrong.

How to use data saved from an old session in next session?

I have been using cookies to share non-sensitive data across sessions. I want to store some lastUsedEntity (a string literal) from the current session at user logout event so that that entity can be read/used at next login session. The said entity belongs to a session bean of my application.
I decided to extract and store this entity in #PreDestroy method of the session bean. The method ran successfully at session timeout of the application. But storing cookie failed because FacesContext.getCurrentInstance() was null in #PreDestroy method, maybe because JSF Lifecycle request-response cycle completed by then. I tried caching FacesContext.getCurrentInstance() in #PostContruct method of my session bean so that I could access faces context cached instance but then I faced another problem java.lang.IllegalStateException at com.sun.faces.context.FacesContextImpl.assertNotReleased because I used FacesContext as instance variable of my session scoped class. I would appreciate if I could get some heads up here or any other better idea in order to persist my old session data for further use in this scenario.
There's not necessarily means of a HTTP request when a HTTP session gets expired in server side due to enduser inactivity. The enduser itself is the only one who can send a HTTP request. If there's no HTTP request which invoked the FacesServlet, then there's no FacesContext either. Let alone a HTTP response on which you could return the cookie.
You'd better rethink your logic. E.g. set the cookie immediately on every request, overriding the previous one, if necessary on a specific path and/or with a timestamp in the cookie value. Depending on the concrete functional requirement there may be better ways though as cookies are fully manipulatable by the enduser and you should absolutely not depend critical business logic on that. If it's purely for presentation, it should be okayish, otherwise better store it in the database associated with logged-in user.

Grails Spring Security - reload session variables on relogin after session timeout

I'm using spring security core in my grails application. My app has lots of ajax calls which call controllers. Controllers in turn, depend on some session variables to fulfil the request. I'm currently able to correctly display the ajax login form on session timeout. However, it creates a new session with only the newly created user object. All other objects stored in session are lost.
Is there a way to reload session variables after a user logs back in after session time out?
the purpose of the session scope is that it's wiped when the session ends. if you need to share data between sessions, you should rethink your architecture and persist the data in a database (server side), or a cookie (client side)
(moved from comments into an answer)

JSF - How to save managedBean state when session times out?

I am working for a client that has it's own session management system in case of idle timeouts. What happens is the following :
User stays idle for the set amount of time.
Session times out redirecting to login page
User enters credentials and is redirected back to where he was.
Now the above process is handled by passing a POST request passing the javax.faces.ViewState to the session management system. However, in case of timeouts it needs only 8K of data in the request to process and redirect. But since my managed bean is saving a lot of data (banking app, need to keep track of the calculations!) the size of the request is high (around 20K) due to which redirection fails.
So is there any way I can somehow save the ViewState? Or better, any way I can prevent the timeout? Something like keeping the session alive?
All my managed beans have a session scope.
EDIT: Just in case required, the javax.faces.STATE_SAVING_METHOD context-param in web.xml is set to client for performance purposes.
EDIT: Did a trace of the flow using HttpWatch and found out that javax.faces.ViewState is taking up 18kB of the total 22kB of size of the POST request. So my aim is narrowed down to reducing the size of ViewState. Any way to I can do this ?
State saving only keeps the data associated with the current view. Your problem here is that the session scoped beans are lost. I suggest two ways of solving the problem:
1) Implement a HttpSessionListener and in its sessionDestroyed() method get the beans, serialize them and store them in a database row associated with the current user. When the user logs in again you can fetch the beans, deserialize them and put them in the user's session.
2) Implement ajax poll that will ping the server in a specific period and this way the session will not timetout. You could achive this using Richfaces JSF library that has a built-in JSF component for ajax poll.

How do backing bean scopes work?

I have some misunderstanding with JSF backing bean scope. I am new to JSF and now writing a simple project and all my beans mostly have session scope. But if my site will have many users that means my session will be very very big and kill my server. Some people have told me that the solution is use request scope beans. But, for example, when my page must be validated and if validation is failure show error messages and save all user input, what can I do in this situation? I am trying use component that use AJAX-request and hoped that my request bean will be not reconstructed, but this doesn't work (I am using <rich:datascroller> ).
I think I have big hole in my JSF understanding, I will be grateful if somebody explain what I must do in this situation or link me on some good article about bean scopes.
Scope defines the lifetime of the beans.
Request scope beans live during the servicing of one HTTP request, so thay are available both while you analyze the user's input and formulate the response page. So for simple validation and response I'd expect request-scoped beans to be what you need - the exception being perhaps if you send a redirect back to the browser and that submits a new request, then you may need ...
Session scoped beans live for the life of the user's session, ie. across several requests. Sessions might last for some time, but eventually the user logs out, or becomes quiscent and his session gets timed-out. So it doesn't matter how many users overall you have, just how many are active at once. It's pretty common to keep some session data around for each user (like at least who is, and perhaps his recently viewed stuff) so there's no fundamental reason to be worried by some data being kept. You just need to ensure you keep it tidy, don't keep the data for old pages very very long - perhaps just a "current data" bean or some such.

Resources