Is it good to use request scoped bean with ajax validation? - jsf-2

Let's say I have a form with ten input fields, and each of them has AJAX validation. Can I still use a Request scoped backing bean, or should I use View scoped to keep the page performant? Is it too expensive to recreate the backing bean on each validation request, if there are not too many DB queries? Are there any guidelines when to use View scoped bean in a situations like this?

You should use View scoped beans.
Unless you have a reason to do otherwise, using Request scope will be confusing: page state is not preserved between trips to the server. Using View scope will make your page behave the same way you think about the page: requests go to the server, responses come back, the page saves its state as long as the user does not navigate away from the page.
With 10 input fields, your performance overhead should be negligible. Depending on your application, performance might even improve (!)
As suggested in the comments, if you have serious performance concerns, run a profiler. Convince yourself that what you are doing is correct.
Here are some guidelines on which scope to choose:
How to choose the right bean scope?

Related

Session State between Pages in MVC

besides TempData, which I believe isn't the best thing to use nowdays, what are some best practices in how you can persist user data from page to page?
Do you usually just go back to the DB every time...ajax or not...do you make a request every time or do you store it in lets say the Request object or some other in process object instance?
I'm just looking for a broad range of ideas as I am overwhelmed with looking this up on the net...there's a LOT out there and it would be easier for me to get some insight via stack as well.
There are several options. If we're talking about intrarequest, then of course ViewBag is the best choice. Intrapage (across requests) then the best choice is probably hidden fields, unless it's sensitive data.
Between pages, then there are several options. You can of course pass data as query string parameters. Session also makes a convenient option, so long as the data size is small, and it's ok if the session gets lost (ie, you can get it again or regenerate it). In certain other situations, you can post data to another page using hidden fields, but this should largely be discouraged since you should prefer to use PRG (Post/Redirect/Get) pattern.
Some other options are using the context cache HttpContext.Cache (Which i feel is misnamed, but oh well) or saving it in temporary tables in the database. Any "in-memory" option will have scalability issues if you decide to move to a web farm (Session can be made to be backed by database, but it slows things down).
It also depends on what data you're talking about. If it's user data, then another option is to store it in a cookie, or to use the user data portion of the Forms Authentication cookie, and create a custom IIdentity object.
Finally, there's just rebuilding the data from its source on every request.

EJB3 / JSF2: Design of JSF2 app with ConversationalScope and Stateful EJB

My use case is as follows:
Managing orders with order lines, a customer and payment details.
The app consists of an order list view from which an order detail view can be opened for editing an existing order or creating an new order. The order detail view uses a view param (existing order id or nothing to indicate a new order to be created).
When the order detail view is opened an OrderControllerBean is starting a ConversationalScope and depending on the availability of the order id loading or creating a new order entity. This bean is a stateful session bean as well meant to be used as a facade. The bean contains methods for handling order lines, the customer and the payment details as well as saving and deleting an order. These methods use injected EJBs which are designed as stateless session beans as some kind of DAOs to handle the JPA entities order, order line, customer and payment detail.
From the order detail view with customer info, payment info and order line list the user can navigate to the order line detail view adding/editing order lines and to the customer and payment detail view in a similar manner. Those detail views all use the same OrderControllerBean. On the customer, order line and payment detail views there are Ok and Cancel buttons which are not transactional.
On the order detail view there is a Save and Cancel button which should persist all modifications which are done during the conversation.
The question i have now is: is this design suitable and ok?
I am not sure about the following issues:
What happens if the user never use Save or Cancel?
Does everything stay around till the conversion or the session times out?
What does this mean from the transaction perspective?
What does this mean for the managed entities?
What happens if the user leaves his worksplace and comes back later continuing work on the conversation? If the conversation is timed out, how can i gracefully handle this issue?
Stateful beans are a pain and a source of problems in my opinion.
It's better if you handle timeouts at the http session level, rather than givin this responsibility to the Application server (specially since the http session timeout is still relevant you just add another timeout)
You can replace the persitent state provided by the stateful bean with some kind of object caching or if you prefer you can add a sessionid to the database and keep track of your objects states there (it can be special tables to hold temporary objects until saved or discarded for example).
All in all, keep things apart, timeout and temporary objects on the web server side, and use the ejbs for persistence (JPA) and as a facade (stateless beans)
Why do you need to evaluate the either/or situation in creating orders? There should simply be a button that says : New Order that launches a popup form and another, possibly from a datatable row that says "View Order Details".
The design is fine. Just a few tweaks.
You'll want to create and maintain a single session scoped object(call it Visit) in which you store all session related material. I'd advise you stick with the JSF session scoped bean that is dependent on the http session and can be effectively managed by the container. JSF Session Scoped beans are stored as simple objects in the http session and so can be easily manipulated outside the context of JSF. CDI Session Scoped beans however are trickier to handle outside of CDI.
I'll also advise you break up your order creation process into a multi-step process using dynamically loaded page fragments <ui:include/> or the fine primefaces wizard component. With a multi-step creation, all you need to do is gather data along the steps and only commit a transaction when you've all the info you need from all the steps in a DTO. Keep the wizard DTO in the single session object so the container can cleanup in case of a timeout. If the user never saves or cancel or walks away from his desk, the session will die a natural death. And he can come back and continue his transaction if he makes it in time. Not sure what carlos has against stateless session beans but in my experience, they're a nice way of exposing business processes, in that they can expose their functionality in other ways like webservices and message targets (JEE5). Above all, it's very good design to keep as much business processing out of the managed beans as possible and into durable constructs like EJBs and Spring beans etc.

