I have a Java EE application consisting of 1 web module and 1 EJB module. Inside my EJB module I have a stateful session bean containing my business logic.
What I would like is:
When a user logs in to my web application and creates a new session in the web tier I want that user to be assigned an instance of my session bean.
At the moment a session is being created in the web tier as expected but I am unsure about how to map the session in the web tier to a new EJB session each time. Currently I am invoking my EJB from my Servlet meaning that only 1 instance of the bean is being created. I am trying to get a 1-1 mapping between web sessions and sessions in my EJB layer.
I know this could be achived easily using application clients but any advice / design patterns on how I could achive this in the web tier would be greatly appreciated.
Stateful Sessions are not always a good choice, sometimes using persistence to a DB is easier.
In the servlet, as process a request from a user, obtain the "handle" to your SFSB. Put that "handle" into your HttpSession. Now when the next request for that user arrives you have the handle ready.
With EJB 3.0 do it like this.
Declare the bean reference with #EJB at class scope, this sets up the reference you'll use later
#EJB
(name=“CounterBean", beanInterface=Counter.class)
public class MyStarterServlet …
When you process the request: access the EJB using JNDI and the declared bean name, note that this code is in your doGet() and/or doPost() method, the "counter" variable must be local (on the stack), as the servlet object is shared between potentually many requests a the same time.
Context ctx = new InitialContext();
Counter counter = (Counter)
ctx.lookup(“java:comp/env/CounterBean”);
counter.increment();
Store the interface in the HttpSession object to retrieve as needed
session.setAttribute(“counter”, counter);
Related
I noticed that there are different bean scopes like:
#RequestScoped
#ViewScoped
#FlowScoped
#SessionScoped
#ApplicationScoped
What is the purpose of each? How do I choose a proper scope for my bean?
Introduction
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
#Request/View/Flow/Session/ApplicationScoped
A #RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A #ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A #FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A #SessionScoped bean lives as long as the established HTTP session. An #ApplicationScoped bean lives as long as the web application runs. Note that the CDI #Model is basically a stereotype for #Named #RequestScoped, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use #RequestScoped for simple and non-ajax forms/presentations. Use #ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use #FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use #SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use #ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an #ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a #SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a #RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a #ViewScoped bean for request, session or application scoped data, and abusing a #SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively #RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via #ManagedProperty in case of JSF managed beans or #Inject in case of CDI managed beans.
See also:
Difference between View and Request scope in managed beans
Advantages of using JSF Faces Flow instead of the normal navigation system
Communication in JSF2 - Managed bean scopes
#CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports #CustomScoped and #NoneScoped, which are rarely used in real world. The #CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.
The JSF #NoneScoped and CDI #Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a #NoneScoped or #Dependent is injected in a #SessionScoped, then it will live as long as the #SessionScoped bean.
See also:
Expire specific managed bean instance after time interval
what is none scope bean and when to use it?
What is the default Managed Bean Scope in a JSF 2 application?
Flash scope
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as #FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.
See also:
How to show faces message in the redirected page
Pass an object between #ViewScoped beans without using GET params
CDI missing #ViewScoped and #FlashScoped
Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using #ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.
From JSF 2.3 here are scopes that can be used on JSF Backing Beans:
1. #javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.
2. #javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.
3. #javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.
4. #javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.
5. #javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.
6. #javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.
The following legacy answer applies JSF version before 2.3
As of JSF 2.x there are 4 Bean Scopes:
#SessionScoped
#RequestScoped
#ApplicationScoped
#ViewScoped
Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates
if the web application invokes the invalidate method on the
HttpSession object, or if it times out.
RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back
to the client. If you place a managed bean into request scope, a new
instance is created with each request. It is worth considering request
scope if you are concerned about the cost of session scope storage.
ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all
requests and all sessions. You place managed beans into the
application scope if a single bean should be shared among all
instances of a web application. The bean is constructed when it is
first requested by any user of the application, and it stays alive
until the web application is removed from the application server.
ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF
specification uses the term view for a JSF page.) As soon as the user
navigates to a different page, the bean goes out of scope.
Choose the scope you based on your requirement.
Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54]
Is there any relationship between stateful session bean and HTTP session ?
What are the use cases where we would require a stateful session bean and what use cases requires HTTP Session.
Can i expose a stateful session bean as a restful web service ?
HTTP is a stateless protocol Which means that it is actual transport protocol between the server and the client -- is "stateless because it remembers nothing between invocationsNow First read this what is HTTPSession and what is Session Bean (keep in mind that session beans are use to maintain the data state across multiple request so mostly a session bean is a stateful session bean because it holds data across whole session)
HTTP Session
An HttpSession object can hold conversational state across multiple requests from the same client. In other words, it persists for an entire session with a specific client.
We can use it to store everything we get back from the client in all the requests the client makes during a session.
Session Bean from wiki
In the Java Platform, Enterprise Edition specifications, a Session Bean is a type of Enterprise Bean.A session bean performs operations, such as calculations or database access, for the client. Although a session bean can be transactional, it is not recoverable should a system crash occur. Session bean objects either can be stateless or can maintain conversational state across methods and transactions. If a session bean maintains state, then the EJB container manages this state if the object must be removed from memory. However, the session bean object itself must manage its own persistent data.
In Simple words
Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page. It requires some work on the part of the Web developer since there's no built-in mechanism for it. The connection from a browser to a Web server occurs over the stateless Hypertext Transfer Protocol (HTTP) AND
SFSB's are designed for managed client state over multiple calls to the same session bean (i.e. a conversation). If you look at JBoss Seam, you will see that there is very heavy use of SFSB's for conversation context.In EJB3, there is no such thing as "stateless is better than stateful session beans". For example, one provides a service like a credit card processor (stateless) and one provides processing for a multi-screen wizard use case (stateful). In My opinion Managing state using HttpSession and stateless session beans is very difficult and problematic.
EDIT: HTTPSession is use to keep the session tracking like A user sessionFor example You want to create a Login , Logout mechanism then You must need the HTTPSession because when The user will start navigation between different pages then this HTTPsession will remember that WHO is asking for the pages otherwise it is not possible(because HTTP is a stateless protocol) Now In session you just set the session of username and password and you are checking on every page that if this session exists then show the pageNow what if , You have to send a lot of information of this user across multiple requests? In this scenario, You will set all this info in a Stateful session bean But now a days , In modern frameworks session as well as information , everything is stored in Session beans because From session bean it is easy to manage them. HTTPSession was used when we were purely on Servlet and somehow JSP technologies
I have created Webservice using JAXWS and hosted it as stateless session bean in jboss6.
Following is the web service code:
#Stateless
#WebService(serviceName = "CommonSmsServices", name = "CommonSmsServices", wsdlLocation = "META-INF/wsdl/CommonSmsServices.wsdl", endpointInterface = "com.sms.webservice.common.CommonServices")
public class CommonServicesImpl implements CommonServicesLocal,CommonServicesRemote {
//.....
// methods
//.....
}
This works fine with a single Http session. Now I am facing the problem while running multiple sessions, that the response time becomes very slow.
I did YourKit porfiling for memory and threading sampling. Memory utilization look good. but in thread section it shows one htpp thread is waiting for other to complete.
I have also gone through the Java EE session bean documentation. It says session bean are single threaded. Is there a performance issue with session beans that handle multiple Http session concurrently?
Is there a way or configuration in JBoss AS 6 to improve my web service performance?
In an EJB (including Stateless ones) multithreading is supported by the container. If you want your data to be stored between to distinct calls you probably should use a Statefull bean instead; this also supports multithreading.
I want to handle a login scenario as follows:
Client connects to a Stateless Java Bean (SLJB) and tries to login;
If login succeeds, the SLJB returns to the user a Stateful Java Bean (SFJB), so that the client can continue using the application.
I am currently doing the second step as:
return new StatefulBean(some params);
Is this the right way to do it? It does not seem to me as I get the exception:
Class org.eclipse.persistence.internal.jpa.EntityManagerImpl is not Serializable
when running my application, and I think it is related to the described method.
What would be the correct way to return a reference to the SFJB from the SLJB to the client?
First of all, this is completely wrong:
new StatefulBean(some params)
EJB container is responsible for creating and destroying instances of beans, you should never create them manually.
In your scenario I would reverse the flow: the client connects to the stateful bean which might stateless session bean as a helper. No need to pass beans around, client always uses the same bean.
As Tomasz mentions, you probably need to rethink your flow.
That said, you can get a hold of a new stateful instance by doing a JNDI lookup, using the portable JNDI name that us assigned to each bean at startup.
This is not a simple question its just because i'm rethinking our architecture for securing our EJB 3.0 service by a login and security.
We have a EJB3.0 application on JBoss 5.1 that offers various services to a SWT client to read and write data. To use a service, the client must login with a valid user and password which is looked up by SpringSecurity in a LDAP server. SpringSecurity generates a session id which is passed back to the client to be resused in any further service call.
client server
| |
|-> login(user/password)-------->|
| |
| <------- sessionId ------------|
| |
|-->serviceXy(sessionId,param1)->|
The situation seems clear. We store the sessionId in our own context object which is the first parameter of each service method. There is an interceptor on each service method which reads the sessionId from the given context object and checks if the session is still valid. The client needs to call the login service first to get a context object filled with the sessionId and reusue this context object in further service calls.
public class OurContext {
private String sessionId;
}
#Stateless
#Interceptors(SecurityInterceptor.class)
public OurServiceImpl implements OurService {
public void doSomething(OurContext context, String param1) {
[...]
}
}
The thing i don't like at this solution is the polution of each service method with the context parameter.
Isn't there a similar mechanism like a http session in rmi calls? I'm thinking of putting our context object in some kind of session that is created in the client(?) right after the login and is passed to the server on each service call so that the SecurityInterceptor can read the sessionId from this "magic context".
Something like this:
OurContext ctx = service.login("user","password");
Magical(Jboss)Session.put("securContext", ctx);
service.doSomething("just the string param");
Since you are already using an app server, it seems that you should be using the built-in EJB security mechanisms, generally provided through JAAS. On the 4.x jboss line, if you implemented your own JAAS plugin for jboss, you could get access to a "special" context map (similar to what you describe) which is passed along on remote requests (by the jboss remote invocation framework). I haven't used jboss in a while, so not sure how this maps to the 5.1 product, but i have to imagine it has similar facilities. This assumes, of course, that you are willing to implement something jboss specific.
There are some kinds of session mechanisms in EJB, but they all start when the remote call starts, and ends when that ends. On old one is the transaction context ( Adam Bien wrote about this some time ago), and a newer one the CDI Session Scope.
Contrary to popular belief, this scope doesn't just mirror the http session scope, but in absence of an http session (like for remote calls), it represents a single call chain or message delivery (for mdbs).
With such a session, your remote SWT client still has to pass the sessionId to the remote service, but any local beans called from there can pick it up from this "cdi" session.
The other option is kinda like what jtahlborn says: with your own login module you can return a custom principal, instead of the default one. Your code can first request the normal principal and then try to cast it.
The problem is that this stuff is container specific and JBoss always forgets about it. It pretty much breaks after every update, and users have to kick and scream to get it fixed in some next version (only to see it break again in the version after that). Without JBoss really supporting this it's an endless battle.
Yet another option is to let the user login with the sessionId as name. The login module behind that could be a simple module that accepts everything and just puts a principal in the security context with the sessionId as 'name'. It's a little weird, but we've used this succesfully to get any data that can be expressed by a string into the security context. Of course, you would need to let your client do a regular container authentication here, which kinda defeats using Spring security in the first place.
We went for another approach which is portable and does not rely on a specific app server. In addition our security implementation frees us from the restrictions of the EJB approach (which by the way I thought were closed 2 decades ago ... but came up again).
Looking top down:
There is a server providing classes with methods to work on same data.
The client(s) provide the data and invoke specific methods.
Our approach is to put all data (and therefore communication between client and server) into a "Business Object". Every BO extends a superclass. This superclass contains a session id. The login method provides and returns that id. Every client only has to ensure to copy the id received in one BO into the next one it sends to the server. Every method which can be remotely (or locally) invoked, first obtains the session object with the received id. The method to return the session object also checks security constraints (which are based on permissions and not on roles like in the EKB approach).