How session sets and unsets in JSF2.0 - session

I want to know about setting and un-setting the session in JSF2.0. Although following some blogs and books (Core JavaServer Faces-3rd Edition), i got to know that using annotation #SessionScoped we can set any manage bean to be in session. I have a loginBean which is #ManagedBean and SessionScoped declared. On the top right corner, my web has login button.
When this session is created (i am not setting it manually, that is why i am confused) and when i gets destroyed? It must be destroyed either by time out or by clicking in logout button only.

JSF uses the Servlet API under the covers. A session scoped managed bean is in essence set as an attribute of the HttpSession. It will be created and set whenever the EL expression referencing the managed bean #{sessionBean} is evaluated for the first time. It will be "removed" from the session whenever the session expires (by either a restart of the client or a timeout in the server) or get invalidated. If you let your logout button call ExternalContext#invalidateSession(), then the session will be invalidated.
If you're familiar with the basic Servlet API, you should already understand how this all works. For an in-depth explanation of the Servlet's HttpSession works under JSF's covers, read this answer: How do servlets work? Instantiation, sessions, shared variables and multithreading.

In jsf 2.0 we can set total class ob as session like i mention
Class_name sm;
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext(); extContext.getSessionMap().put("Give name for access this property",sm);
Class_name sm = (Class_name) extContext.getSessionMap().get("Give name for access this property");

Related

Real World use case of bean scopes

I am learning Spring, I learned about bean scopes - what are the real world use cases for each of them, I am not able to get any help. please help when to use Singleton, Prototype , Request and Session scopes in Spring.
Singleton: It returns a single bean instance per Spring IoC container.This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. If no bean scope is specified in the configuration file, singleton is default. Real world example: connection to a database
Prototype: It returns a new bean instance each time it is requested. It does not store any cache version like singleton. Real world example: declare configured form elements (a textbox configured to validate names, e-mail addresses for example) and get "living" instances of them for every form being created
Request: It returns a single bean instance per HTTP request. Real world example: information that should only be valid on one page like the result of a search or the confirmation of an order. The bean will be valid until the page is reloaded.
Session: It returns a single bean instance per HTTP session (User level session). Real world example: to hold authentication information getting invalidated when the session is closed (by timeout or logout). You can store other user information that you don't want to reload with every request here as well.
GlobalSession: It returns a single bean instance per global HTTP session. It is only valid in the context of a web-aware Spring ApplicationContext (Application level session). It is similar to the Session scope and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are bound to the lifetime of the global portlet Session.

Stateless session bean maintaining state

I deployed a web application on the localhost GlassFish server. This application takes order information from user and stores it in a List type variable in a Stateless Session Bean.The list object is created in the constructor.
I open the order page and add multiple orders in it. When I open the show orders page in different tabs and different browsers, it displays all the order information bean correctly, as though the state is maintained in a Stateless Bean!
I think this behavior is wrong as each browser/tab should create different session with the server and new order information should be shown for each browser/tab. How can this behavior be explained?
Your use case is precisely what a stateful session bean is for, if you want your List object to be maintained across method invocations, and if you want each session to be assigned its own bean.
Stateless session beans are pooled and made available to any session. But your instance fields are not guaranteed to be cleared, so you can't depend on them being cleared. The behavior that you are seeing is not unexpected. Even if you were successful in creating separate sessions in multiple tabs, those sessions could very well have been (and apparently were) assigned the same session bean. That's because the associated method invocations occurred at different points in time. Now if the associated method invocations occurred simultaneously instead, then the platform would have assigned a different stateless bean to each invocation (session). In that case, you'd see different behavior.
See also;
conversational state of session beans
and
Stateless and Stateful Enterprise Java Beans
Never let what you can't do get in the way of what you can do.
Problem: Stateful Session Bean was not maintaining separate state per client. In the example I tried, I input orders from the JSP page, which were stored in a List in a Stateful Session Bean. When I called the same URL from a different browser (i.e. a different session), the list of orders input in the previous session were visible. The same EJB was getting referenced in both sessions. (Verified by sysouts)
It's like saying, the shopping cart of some other user was directly visible to me as if they were my orders!!
Solution: Used an HttpSessionListener and got the dependency of the Stateful EJB through JNDI, in sessionCreated(HttpSessionEvent se) method. Next, added the stateful EJB in an HttpSession and accessed the EJB through session in servlet.
Suggestions for using JNDI, instead of DI, for Stateful Session Bean and Adding EJB to HttpSession are given in the answer above. Don't know if it is the proper way to go, but it works!!

will org.jboss.seam.web.Session.invalidate destroys the EJB threads that are created by the xhtml's?

I am working on a weam web application where the once the user logs in, the main (or landing) page calls 4 stateful session beans. So once the user logs in, there will be atleast 4 threads of stateful session beans created. The page also has a logout button. The logout component in the xhtml calls a POJO which has a logout method.
In the logout method, the following statement is executed:
Session.instance().invalidate();
Now the question is, will the 4 threads/instances of the stateful session beans which are created when the user logs in will be destroyed or not.
I am running this application on JBOSS 4.2.3, Seam 2.2.1 Final
I am using JOSSO for authentication.
Yes, they're all part of the same session. You're actually creating session scoped beans, not separate sessions.
Easy enough to check though. Create a method in each of the session beans and annotate them with #Destroy, when the annotated bean is destroyed, it will call this method.
#Destroy
public void callMeWhenIDie(){
log.debug("I'm melting, I'm melting" + this.someDefiningCharacteristic);
}