Struts2 and multiple active wizards / workflows

I'm currently working on a Struts2 application that integrates a wizard / workflow in order to produce the desired results. To make it more clear, there is a business object that is changed on three different pages (mostly with AJAX calls). At the moment I'm using a ModelDriven action (that's extended by all the actions working with the same business object) coupled with the Scope interceptor. While this works okay if the user is handling data for only one business object at a time, if the user opens the wizard for different objects in multiple tabs (and we all do this when we want to finish things faster) everything will get messy, mostly due to the fact that I have only one business object stored in the session.
I have read a few articles about using a Conversation Scope Interceptor (main article) and about using the Scope plug-in (here). However, both approaches seem to have problems:
the Conversation Scope Interceptor doesn't auto-expire the conversations, nor does it integrate properly with Struts2;
the Scope plug-in lacks proper documentation and the last build was made in 2007 (and actually includes some of the ideas written by Mark Menard when he defines his Conversation Scope Interceptor, though it doesn't use the same code).
Spring's WebFlow plug-in seems a bit too complex to be used at the moment. I'm currently looking for something that can be implemented in a few hours time, though I don't mind if you can suggest something that works as needed, even if it requires more time than I'd currently want to spend on this now.
So, seasoned Struts2 developers, what do you suggest? How should I implement this?
Okay this isn't a fully baked idea. But seeing as no else has provided anything, here is what I would start with.
1) See if you can move the whole flow into a single page. I'm a big believer in the less pages is better approach. It doesn't reduce complexity for the application at all, but the user generally finds the interface a lot more intuitive. One of the easiest ways to go about this is by using the json plugin and a lot of ajax calls to your json services.
2) If you must transition between pages (or simply think it is too much client side work to implement #1) then I'd look to the s:token tag. The very first page to kick off a flow will use this tag, which will create a unique value each invocation. You will store a map in your session of model objects. An action will need to be provided with a model by looking it up from the session.
There are a couple challenges with #2. One how do you keep the session from getting too many domain objects? a) Well it might not matter, if the session is set to say six hours you can be rather sure that over night they will get cleared up. b) provided a self management interface which can get/set/list objects in the session. It might be what you thought of at first but it would let a worker do a certain amount and then stop and work on another. If the unit of work has some meaningful name (an invoice number or whatever) it could be quite useful.
A little more sophistication would be to move the model objects out of the session and into the service layer. At which point when inserted you would set an insertion time. You would probably need a manager to hold each type of model object and each manager would have a daemon thread that would periodically scan the map of domain objects and clean out expired ones.
You can figure out more complicated system by kicking a flow off with a token and then using another token on each page. "flowId" and "currentPageId" respectively, then you can graph allowable transitions.
Mind you at this point spring web flow is starting to look pretty good.
There is now a conversation plugin for Struts2 that achieves all these goals with very little work required by the developer: http://code.google.com/p/struts2-conversation/
It has:
-nested conversations
-cleanup of dead conversations
-convention over configuration with annotations and naming conventions
-inherited conversations
-fully integrated with Struts2
-the conversation scope can also be used by Spring IoC container-managed beans
Hope it helps somebody.

JSF 2 Handling Data

I'm developing an app with JSF2 in Tomcat. Still pretty fresh to JSF I have a question which I guess is pretty simple to answer to someone who's got fairly good experience developing web aps and specifically in JSF 2. It's about the way one should store user's data during their interaction with the application. As it stands right now I am saving a lot of data in a session scoped managed bean (like collection of earlier pulled from database entities which themselves are linked to other entities) and whenever a request is made the application will serve anyone of those objects stored in that collection. But I am worried that the session bean is becoming over bloated and don't know how much memory it is safe for a single session bean to consume. What I don't know is whwther when the app goes into production, and a lot of users log, is then the server gonna be ok to handle it. So I guess my question is as follows.
Is there any rule to go buy about storing, handlind and serving large amounts of users data that comes from the database:
Is it ok to do it my way (that is store a lot of stuff in a session scoped bean) so that with each request the app doesn't nee to query and retrieve the data from database. And it that's the case how to best load entities linked to an object stored in a list so they are not all loaded at once but only after the actual object is used to perform some operations before sending the data to the user.
Or should the app keep session beans fairly light (no lists of pre-pulled enities, objects etc) and instead make a trip to the database every time a larger piece of data is required, retrieve it and serve on the fly?
Or perhaps there's an entirely different method, preferred or recommended, to do this.
All suggestions and help are very much appreciated.
You should definitely not do the entity caching job by a JSF session scoped bean. You should delegate the entity caching job to the persistence layer and configure/finetune it over there. JPA and Hibernate for example have pretty good caching support. Here are some articles to read about it:
Javalobby - JPA Caching
EclipseLink Examples - JPA Caching
Hibernate Reference - Chapter 21 - Improving performance
A JSF session scoped bean should merely just contain session scoped data which is used in every request of the webapp throughout the entire browser session. For example, the logged-in user, the user preferences, the user language/locale, etcetera.
The (form) data should just be represented by a JSF request or view scoped bean. Just call the database on every fresh new request or view and do not worry about the costliness of the database trips in your JSF backing bean. Let the persistence layer worry about it.

ASP.NET MVC ,Maintaining Model State between Ajax requests

problem:
On first full page request, my controller invokes an applicationServices Layer (Web Service Proxy to my business tier) in order to populate a collection of current services that is stored in my own controller base class property. This is then to be displayed within a view.
Everything within the context of that controller has access to this "Services Collection". Now when i make further calls to the same action method via an AJAX Call, i obviously hitt a different instance of that controller meaning my services collection is empty.
So other than re-getting the whole collection again, where would i store this collection so it gets persisted between ajax requests? Should i persist it as a seperate DomainModel Object, Session object?....as ViewData is not working for me obv. Excuse my MVC ignorance :)
Any help would be greatly appreciated :)
The web is essentially stateless and MVC helps you to go down to the metal, that is, MVC does not try to make something stateful that isn't, which is mostly the path of ye olde ASP: Each request is a request of it's own and it shouldn't know anything about any other request that has been performed in the past.
I feel it is easiest to go down exactly that route, because it it tends to stay clean, fast and helps you in adhering to best practices such as separation of concerns.
AJAX takes this a step further: The idea of AJAX is that a simple 'delete' operation can be implemented as such, i.e. you only need to authorize and perform one very small query on the persistence layer. That's it. You don't even need to pass a modified page back to the user. A simple machine-readable success/error indication via JSON is sufficient.
If you start to pull lots of services around for small AJAX requests, you really lose most of what it's good for.
I'd also suggest you don't store a bunch of services in a base controller. Chances are that for most requests, you will only need a small subset of these. It's best practices to retrieve only those service you absolutely positively need.

Resources