Stateful Session Bean and HTTP Session - java

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

Related

Hibernate Contextual sessions

What's the difference between ManagedSessionContext and ThreadLocalSessionContext both has a ThreadLocal in their implementation for maintaining sessions
ThreadLocalSessionContext - It takes care of the hibernate session management activities like :
Creating a session if one doesn't already exist.
Binding the session to the ThreadLocal, so that sessionFactory.getCurrentSession() returns this bound session and unbinds it once the transaction is completed.
Flush and close the session at the end of transaction complete.
ManagedSessionContext - Responsibility of session management activities like above are handled by some external entity (generally some form of interceptor, etc).
In both the cases the session is stored in the ThreadLocal though.
But the call to bind/unbind of the session and especially when to call flush and close on the session are defined via the external entity.
This gives more flexibility, for example, in the case of ThreadLocalSessionContext, the session is closed automatically when the transaction ends and it is not possible to leave the session open for multi-request conversation type of requirements.
In case of ManagedSessionContext, we can implement multi-request conversation (a.k.a session-per-conversation model) the same session needs to be kept open and should be reused across the user requests. So in the first user request we insert/update/delete some entities and in the next request we do some more operations and finally at the end of third interaction we want to commit the data.
Quoting from Managing the current Session section
When a conversation starts, a new Session must be opened and bound with ManagedSessionContext.bind() to serve the first request in the conversation. You also have to set FlushMode.MANUAL on that new Session, because you don’t want any persistence context synchronization to occur behind your back.
All data-access code that now calls sessionFactory.getCurrentSession() receives the Session you bound.
When a request in the conversation completes, you need to call Managed-SessionContext.unbind() and store the now disconnected Session somewhere until the next request in the conversation is made. Or, if this was the last request in the conversation, you need to flush and close the Session.
To represent that pictorially,
Session scoping with ThreadLocalSessionContext
Session scoping implemented for Session-per-conversation using ManagedSessionContext
You can go through the Listing 11.5 of this link for a sample implementation an interceptor that manages the session for session-per-conversation model.

Bytearray in multithreaded environment in JSF [duplicate]

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]

Node.js stateful server

I am new to Node.js and server-side JS in general.
I am coming from Java EE and I am used to use stateful objects (not EJB, I am using CDI), for instance, for MVC.
My aim is to keep some data that is tied to e.g. a session.
CDI in Java EE knows the following state scopes:
Application scoped (= same as the singleton pattern)
Session scoped (state is kept for a user's session lifecycle, e.g. the logged in user)
Conversation scoped (state is kept for an identified conversation, e.g. a shopping cart)
Flash scoped (state is kept between two requests)
How to do all that stuff with Node without using a database, just using stateful objects?
You'll need something like connect to track session state for you as that is the least-trivial of these scopes. Once you have that you can do things as follows.
Application scoped (= same as the singleton pattern)
set a property on your HTTP server instance: myServer.totalRequestsServed = 0
or you can use a process-wide global: global.totalRequestsServed = 0
Session scoped (state is kept for a user's session lifecycle, e.g. the logged in user)
use the connect session middleware for this: req.session.user = myUser
Conversation scoped (state is kept for an identified conversation, e.g. a shopping cart)
I'm not totally clear on what you mean by "conversation scope" but I would stick this on the session user or in a shared hash object. session.user.shoppingCart = {}
Flash scoped (state is kept between two requests)
Use either the session or the request for this. There are existing modules in npm to give you helpers like req.flash("Welcome!"). See connect-flash for example.
Just like in the Java world, to be scalable, you'd need either server affinity or an external store for session data. Storing session scoped data on the server (as well as replicating it across all clones) is not scalable.
Server affinity can be arranged at infra level via a cookie. No change needed in the application.
External store support in NodeJS is available via the express-session middleware. It supports a number of session stores out of the box.

Generating Own Session Id in JSF

I have a web application in which we use JSF framework.
I have been diving deep into the security part for web application and hence I was looking to generate my own unique session ID(using encryption algorithm and assign it to every new session which gets created once user logs in.
Can anyone please guide me on how to set manual generated session id in session and ensure with each request that session id is transmitted.
Thanks.
I really doubt you'll generate session IDs that are more secure than the ones generated by the container, but here's what you could do, without using any container-specific extension.
Create a servlet filter which intercept every request to the server.
When a request comes in, check if a session already exists for this request (using getSession(false)). If one exists, then extract your specific cookie MY_SESSION_ID from the request, and compare its value to the one that is stored in the session. If they don't match, reject the request.
If the session doesn't exist, then create it (using getSession(true)), generate your super-secure session ID, store it as a session attribute and add the cookie MY_SESSION_ID to the response.
This has the disadvantage of creating a session automatically, even if it's not strictly needed. But that's the case most of the time when using JSPs of component frameworks.
Attempting to do this at the JSF application layer is unlikely to be successful; I would perform this task at a lower level API. I am assuming a servlet container.
I can think of two approaches:
do this at a container level via a server-specific SPI (if one even exists)
do this by rewriting requests/responses via a servlet Filter
There is insufficient information to comment on the viability of the first approach.
In the second, you would have to determine the name of the session cookie (it is usually JSESSIONID, but does not have to be). Your API would:
map the filter to all application requests
maintain a map of container session ids to "secure" ids
use the filter to rewrite any session cookie in the request with the session id
use the filter rewrite any session cookie in the response with the secure id
use a listener to remove invalid sessions from the map to avoid memory leaks

Java EE Session Management Between Web & EJB Tier

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);

Categories