Security SessionFixationProtectionStrategy interfering with session scoped beans

I'm using Spring 3.1.1.Release, Security 3.1.0.Release.
I've added login/logout to my web app, however a session scoped bean is not functioning the way it was. The bean is used to connect to a CMS called CMSConnector.
To authenticate users, I implemented an AuthenticationProvider, and in the authenticate() call, I get the session-scoped CMSConnector and call the CMSConnector.login(). If the CMS login fails, it fails the login.
THE PROBLEM -
If the login is success, #predestroy logout() is called immediately after the successful login. I then found it was the SessionFixationProtectionStrategy is invoking the invalidate the previous session and assign it a new session.
session.invalidate();
session = request.getSession(true); // we now have a new session
The invalidate() is calling the #predestroy method on the session-scoped bean.
So I have temporarily removed the the #predestroy annotation leaving the connection not closed. (VERY BAD PRACTICE.)
What is a work around to resolve the issue?
I tried to create a #PostConstruct and put the login process there, but the #PostConstruct doesn't get called when request.getSession(true) is called.
Thanks!
Jason
I think its not the SessionFixationProtectionStrategy but the ConcurrentSessionControlStrategy.
Set max-sessions="-1" for this code snippet
I did not solve my original question, but I implemented a workaround - expire session in the session expire object instead of attached with #predestroy.

Using a Stateful Session Bean to track an user's session

it's my first question here and I hope that I'm doing it right.
I need to work on a Java EE project, so, before starting, I'm trying to do something simple and see if I can do that.
I'm stuck with Stateful Session Beans.
Here's the question :
How can I use a SFSB to track an user's session?
All the examples that I saw, ended up in "putting" the SFSB into a HttpSession attribute.
But I don't understand why!
I mean, if the bean is STATEFUL, why do I have to use the HttpSession to keep it?
Isn't an EJB Container's task to return the right SFSB to the client?
I've tried with a simple counter bean.
Without using the session, two different browsers have the same counter bean (clicking on "increment" changed the value for both of them).
Using session, I have two different values, each for every browser (clicking on "increment" on Firefox, added one just to Firefox's bean).
But my teacher told that a SFSB keeps the "conversational state with a client", so why it doesn't just work without using a HttpSession ?
If I understood correctly , isn't using HttpSession with a SFSB the same of doing it with a SLSB instead?
I hope that my question(s) is clear and that my English is not that poor!
EDIT :
I'm working on a login system.
Everything goes fine and after completing the login it takes me to a profile page that show user's data.
But reloading the page makes my data disappear!
I've tried adding HttpSession while logging but doing in this way makes the data stay even after the logout!
A Stateful Session Bean (SFSB) has to be combined with the HTTP session in a web environment, since it's a pure business bean that itself knows nothing about the web layer.
Traditionally EJBs even mandatory lived inside their own module (the EJB module), that couldn't even access web artifacts if they wanted to. This is an aspect of layered systems. See Packaging EJB in JavaEE 6 WAR vs EAR for more information about that.
The original clients for Stateful Session Beans were among others Swing desktop applications, that communicated with the remote EJB server via a binary protocol. A Swing application would obtain a connection to a remote Stateful Session Bean via a proxy/stub object. Embedded in this proxy is an ID of some kind that the server can associate with a specific SFSB. By holding on to this proxy object, the Swing client can make repeated calls to it and those will go to the same bean instance. This will thus create a session between the client and the server.
In the case of a web application, when a browser makes an initial request to a Java EE web application it gets a JSESSIONID that the server can associate with a specific HTTPSession instance. By holding on to this JSESSIONID, the browser can provide it with each followup request and this will activate the same http session server-side.
So, those concepts are very similar, but they do not automatically map to each other.
The browser only gets the JSESSIONID and has no knowledge about any SFSB ID. Unlike the Swing application, the browser communicates with web pages, not directly with Java beans.
For mapping the client's request to a specific stateful session bean, the EJB container only cares about the ID provided via the SFSB proxy. It can't see if the call happened to originate from code in the web module and can't/shouldn't really access any HTTP contexts.
The web layer being the client code that accesses the SFSB must 'hold on' to a specific proxy reference. Holding on to something in the web layer typically means storing it in the HTTP session.
There is however a bridge technology called CDI that can make this automatic connection. If you annotate your SFSB with CDI's #SessionScoped and obtain a reference to the SFSB via CDI (e.g. using #Inject), you don't have to manually put your SFSB into the http session. However, behind the scenes CDI will do exactly that anyway.
You need to define the bean with #SessionScoped instead of #RequestScoped (if you are looking for HttpSession equivalent solution)
something like
#SessionScoped
public class SessionInfo implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Have a look at following (explained in detail)
http://www.oracle.com/technetwork/articles/java/cdi-javaee-bien-225152.html

Resources